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 <king-jan1999@hotmail.de>
  • Loading branch information
kingjan1999 committed Aug 1, 2018
1 parent adbcc5f commit 701e490
Show file tree
Hide file tree
Showing 33 changed files with 1,838 additions and 22 deletions.
9 changes: 8 additions & 1 deletion 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 Expand Up @@ -87,5 +94,5 @@ type swaggerRejectRequest struct {
type swaggerListHandledConsentRequestsResult struct {
// in: body
// type: array
Body []HandledConsentRequest
Body []HandledConsentRequestResponse
}
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
25 changes: 25 additions & 0 deletions consent/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,31 @@ 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:"-"`
}

// The response used to return handled consent requests
// same as HandledAuthenticationRequest, just with consent_request exposed as json
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
48 changes: 43 additions & 5 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": "The response used to return handled consent requests\nsame as HandledAuthenticationRequest, just with consent_request exposed as json",
"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 Expand Up @@ -3055,7 +3093,7 @@
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/acceptConsentRequest"
"$ref": "#/definitions/HandledConsentRequestResponse"
}
}
},
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**
> []HandledConsentRequestResponse 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

[**[]HandledConsentRequestResponse**](HandledConsentRequestResponse.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
Loading

0 comments on commit 701e490

Please sign in to comment.