Skip to content

Commit

Permalink
Generate and test sdk for listUserConsentSessions, add pagination
Browse files Browse the repository at this point in the history
Signed-off-by: Jan <[email protected]>
  • Loading branch information
kingjan1999 committed Aug 1, 2018
1 parent adbcc5f commit 31d14ba
Show file tree
Hide file tree
Showing 33 changed files with 1,830 additions and 20 deletions.
7 changes: 7 additions & 0 deletions consent/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ type swaggerRevokeUserClientConsentSessionsPayload struct {
Client string `json:"client"`
}

// swagger:parameters listUserClientConsentSessions
type swaggerListUserClientConsentSessionsPayload struct {
// in: path
// required: true
User string `json:"user"`
}

// swagger:parameters revokeAuthenticationSession
type swaggerRevokeAuthenticationSessionPayload struct {
// in: path
Expand Down
15 changes: 12 additions & 3 deletions consent/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/ory/fosite"
"github.com/ory/go-convenience/urlx"
"github.com/ory/herodot"
"github.com/ory/pagination"
"github.com/pkg/errors"
)

Expand Down Expand Up @@ -136,7 +137,7 @@ func (h *Handler) DeleteUserClientConsentSession(w http.ResponseWriter, r *http.

// swagger:route GET /oauth2/auth/sessions/consent/{user} oAuth2 listUserClientConsentSessions
//
// List all consent sessions of a user
// Lists all consent sessions of a user
//
// This endpoint lists all user's granted consent sessions, including client and granted scope
//
Expand All @@ -160,19 +161,27 @@ func (h *Handler) GetConsentSessions(w http.ResponseWriter, r *http.Request, ps
h.H.WriteError(w, r, errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Parameter user is not defined")))
return
}
limit, offset := pagination.Parse(r, 100, 0, 500)

sessions, err := h.M.FindPreviouslyGrantedConsentRequestsByUser(user)
sessions, err := h.M.FindPreviouslyGrantedConsentRequestsByUser(user, limit, offset)

if err != nil {
h.H.WriteError(w, r, err)
return
}

var a []HandledConsentRequestResponse

for _, session := range sessions {
session.ConsentRequest.Client = sanitizeClient(session.ConsentRequest.Client)
a = append(a, HandledConsentRequestResponse(session))
}

if len(a) == 0 {
a = []HandledConsentRequestResponse{}
}

h.H.Write(w, r, sessions)
h.H.Write(w, r, a)
}

// swagger:route DELETE /oauth2/auth/sessions/login/{user} oAuth2 revokeAuthenticationSession
Expand Down
2 changes: 1 addition & 1 deletion consent/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ type Manager interface {

VerifyAndInvalidateConsentRequest(verifier string) (*HandledConsentRequest, error)
FindPreviouslyGrantedConsentRequests(client string, user string) ([]HandledConsentRequest, error)
FindPreviouslyGrantedConsentRequestsByUser(user string) ([]HandledConsentRequest, error)
FindPreviouslyGrantedConsentRequestsByUser(user string, limit, offset int) ([]HandledConsentRequest, error)

// Cookie management
GetAuthenticationSession(id string) (*AuthenticationSession, error)
Expand Down
17 changes: 10 additions & 7 deletions consent/manager_memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

"github.com/ory/fosite"
"github.com/ory/hydra/pkg"
"github.com/ory/pagination"
"github.com/pkg/errors"
)

Expand Down Expand Up @@ -163,12 +164,11 @@ func (m *MemoryManager) VerifyAndInvalidateConsentRequest(verifier string) (*Han

func (m *MemoryManager) FindPreviouslyGrantedConsentRequests(client string, subject string) ([]HandledConsentRequest, error) {
var rs []HandledConsentRequest
filteredByUser, _ := m.FindPreviouslyGrantedConsentRequestsByUser(subject)
filteredByUser, _ := m.FindPreviouslyGrantedConsentRequestsByUser(subject, -1, -1)
for _, c := range filteredByUser {
if client != c.ConsentRequest.Client.GetID() {
continue
if client == c.ConsentRequest.Client.GetID() {
rs = append(rs, c)
}
rs = append(rs, c)
}
if len(rs) == 0 {
return []HandledConsentRequest{}, nil
Expand All @@ -177,7 +177,7 @@ func (m *MemoryManager) FindPreviouslyGrantedConsentRequests(client string, subj
return rs, nil
}

func (m *MemoryManager) FindPreviouslyGrantedConsentRequestsByUser(subject string) ([]HandledConsentRequest, error) {
func (m *MemoryManager) FindPreviouslyGrantedConsentRequestsByUser(subject string, limit, offset int) ([]HandledConsentRequest, error) {
var rs []HandledConsentRequest
for _, c := range m.handledConsentRequests {
cr, err := m.GetConsentRequest(c.Challenge)
Expand Down Expand Up @@ -214,8 +214,11 @@ func (m *MemoryManager) FindPreviouslyGrantedConsentRequestsByUser(subject strin
if len(rs) == 0 {
return []HandledConsentRequest{}, nil
}

return rs, nil
if limit < 0 && offset < 0 {
return rs, nil
}
start, end := pagination.Index(limit, offset, len(rs))
return rs[start:end], nil
}

func (m *MemoryManager) GetAuthenticationSession(id string) (*AuthenticationSession, error) {
Expand Down
9 changes: 5 additions & 4 deletions consent/manager_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ WHERE
return m.resolveHandledConsentRequests(a)
}

func (m *SQLManager) FindPreviouslyGrantedConsentRequestsByUser(subject string) ([]HandledConsentRequest, error) {
func (m *SQLManager) FindPreviouslyGrantedConsentRequestsByUser(subject string, limit, offset int) ([]HandledConsentRequest, error) {
var a []sqlHandledConsentRequest

if err := m.db.Select(&a, m.db.Rebind(`SELECT h.* FROM
Expand All @@ -378,14 +378,15 @@ WHERE
r.subject=? AND r.skip=FALSE
AND
(h.error='{}' AND h.remember=TRUE)
`), subject); err != nil {
LIMIT ? OFFSET ?
`), subject, limit, offset); err != nil {
if err == sql.ErrNoRows {
return nil, errors.WithStack(errNoPreviousConsentFound)
}
return nil, sqlcon.HandleError(err)
}

return m.resolveHandledConsentRequests(a)
aa, err := m.resolveHandledConsentRequests(a)
return aa, err

}

Expand Down
2 changes: 1 addition & 1 deletion consent/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ func TestManagers(t *testing.T) {
},
} {
t.Run(fmt.Sprintf("case=%d/subject=%s", i, tc.subject), func(t *testing.T) {
consents, _ := m.FindPreviouslyGrantedConsentRequestsByUser(tc.subject)
consents, _ := m.FindPreviouslyGrantedConsentRequestsByUser(tc.subject, 100, 0)

assert.Equal(t, len(tc.challenges), len(consents))

Expand Down
16 changes: 16 additions & 0 deletions consent/sdk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,16 @@ func TestSDK(t *testing.T) {

cr1, hcr1 := mockConsentRequest("1", false, 0, false, false, false)
cr2, hcr2 := mockConsentRequest("2", false, 0, false, false, false)
cr3, hcr3 := mockConsentRequest("3", true, 3600, false, false, false)
require.NoError(t, m.CreateConsentRequest(cr1))
require.NoError(t, m.CreateConsentRequest(cr2))
require.NoError(t, m.CreateConsentRequest(cr3))
_, err = m.HandleConsentRequest("challenge1", hcr1)
require.NoError(t, err)
_, err = m.HandleConsentRequest("challenge2", hcr2)
require.NoError(t, err)
_, err = m.HandleConsentRequest("challenge3", hcr3)
require.NoError(t, err)

crGot, res, err := sdk.GetConsentRequest("challenge1")
require.NoError(t, err)
Expand Down Expand Up @@ -113,6 +117,18 @@ func TestSDK(t *testing.T) {
_, res, err = sdk.GetConsentRequest("challenge2")
require.NoError(t, err)
require.EqualValues(t, http.StatusNotFound, res.StatusCode)

csGot, res, err := sdk.ListUserClientConsentSessions("subject3")
require.NoError(t, err)
require.EqualValues(t, http.StatusOK, res.StatusCode)
assert.Equal(t, 1, len(csGot))
cs := csGot[0]
assert.Equal(t, "challenge3", cs.ConsentRequest.Challenge)

csGot, res, err = sdk.ListUserClientConsentSessions("subject2")
require.NoError(t, err)
require.EqualValues(t, http.StatusOK, res.StatusCode)
assert.Equal(t, 0, len(csGot))
}

func compareSDKLoginRequest(t *testing.T, expected *AuthenticationRequest, got *swagger.LoginRequest) {
Expand Down
24 changes: 24 additions & 0 deletions consent/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,30 @@ type HandledConsentRequest struct {
// authorization will be remembered indefinitely.
RememberFor int `json:"remember_for"`

ConsentRequest *ConsentRequest `json:"-"`
Error *RequestDeniedError `json:"-"`
Challenge string `json:"-"`
RequestedAt time.Time `json:"-"`
AuthenticatedAt time.Time `json:"-"`
WasUsed bool `json:"-"`
}

// same as HandledConsentRequest, just with consent_request exposed via json used as response type
type HandledConsentRequestResponse struct {
// GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope`
GrantedScope []string `json:"grant_scope"`

// Session allows you to set (optional) session data for access and ID tokens.
Session *ConsentRequestSessionData `json:"session"`

// Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same
// client asks the same user for the same, or a subset of, scope.
Remember bool `json:"remember"`

// RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the
// authorization will be remembered indefinitely.
RememberFor int `json:"remember_for"`

ConsentRequest *ConsentRequest `json:"consent_request"`
Error *RequestDeniedError `json:"-"`
Challenge string `json:"-"`
Expand Down
46 changes: 42 additions & 4 deletions docs/api.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -1079,8 +1079,17 @@
"tags": [
"oAuth2"
],
"summary": "List all consent sessions of a user",
"summary": "Lists all consent sessions of a user",
"operationId": "listUserClientConsentSessions",
"parameters": [
{
"type": "string",
"x-go-name": "User",
"name": "user",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"$ref": "#/responses/handledConsentRequestList"
Expand Down Expand Up @@ -1761,6 +1770,38 @@
},
"x-go-package": "crypto/x509/pkix"
},
"HandledConsentRequestResponse": {
"description": "same as HandledConsentRequest, just with consent_request exposed via json used as response type",
"type": "object",
"properties": {
"consent_request": {
"$ref": "#/definitions/consentRequest"
},
"grant_scope": {
"description": "GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope`",
"type": "array",
"items": {
"type": "string"
},
"x-go-name": "GrantedScope"
},
"remember": {
"description": "Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same\nclient asks the same user for the same, or a subset of, scope.",
"type": "boolean",
"x-go-name": "Remember"
},
"remember_for": {
"description": "RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the\nauthorization will be remembered indefinitely.",
"type": "integer",
"format": "int64",
"x-go-name": "RememberFor"
},
"session": {
"$ref": "#/definitions/consentRequestSession"
}
},
"x-go-package": "github.com/ory/hydra/consent"
},
"IP": {
"description": "Note that in this documentation, referring to an\nIP address as an IPv4 address or an IPv6 address\nis a semantic property of the address, not just the\nlength of the byte slice: a 16-byte slice can still\nbe an IPv4 address.",
"type": "array",
Expand Down Expand Up @@ -1957,9 +1998,6 @@
"type": "object",
"title": "The request payload used to accept a consent request.",
"properties": {
"consent_request": {
"$ref": "#/definitions/consentRequest"
},
"grant_scope": {
"description": "GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope`",
"type": "array",
Expand Down
2 changes: 2 additions & 0 deletions sdk/go/hydra/swagger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Class | Method | HTTP request | Description
*OAuth2Api* | [**GetWellKnown**](docs/OAuth2Api.md#getwellknown) | **Get** /.well-known/openid-configuration | Server well known configuration
*OAuth2Api* | [**IntrospectOAuth2Token**](docs/OAuth2Api.md#introspectoauth2token) | **Post** /oauth2/introspect | Introspect OAuth2 tokens
*OAuth2Api* | [**ListOAuth2Clients**](docs/OAuth2Api.md#listoauth2clients) | **Get** /clients | List OAuth 2.0 Clients
*OAuth2Api* | [**ListUserClientConsentSessions**](docs/OAuth2Api.md#listuserclientconsentsessions) | **Get** /oauth2/auth/sessions/consent/{user} | Lists all consent sessions of a user
*OAuth2Api* | [**OauthAuth**](docs/OAuth2Api.md#oauthauth) | **Get** /oauth2/auth | The OAuth 2.0 authorize endpoint
*OAuth2Api* | [**OauthToken**](docs/OAuth2Api.md#oauthtoken) | **Post** /oauth2/token | The OAuth 2.0 token endpoint
*OAuth2Api* | [**RejectConsentRequest**](docs/OAuth2Api.md#rejectconsentrequest) | **Put** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request
Expand Down Expand Up @@ -70,6 +71,7 @@ Class | Method | HTTP request | Description
- [ExtKeyUsage](docs/ExtKeyUsage.md)
- [Extension](docs/Extension.md)
- [FlushInactiveOAuth2TokensRequest](docs/FlushInactiveOAuth2TokensRequest.md)
- [HandledConsentRequestResponse](docs/HandledConsentRequestResponse.md)
- [HealthNotReadyStatus](docs/HealthNotReadyStatus.md)
- [HealthStatus](docs/HealthStatus.md)
- [InlineResponse401](docs/InlineResponse401.md)
Expand Down
14 changes: 14 additions & 0 deletions sdk/go/hydra/swagger/docs/HandledConsentRequestResponse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# HandledConsentRequestResponse

## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ConsentRequest** | [**ConsentRequest**](consentRequest.md) | | [optional] [default to null]
**GrantScope** | **[]string** | GrantScope sets the scope the user authorized the client to use. Should be a subset of &#x60;requested_scope&#x60; | [optional] [default to null]
**Remember** | **bool** | Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope. | [optional] [default to null]
**RememberFor** | **int64** | RememberFor sets how long the consent authorization should be remembered for in seconds. If set to &#x60;0&#x60;, the authorization will be remembered indefinitely. | [optional] [default to null]
**Session** | [**ConsentRequestSession**](consentRequestSession.md) | | [optional] [default to null]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


30 changes: 30 additions & 0 deletions sdk/go/hydra/swagger/docs/OAuth2Api.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Method | HTTP request | Description
[**GetWellKnown**](OAuth2Api.md#GetWellKnown) | **Get** /.well-known/openid-configuration | Server well known configuration
[**IntrospectOAuth2Token**](OAuth2Api.md#IntrospectOAuth2Token) | **Post** /oauth2/introspect | Introspect OAuth2 tokens
[**ListOAuth2Clients**](OAuth2Api.md#ListOAuth2Clients) | **Get** /clients | List OAuth 2.0 Clients
[**ListUserClientConsentSessions**](OAuth2Api.md#ListUserClientConsentSessions) | **Get** /oauth2/auth/sessions/consent/{user} | Lists all consent sessions of a user
[**OauthAuth**](OAuth2Api.md#OauthAuth) | **Get** /oauth2/auth | The OAuth 2.0 authorize endpoint
[**OauthToken**](OAuth2Api.md#OauthToken) | **Post** /oauth2/token | The OAuth 2.0 token endpoint
[**RejectConsentRequest**](OAuth2Api.md#RejectConsentRequest) | **Put** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request
Expand Down Expand Up @@ -348,6 +349,35 @@ No authorization required

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **ListUserClientConsentSessions**
> []AcceptConsentRequest ListUserClientConsentSessions($user)
Lists all consent sessions of a user

This endpoint lists all user's granted consent sessions, including client and granted scope


### Parameters

Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**user** | **string**| |

### Return type

[**[]AcceptConsentRequest**](acceptConsentRequest.md)

### Authorization

No authorization required

### HTTP request headers

- **Content-Type**: application/json
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **OauthAuth**
> OauthAuth()
Expand Down
27 changes: 27 additions & 0 deletions sdk/go/hydra/swagger/handled_consent_request_response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server
*
* Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future.
*
* OpenAPI spec version: Latest
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/

package swagger

// same as HandledConsentRequest, just with consent_request exposed via json used as response type
type HandledConsentRequestResponse struct {
ConsentRequest ConsentRequest `json:"consent_request,omitempty"`

// GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope`
GrantScope []string `json:"grant_scope,omitempty"`

// Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope.
Remember bool `json:"remember,omitempty"`

// RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely.
RememberFor int64 `json:"remember_for,omitempty"`

Session ConsentRequestSession `json:"session,omitempty"`
}
Loading

0 comments on commit 31d14ba

Please sign in to comment.