Add identity-scoped OAuth token management
Let users create, list, and revoke manual bearer tokens from /me/oauth-tokens, scoped to their identity rather than an organization. Manual tokens store a null client_id and are authorized with a self-manage IAM policy. Wire Connect GraphQL on Identity (list, create, revoke), add console UI with scoped create flow and credentials dialog, and cover the flow in e2e tests. Fix list pagination ordering and keep the Relay connection in sync after create. Signed-off-by: Ludovic Vielle <ludovic@probo.com>
This commit is contained in:
19
pkg/coredata/migrations/20260617T120001Z.sql
Normal file
19
pkg/coredata/migrations/20260617T120001Z.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
-- Copyright (c) 2026 Probo Inc <hello@probo.com>.
|
||||
--
|
||||
-- Permission to use, copy, modify, and/or distribute this software for any
|
||||
-- purpose with or without fee is hereby granted, provided that the above
|
||||
-- copyright notice and this permission notice appear in all copies.
|
||||
--
|
||||
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
-- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
-- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
-- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
-- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
-- PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
ALTER TABLE iam_oauth2_access_tokens ADD COLUMN name TEXT;
|
||||
|
||||
UPDATE iam_oauth2_access_tokens SET name = 'OAuth grant' WHERE name IS NULL;
|
||||
|
||||
ALTER TABLE iam_oauth2_access_tokens ALTER COLUMN name SET NOT NULL;
|
||||
16
pkg/coredata/migrations/20260618T120000Z.sql
Normal file
16
pkg/coredata/migrations/20260618T120000Z.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
-- Copyright (c) 2026 Probo Inc <hello@probo.com>.
|
||||
--
|
||||
-- Permission to use, copy, modify, and/or distribute this software for any
|
||||
-- purpose with or without fee is hereby granted, provided that the above
|
||||
-- copyright notice and this permission notice appear in all copies.
|
||||
--
|
||||
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
-- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
-- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
-- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
-- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
-- PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
-- Manual console tokens are identity-scoped and have no OAuth2 client.
|
||||
ALTER TABLE iam_oauth2_access_tokens ALTER COLUMN client_id DROP NOT NULL;
|
||||
@@ -18,25 +18,40 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/iam/policy"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
)
|
||||
|
||||
type (
|
||||
OAuth2AccessToken struct {
|
||||
ID gid.GID `db:"id"`
|
||||
Name string `db:"name"`
|
||||
HashedValue []byte `db:"hashed_value"`
|
||||
ClientID gid.GID `db:"client_id"`
|
||||
ClientID *gid.GID `db:"client_id"`
|
||||
IdentityID gid.GID `db:"identity_id"`
|
||||
Scopes OAuth2Scopes `db:"scopes"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
ExpiresAt time.Time `db:"expires_at"`
|
||||
}
|
||||
|
||||
OAuth2AccessTokens []*OAuth2AccessToken
|
||||
)
|
||||
|
||||
func (t *OAuth2AccessToken) CursorKey(orderBy OAuth2AccessTokenOrderField) page.CursorKey {
|
||||
switch orderBy {
|
||||
case OAuth2AccessTokenOrderFieldCreatedAt:
|
||||
return page.NewCursorKey(t.ID, t.CreatedAt)
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("unsupported order by: %s", orderBy))
|
||||
}
|
||||
|
||||
func (t *OAuth2AccessToken) ExpiresIn(now time.Time) time.Duration {
|
||||
return t.ExpiresAt.Sub(now)
|
||||
}
|
||||
@@ -45,6 +60,7 @@ func (t *OAuth2AccessToken) Insert(ctx context.Context, conn pg.Tx) error {
|
||||
q := `
|
||||
INSERT INTO iam_oauth2_access_tokens (
|
||||
id,
|
||||
name,
|
||||
hashed_value,
|
||||
client_id,
|
||||
identity_id,
|
||||
@@ -53,6 +69,7 @@ INSERT INTO iam_oauth2_access_tokens (
|
||||
expires_at
|
||||
) VALUES (
|
||||
@id,
|
||||
@name,
|
||||
@hashed_value,
|
||||
@client_id,
|
||||
@identity_id,
|
||||
@@ -64,6 +81,7 @@ INSERT INTO iam_oauth2_access_tokens (
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"id": t.ID,
|
||||
"name": t.Name,
|
||||
"hashed_value": t.HashedValue,
|
||||
"client_id": t.ClientID,
|
||||
"identity_id": t.IdentityID,
|
||||
@@ -80,10 +98,48 @@ INSERT INTO iam_oauth2_access_tokens (
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *OAuth2AccessToken) LoadByID(ctx context.Context, conn pg.Querier, id gid.GID) error {
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
hashed_value,
|
||||
client_id,
|
||||
identity_id,
|
||||
scopes,
|
||||
created_at,
|
||||
expires_at
|
||||
FROM
|
||||
iam_oauth2_access_tokens
|
||||
WHERE
|
||||
id = @id
|
||||
LIMIT 1;
|
||||
`
|
||||
|
||||
rows, err := conn.Query(ctx, q, pgx.StrictNamedArgs{"id": id})
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot query oauth2_access_token: %w", err)
|
||||
}
|
||||
|
||||
token, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[OAuth2AccessToken])
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return fmt.Errorf("cannot collect oauth2_access_token: %w", err)
|
||||
}
|
||||
|
||||
*t = token
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *OAuth2AccessToken) LoadByHashedValue(ctx context.Context, conn pg.Querier, hashedValue []byte) error {
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
hashed_value,
|
||||
client_id,
|
||||
identity_id,
|
||||
@@ -125,6 +181,7 @@ func (t *OAuth2AccessToken) LoadByHashedValueAndClientID(
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
hashed_value,
|
||||
client_id,
|
||||
identity_id,
|
||||
@@ -163,6 +220,127 @@ LIMIT 1;
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *OAuth2AccessToken) AuthorizationAttributes(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
resourceIDs []gid.GID,
|
||||
) (policy.AttributesByID, error) {
|
||||
q := `
|
||||
SELECT
|
||||
t.id,
|
||||
t.identity_id
|
||||
FROM
|
||||
iam_oauth2_access_tokens t
|
||||
WHERE
|
||||
t.id = ANY(@resource_ids::text[])
|
||||
`
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"resource_ids": resourceIDs,
|
||||
}
|
||||
|
||||
rows, err := conn.Query(ctx, q, args)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot query oauth2 access token authorization attributes: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
attrsByID := make(policy.AttributesByID, len(resourceIDs))
|
||||
|
||||
for rows.Next() {
|
||||
var (
|
||||
id gid.GID
|
||||
identityID gid.GID
|
||||
)
|
||||
|
||||
err = rows.Scan(&id, &identityID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot scan oauth2 access token authorization attributes: %w", err)
|
||||
}
|
||||
|
||||
attrsByID[id] = policy.Attributes{"identity_id": identityID.String()}
|
||||
}
|
||||
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("cannot iterate oauth2 access token authorization attributes: %w", err)
|
||||
}
|
||||
|
||||
return attrsByID, nil
|
||||
}
|
||||
|
||||
func (ts *OAuth2AccessTokens) LoadByIdentityID(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
identityID gid.GID,
|
||||
cursor *page.Cursor[OAuth2AccessTokenOrderField],
|
||||
) error {
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
hashed_value,
|
||||
client_id,
|
||||
identity_id,
|
||||
scopes,
|
||||
created_at,
|
||||
expires_at
|
||||
FROM
|
||||
iam_oauth2_access_tokens
|
||||
WHERE
|
||||
identity_id = @identity_id
|
||||
AND client_id IS NULL
|
||||
AND %s
|
||||
`
|
||||
|
||||
q = fmt.Sprintf(q, cursor.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"identity_id": identityID,
|
||||
}
|
||||
maps.Copy(args, cursor.SQLArguments())
|
||||
|
||||
rows, err := conn.Query(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot query oauth2 access tokens: %w", err)
|
||||
}
|
||||
|
||||
tokens, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[OAuth2AccessToken])
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot collect oauth2 access tokens: %w", err)
|
||||
}
|
||||
|
||||
*ts = tokens
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ts *OAuth2AccessTokens) CountByIdentityID(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
identityID gid.GID,
|
||||
) (int, error) {
|
||||
q := `
|
||||
SELECT
|
||||
COUNT(id)
|
||||
FROM
|
||||
iam_oauth2_access_tokens
|
||||
WHERE
|
||||
identity_id = @identity_id
|
||||
AND client_id IS NULL;
|
||||
`
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"identity_id": identityID,
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := conn.QueryRow(ctx, q, args).Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("cannot count oauth2 access tokens: %w", err)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (t *OAuth2AccessToken) Delete(ctx context.Context, conn pg.Tx) error {
|
||||
q := `
|
||||
DELETE FROM iam_oauth2_access_tokens
|
||||
|
||||
78
pkg/coredata/oauth2_access_token_order_field.go
Normal file
78
pkg/coredata/oauth2_access_token_order_field.go
Normal file
@@ -0,0 +1,78 @@
|
||||
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"fmt"
|
||||
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
)
|
||||
|
||||
type OAuth2AccessTokenOrderField string
|
||||
|
||||
const (
|
||||
OAuth2AccessTokenOrderFieldCreatedAt OAuth2AccessTokenOrderField = "CREATED_AT"
|
||||
)
|
||||
|
||||
var (
|
||||
_ page.OrderField = OAuth2AccessTokenOrderField("")
|
||||
_ fmt.Stringer = OAuth2AccessTokenOrderField("")
|
||||
_ encoding.TextMarshaler = OAuth2AccessTokenOrderField("")
|
||||
_ encoding.TextUnmarshaler = (*OAuth2AccessTokenOrderField)(nil)
|
||||
)
|
||||
|
||||
func OAuth2AccessTokenOrderFields() []OAuth2AccessTokenOrderField {
|
||||
return []OAuth2AccessTokenOrderField{
|
||||
OAuth2AccessTokenOrderFieldCreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (v OAuth2AccessTokenOrderField) IsValid() bool {
|
||||
switch v {
|
||||
case OAuth2AccessTokenOrderFieldCreatedAt:
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (v OAuth2AccessTokenOrderField) String() string {
|
||||
return string(v)
|
||||
}
|
||||
|
||||
func (v OAuth2AccessTokenOrderField) MarshalText() ([]byte, error) {
|
||||
return []byte(v.String()), nil
|
||||
}
|
||||
|
||||
func (v *OAuth2AccessTokenOrderField) UnmarshalText(text []byte) error {
|
||||
val := OAuth2AccessTokenOrderField(text)
|
||||
if !val.IsValid() {
|
||||
return fmt.Errorf("invalid OAuth2AccessTokenOrderField value: %q", string(text))
|
||||
}
|
||||
|
||||
*v = val
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f OAuth2AccessTokenOrderField) Column() string {
|
||||
switch f {
|
||||
case OAuth2AccessTokenOrderFieldCreatedAt:
|
||||
return "created_at"
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("unsupported order by: %s", f))
|
||||
}
|
||||
@@ -151,7 +151,7 @@ func TestAuthorizer_AuthorizeBatch(t *testing.T) {
|
||||
Principal: fixture.identityID,
|
||||
Action: action,
|
||||
Resources: []gid.GID{
|
||||
gid.New(fixture.tenantID, coredata.OAuth2AccessTokenEntityType),
|
||||
gid.New(fixture.tenantID, coredata.OAuth2RefreshTokenEntityType),
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -159,7 +159,7 @@ func TestAuthorizer_AuthorizeBatch(t *testing.T) {
|
||||
|
||||
errUnsupported, ok := errors.AsType[*iam.ErrBatchAuthorizationUnsupportedResourceType](err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, coredata.OAuth2AccessTokenEntityType, errUnsupported.EntityType)
|
||||
assert.Equal(t, coredata.OAuth2RefreshTokenEntityType, errUnsupported.EntityType)
|
||||
})
|
||||
|
||||
t.Run("single deny rolls back entire batch", func(t *testing.T) {
|
||||
|
||||
@@ -91,7 +91,7 @@ func TestAuthorizer_InternalErrorPaths(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
identityID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
|
||||
unknownResourceID := gid.New(gid.NewTenantID(), 65535)
|
||||
unsupportedResourceID := gid.New(gid.NewTenantID(), coredata.OAuth2AccessTokenEntityType)
|
||||
unsupportedResourceID := gid.New(gid.NewTenantID(), coredata.OAuth2RefreshTokenEntityType)
|
||||
|
||||
a := &Authorizer{
|
||||
evaluator: policy.NewEvaluator(),
|
||||
@@ -156,7 +156,7 @@ func TestAuthorizer_InternalErrorPaths(t *testing.T) {
|
||||
require.Error(t, err)
|
||||
errUnsupported, ok := errors.AsType[*ErrBatchAuthorizationUnsupportedResourceType](err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, coredata.OAuth2AccessTokenEntityType, errUnsupported.EntityType)
|
||||
assert.Equal(t, coredata.OAuth2RefreshTokenEntityType, errUnsupported.EntityType)
|
||||
})
|
||||
|
||||
t.Run("build principal attributes keeps defaults when entity type is unknown", func(t *testing.T) {
|
||||
|
||||
@@ -94,6 +94,12 @@ const (
|
||||
ActionOAuth2ConsentGet = "iam:oauth2-consent:get"
|
||||
ActionOAuth2ConsentApprove = "iam:oauth2-consent:approve"
|
||||
|
||||
// OAuth2 Access Token actions
|
||||
ActionOAuth2AccessTokenCreate = "iam:oauth2-access-token:create"
|
||||
ActionOAuth2AccessTokenGet = "iam:oauth2-access-token:get"
|
||||
ActionOAuth2AccessTokenList = "iam:oauth2-access-token:list"
|
||||
ActionOAuth2AccessTokenDelete = "iam:oauth2-access-token:delete"
|
||||
|
||||
// Audit log entry actions
|
||||
ActionAuditLogEntryGet = "iam:audit-log-entry:get"
|
||||
ActionAuditLogEntryList = "iam:audit-log-entry:list"
|
||||
|
||||
@@ -42,6 +42,7 @@ var IAMSelfManageIdentityPolicy = policy.NewPolicy(
|
||||
ActionInvitationList,
|
||||
ActionSessionList,
|
||||
ActionPersonalAPIKeyList,
|
||||
ActionOAuth2AccessTokenList,
|
||||
).
|
||||
WithSID("list-own-associations").
|
||||
When(policy.Equals("principal.id", "resource.identity_id")),
|
||||
@@ -123,6 +124,21 @@ var IAMSelfManagePersonalAPIKeyPolicy = policy.NewPolicy(
|
||||
).
|
||||
WithDescription("Allows users to manage their own personal API keys")
|
||||
|
||||
// IAMSelfManageOAuth2AccessTokenPolicy allows users to manage their own OAuth2 access tokens.
|
||||
var IAMSelfManageOAuth2AccessTokenPolicy = policy.NewPolicy(
|
||||
"iam:self-manage-oauth2-access-token",
|
||||
"Self-Manage OAuth2 Access Tokens",
|
||||
|
||||
policy.Allow(
|
||||
ActionOAuth2AccessTokenCreate,
|
||||
ActionOAuth2AccessTokenGet,
|
||||
ActionOAuth2AccessTokenDelete,
|
||||
).
|
||||
WithSID("manage-own-oauth2-access-tokens").
|
||||
When(policy.Equals("principal.id", "resource.identity_id")),
|
||||
).
|
||||
WithDescription("Allows users to manage their own manually created OAuth2 access tokens")
|
||||
|
||||
// IAMSelfManageOAuth2ConsentPolicy allows users to manage their own OAuth2 consents.
|
||||
var IAMSelfManageOAuth2ConsentPolicy = policy.NewPolicy(
|
||||
"iam:self-manage-oauth2-consent",
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"go.probo.inc/probo/pkg/crypto/rand"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/net"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
"go.probo.inc/probo/pkg/uri"
|
||||
)
|
||||
|
||||
@@ -41,9 +42,10 @@ import (
|
||||
var CLIClientID = gid.MustParseGID("AAAAAAAAAAAASwAAAAAAAAAAcHJiY2xp")
|
||||
|
||||
const (
|
||||
tokenByteLength = 32
|
||||
refreshTokenByteLength = 48
|
||||
tokenTypeBearer = "Bearer"
|
||||
tokenByteLength = 32
|
||||
refreshTokenByteLength = 48
|
||||
tokenTypeBearer = "Bearer"
|
||||
oauthGrantAccessTokenName = "OAuth grant"
|
||||
|
||||
// userCodeAlphabet excludes ambiguous characters: 0/O, 1/I/L.
|
||||
userCodeAlphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
@@ -120,6 +122,14 @@ type (
|
||||
ExpiresAt time.Time
|
||||
TokenType string
|
||||
}
|
||||
|
||||
CreateManualAccessTokenRequest struct {
|
||||
IdentityID gid.GID
|
||||
Name string
|
||||
ExpiresAt time.Time
|
||||
Scopes coredata.OAuth2Scopes
|
||||
AllowedAPIScopes []coredata.OAuth2Scope
|
||||
}
|
||||
)
|
||||
|
||||
func WithAccessTokenDuration(d time.Duration) Option {
|
||||
@@ -221,8 +231,9 @@ func (s *Service) CreateAccessToken(
|
||||
now := time.Now()
|
||||
token := &coredata.OAuth2AccessToken{
|
||||
ID: gid.New(clientID.TenantID(), coredata.OAuth2AccessTokenEntityType),
|
||||
Name: oauthGrantAccessTokenName,
|
||||
HashedValue: hash.SHA256String(tokenValue),
|
||||
ClientID: clientID,
|
||||
ClientID: new(clientID),
|
||||
IdentityID: identityID,
|
||||
Scopes: scopes,
|
||||
CreatedAt: now,
|
||||
@@ -409,8 +420,9 @@ func (s *Service) ExchangeAuthorizationCode(
|
||||
func(ctx context.Context, tx pg.Tx) error {
|
||||
accessToken := &coredata.OAuth2AccessToken{
|
||||
ID: accessTokenID,
|
||||
Name: oauthGrantAccessTokenName,
|
||||
HashedValue: hash.SHA256String(accessTokenValue),
|
||||
ClientID: client.ID,
|
||||
ClientID: new(client.ID),
|
||||
IdentityID: code.IdentityID,
|
||||
Scopes: code.Scopes,
|
||||
CreatedAt: now,
|
||||
@@ -602,8 +614,9 @@ func (s *Service) RefreshToken(
|
||||
|
||||
accessToken := &coredata.OAuth2AccessToken{
|
||||
ID: gid.New(client.ID.TenantID(), coredata.OAuth2AccessTokenEntityType),
|
||||
Name: oauthGrantAccessTokenName,
|
||||
HashedValue: hash.SHA256String(accessTokenValue),
|
||||
ClientID: client.ID,
|
||||
ClientID: new(client.ID),
|
||||
IdentityID: previousRefreshToken.IdentityID,
|
||||
Scopes: previousRefreshToken.Scopes,
|
||||
CreatedAt: now,
|
||||
@@ -871,8 +884,9 @@ func (s *Service) PollDeviceCode(
|
||||
func(ctx context.Context, tx pg.Tx) error {
|
||||
accessToken := &coredata.OAuth2AccessToken{
|
||||
ID: gid.New(clientID.TenantID(), coredata.OAuth2AccessTokenEntityType),
|
||||
Name: oauthGrantAccessTokenName,
|
||||
HashedValue: hash.SHA256String(accessTokenValue),
|
||||
ClientID: clientID,
|
||||
ClientID: new(clientID),
|
||||
IdentityID: *deviceCode.IdentityID,
|
||||
Scopes: deviceCode.Scopes,
|
||||
CreatedAt: now,
|
||||
@@ -1230,8 +1244,13 @@ func (s *Service) IntrospectToken(
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var resultClientID gid.GID
|
||||
if accessToken.ClientID != nil {
|
||||
resultClientID = *accessToken.ClientID
|
||||
}
|
||||
|
||||
return &IntrospectResult{
|
||||
ClientID: accessToken.ClientID,
|
||||
ClientID: resultClientID,
|
||||
IdentityID: accessToken.IdentityID,
|
||||
Scopes: accessToken.Scopes,
|
||||
IssuedAt: accessToken.CreatedAt,
|
||||
@@ -1767,3 +1786,168 @@ func (s *Service) issueAuthorizationCode(
|
||||
|
||||
return codeValue, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetAccessTokenByID(ctx context.Context, accessTokenID gid.GID) (*coredata.OAuth2AccessToken, error) {
|
||||
token := &coredata.OAuth2AccessToken{}
|
||||
|
||||
err := s.pg.WithConn(
|
||||
ctx,
|
||||
func(ctx context.Context, conn pg.Querier) error {
|
||||
if err := token.LoadByID(ctx, conn, accessTokenID); err != nil {
|
||||
if errors.Is(err, coredata.ErrResourceNotFound) {
|
||||
return coredata.ErrResourceNotFound
|
||||
}
|
||||
|
||||
return fmt.Errorf("cannot load oauth2 access token: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (s *Service) ListAccessTokensByIdentityID(
|
||||
ctx context.Context,
|
||||
identityID gid.GID,
|
||||
cursor *page.Cursor[coredata.OAuth2AccessTokenOrderField],
|
||||
) (*page.Page[*coredata.OAuth2AccessToken, coredata.OAuth2AccessTokenOrderField], error) {
|
||||
var tokens coredata.OAuth2AccessTokens
|
||||
|
||||
err := s.pg.WithConn(
|
||||
ctx,
|
||||
func(ctx context.Context, conn pg.Querier) error {
|
||||
if err := tokens.LoadByIdentityID(ctx, conn, identityID, cursor); err != nil {
|
||||
return fmt.Errorf("cannot load oauth2 access tokens: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return page.NewPage(tokens, cursor), nil
|
||||
}
|
||||
|
||||
func (s *Service) CountAccessTokensByIdentityID(
|
||||
ctx context.Context,
|
||||
identityID gid.GID,
|
||||
) (int, error) {
|
||||
var count int
|
||||
|
||||
err := s.pg.WithConn(
|
||||
ctx,
|
||||
func(ctx context.Context, conn pg.Querier) error {
|
||||
var tokens coredata.OAuth2AccessTokens
|
||||
|
||||
var err error
|
||||
|
||||
count, err = tokens.CountByIdentityID(ctx, conn, identityID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot count oauth2 access tokens: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (s *Service) RevokeAccessToken(ctx context.Context, accessTokenID gid.GID) error {
|
||||
return s.pg.WithTx(
|
||||
ctx,
|
||||
func(ctx context.Context, tx pg.Tx) error {
|
||||
token := &coredata.OAuth2AccessToken{}
|
||||
|
||||
if err := token.LoadByID(ctx, tx, accessTokenID); err != nil {
|
||||
if errors.Is(err, coredata.ErrResourceNotFound) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("cannot load oauth2 access token: %w", err)
|
||||
}
|
||||
|
||||
if err := token.Delete(ctx, tx); err != nil {
|
||||
return fmt.Errorf("cannot revoke oauth2 access token: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Service) CreateManualAccessToken(
|
||||
ctx context.Context,
|
||||
req *CreateManualAccessTokenRequest,
|
||||
) (string, *coredata.OAuth2AccessToken, error) {
|
||||
if req.Name == "" {
|
||||
return "", nil, NewError(ErrInvalidRequest, WithDescription("name is required"))
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if !req.ExpiresAt.After(now) {
|
||||
return "", nil, NewError(ErrInvalidRequest, WithDescription("expires_at must be in the future"))
|
||||
}
|
||||
|
||||
if len(req.Scopes) == 0 {
|
||||
return "", nil, NewError(ErrInvalidRequest, WithDescription("scopes are required"))
|
||||
}
|
||||
|
||||
if err := validateManualAccessTokenScopes(req.Scopes, req.AllowedAPIScopes); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
tokenValue := rand.MustHexString(tokenByteLength)
|
||||
|
||||
accessToken := &coredata.OAuth2AccessToken{
|
||||
ID: gid.New(req.IdentityID.TenantID(), coredata.OAuth2AccessTokenEntityType),
|
||||
Name: req.Name,
|
||||
HashedValue: hash.SHA256String(tokenValue),
|
||||
ClientID: nil,
|
||||
IdentityID: req.IdentityID,
|
||||
Scopes: req.Scopes,
|
||||
CreatedAt: now,
|
||||
ExpiresAt: req.ExpiresAt,
|
||||
}
|
||||
|
||||
err := s.pg.WithTx(
|
||||
ctx,
|
||||
func(ctx context.Context, tx pg.Tx) error {
|
||||
if err := accessToken.Insert(ctx, tx); err != nil {
|
||||
return fmt.Errorf("cannot insert oauth2 access token: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
return tokenValue, accessToken, nil
|
||||
}
|
||||
|
||||
func validateManualAccessTokenScopes(scopes, allowedAPIScopes coredata.OAuth2Scopes) error {
|
||||
allowed := make(map[coredata.OAuth2Scope]struct{}, len(allowedAPIScopes))
|
||||
for _, scope := range allowedAPIScopes {
|
||||
allowed[scope] = struct{}{}
|
||||
}
|
||||
|
||||
for _, scope := range scopes {
|
||||
if _, ok := allowed[scope]; !ok {
|
||||
return NewError(ErrInvalidScope, WithDescription("invalid scope: "+string(scope)))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ func IAMOAuth2ScopeSet() *ScopeSet {
|
||||
ActionOAuth2ConsentGet,
|
||||
ActionAuditLogEntryGet,
|
||||
ActionAuditLogEntryList,
|
||||
ActionOAuth2AccessTokenGet,
|
||||
ActionOAuth2AccessTokenList,
|
||||
},
|
||||
ScopeV1IAM: {
|
||||
ActionOrganizationCreate,
|
||||
|
||||
@@ -71,6 +71,7 @@ func IAMPolicySet() *PolicySet {
|
||||
IAMSelfManageProfilePolicy,
|
||||
IAMSelfManageMembershipPolicy,
|
||||
IAMSelfManagePersonalAPIKeyPolicy,
|
||||
IAMSelfManageOAuth2AccessTokenPolicy,
|
||||
IAMSelfManageOAuth2ConsentPolicy,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -122,6 +122,16 @@ func (r *queryResolver) Node(ctx context.Context, id gid.GID) (types.Node, error
|
||||
|
||||
return types.NewPersonalAPIKey(personalAPIKey), nil
|
||||
}
|
||||
case coredata.OAuth2AccessTokenEntityType:
|
||||
action = iam.ActionOAuth2AccessTokenGet
|
||||
loadNode = func(ctx context.Context, id gid.GID) (types.Node, error) {
|
||||
accessToken, err := r.iam.OAuth2ServerService.GetAccessTokenByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return types.NewOAuth2AccessToken(accessToken), nil
|
||||
}
|
||||
case coredata.SCIMConfigurationEntityType:
|
||||
action = iam.ActionSCIMConfigurationGet
|
||||
loadNode = func(ctx context.Context, id gid.GID) (types.Node, error) {
|
||||
@@ -256,6 +266,18 @@ func (r *queryResolver) SignUpEnabled(ctx context.Context) (bool, error) {
|
||||
return r.iam.IsSignUpEnabled(), nil
|
||||
}
|
||||
|
||||
// Oauth2ScopesSupported is the resolver for the oauth2ScopesSupported field.
|
||||
func (r *queryResolver) Oauth2ScopesSupported(ctx context.Context) ([]string, error) {
|
||||
apiScopes := r.iam.Authorizer.APIScopes()
|
||||
|
||||
scopes := make([]string, len(apiScopes))
|
||||
for i, scope := range apiScopes {
|
||||
scopes[i] = scope.String()
|
||||
}
|
||||
|
||||
return scopes, nil
|
||||
}
|
||||
|
||||
// Mutation returns schema.MutationResolver implementation.
|
||||
func (r *Resolver) Mutation() schema.MutationResolver { return &mutationResolver{r} }
|
||||
|
||||
|
||||
@@ -33,6 +33,9 @@ type Query {
|
||||
signUpEnabled: Boolean!
|
||||
@goField(forceResolver: true)
|
||||
@authentication(required: OPTIONAL)
|
||||
oauth2ScopesSupported: [String!]!
|
||||
@goField(forceResolver: true)
|
||||
@authentication(required: OPTIONAL)
|
||||
}
|
||||
|
||||
type OIDCProviderInfo {
|
||||
|
||||
@@ -33,6 +33,16 @@ type Identity implements Node {
|
||||
@authentication(required: PRESENT)
|
||||
@sessionOnly
|
||||
|
||||
oauth2AccessTokens(
|
||||
first: Int
|
||||
after: CursorKey
|
||||
last: Int
|
||||
before: CursorKey
|
||||
): OAuth2AccessTokenConnection
|
||||
@goField(forceResolver: true)
|
||||
@authentication(required: PRESENT)
|
||||
@sessionOnly
|
||||
|
||||
invitingOrganizations: [Organization!]!
|
||||
@goField(forceResolver: true)
|
||||
@authentication(required: PRESENT)
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
type OAuth2AccessToken implements Node {
|
||||
id: ID!
|
||||
name: String!
|
||||
scopes: [String!]!
|
||||
expiresAt: Datetime!
|
||||
createdAt: Datetime!
|
||||
permission(action: String!): Boolean! @goField(forceResolver: true)
|
||||
}
|
||||
|
||||
type OAuth2AccessTokenConnection
|
||||
@goModel(
|
||||
model: "go.probo.inc/probo/pkg/server/api/connect/v1/types.OAuth2AccessTokenConnection"
|
||||
) {
|
||||
edges: [OAuth2AccessTokenEdge!]!
|
||||
pageInfo: PageInfo!
|
||||
totalCount: Int @goField(forceResolver: true)
|
||||
}
|
||||
|
||||
type OAuth2AccessTokenEdge {
|
||||
node: OAuth2AccessToken!
|
||||
cursor: CursorKey!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createOAuth2AccessToken(
|
||||
input: CreateOAuth2AccessTokenInput!
|
||||
): CreateOAuth2AccessTokenPayload
|
||||
@authentication(required: PRESENT)
|
||||
@sessionOnly
|
||||
|
||||
revokeOAuth2AccessToken(
|
||||
input: RevokeOAuth2AccessTokenInput!
|
||||
): RevokeOAuth2AccessTokenPayload
|
||||
@authentication(required: PRESENT)
|
||||
@sessionOnly
|
||||
}
|
||||
|
||||
input CreateOAuth2AccessTokenInput
|
||||
@goModel(
|
||||
model: "go.probo.inc/probo/pkg/server/api/connect/v1/types.CreateOAuth2AccessTokenInput"
|
||||
) {
|
||||
name: String!
|
||||
expiresAt: Datetime!
|
||||
scopes: [String!]!
|
||||
}
|
||||
|
||||
input RevokeOAuth2AccessTokenInput {
|
||||
oauth2AccessTokenId: ID!
|
||||
}
|
||||
|
||||
type CreateOAuth2AccessTokenPayload {
|
||||
oauth2AccessTokenEdge: OAuth2AccessTokenEdge!
|
||||
token: String!
|
||||
}
|
||||
|
||||
type RevokeOAuth2AccessTokenPayload {
|
||||
oauth2AccessTokenId: ID!
|
||||
}
|
||||
@@ -130,6 +130,36 @@ func (r *identityResolver) PersonalAPIKeys(ctx context.Context, obj *types.Ident
|
||||
return types.NewPersonalAPIKeyConnection(page, r, obj.ID), nil
|
||||
}
|
||||
|
||||
// Oauth2AccessTokens is the resolver for the oauth2AccessTokens field.
|
||||
func (r *identityResolver) Oauth2AccessTokens(ctx context.Context, obj *types.Identity, first *int, after *page.CursorKey, last *int, before *page.CursorKey) (*types.OAuth2AccessTokenConnection, error) {
|
||||
if _, err := r.authorize(ctx, obj.ID, iam.ActionOAuth2AccessTokenList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if gqlutils.OnlyTotalCountSelected(ctx) {
|
||||
return &types.OAuth2AccessTokenConnection{
|
||||
Resolver: r,
|
||||
ParentID: obj.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
pageOrderBy := page.OrderBy[coredata.OAuth2AccessTokenOrderField]{
|
||||
Field: coredata.OAuth2AccessTokenOrderFieldCreatedAt,
|
||||
Direction: page.OrderDirectionDesc,
|
||||
}
|
||||
|
||||
cursor := cursor.NewCursor(first, after, last, before, pageOrderBy)
|
||||
|
||||
tokenPage, err := r.iam.OAuth2ServerService.ListAccessTokensByIdentityID(ctx, obj.ID, cursor)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot list oauth2 access tokens", log.Error(err))
|
||||
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return types.NewOAuth2AccessTokenConnection(tokenPage, r, obj.ID), nil
|
||||
}
|
||||
|
||||
// InvitingOrganizations is the resolver for the invitingOrganizations field.
|
||||
func (r *identityResolver) InvitingOrganizations(ctx context.Context, obj *types.Identity) ([]*types.Organization, error) {
|
||||
if _, err := r.authorize(ctx, obj.ID, iam.ActionInvitationList, authz.WithSkipAssumptionCheck()); err != nil {
|
||||
|
||||
121
pkg/server/api/connect/v1/oauth2_access_token_resolvers.go
Normal file
121
pkg/server/api/connect/v1/oauth2_access_token_resolvers.go
Normal file
@@ -0,0 +1,121 @@
|
||||
package connect_v1
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.90
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"go.gearno.de/kit/log"
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/iam"
|
||||
"go.probo.inc/probo/pkg/iam/oauth2"
|
||||
"go.probo.inc/probo/pkg/server/api/authn"
|
||||
"go.probo.inc/probo/pkg/server/api/connect/v1/schema"
|
||||
"go.probo.inc/probo/pkg/server/api/connect/v1/types"
|
||||
"go.probo.inc/probo/pkg/server/gqlutils"
|
||||
)
|
||||
|
||||
// CreateOAuth2AccessToken is the resolver for the createOAuth2AccessToken field.
|
||||
func (r *mutationResolver) CreateOAuth2AccessToken(ctx context.Context, input types.CreateOAuth2AccessTokenInput) (*types.CreateOAuth2AccessTokenPayload, error) {
|
||||
identity := authn.IdentityFromContext(ctx)
|
||||
|
||||
if _, err := r.authorize(ctx, identity.ID, iam.ActionOAuth2AccessTokenCreate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
scopes, err := input.ParsedScopes()
|
||||
if err != nil {
|
||||
return nil, gqlutils.Invalid(ctx, err)
|
||||
}
|
||||
|
||||
tokenValue, accessToken, err := r.iam.OAuth2ServerService.CreateManualAccessToken(
|
||||
ctx,
|
||||
&oauth2.CreateManualAccessTokenRequest{
|
||||
IdentityID: identity.ID,
|
||||
Name: strings.TrimSpace(input.Name),
|
||||
ExpiresAt: input.ExpiresAt,
|
||||
Scopes: scopes,
|
||||
AllowedAPIScopes: r.iam.Authorizer.APIScopes(),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
if oauth2Err, ok := errors.AsType[*oauth2.OAuth2Error](err); ok {
|
||||
return nil, gqlutils.Invalid(ctx, oauth2Err)
|
||||
}
|
||||
|
||||
r.logger.ErrorCtx(ctx, "cannot create oauth2 access token", log.Error(err))
|
||||
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return &types.CreateOAuth2AccessTokenPayload{
|
||||
Oauth2AccessTokenEdge: types.NewOAuth2AccessTokenEdge(
|
||||
accessToken,
|
||||
coredata.OAuth2AccessTokenOrderFieldCreatedAt,
|
||||
),
|
||||
Token: tokenValue,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RevokeOAuth2AccessToken is the resolver for the revokeOAuth2AccessToken field.
|
||||
func (r *mutationResolver) RevokeOAuth2AccessToken(ctx context.Context, input types.RevokeOAuth2AccessTokenInput) (*types.RevokeOAuth2AccessTokenPayload, error) {
|
||||
if _, err := r.authorize(ctx, input.Oauth2AccessTokenID, iam.ActionOAuth2AccessTokenDelete); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := r.iam.OAuth2ServerService.RevokeAccessToken(ctx, input.Oauth2AccessTokenID); err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot revoke oauth2 access token", log.Error(err))
|
||||
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return &types.RevokeOAuth2AccessTokenPayload{
|
||||
Oauth2AccessTokenID: input.Oauth2AccessTokenID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Permission is the resolver for the permission field.
|
||||
func (r *oAuth2AccessTokenResolver) Permission(ctx context.Context, obj *types.OAuth2AccessToken, action string) (bool, error) {
|
||||
return r.Resolver.Permission(ctx, obj, action)
|
||||
}
|
||||
|
||||
// TotalCount is the resolver for the totalCount field.
|
||||
func (r *oAuth2AccessTokenConnectionResolver) TotalCount(ctx context.Context, obj *types.OAuth2AccessTokenConnection) (*int, error) {
|
||||
switch obj.Resolver.(type) {
|
||||
case *identityResolver:
|
||||
if _, err := r.authorize(ctx, obj.ParentID, iam.ActionOAuth2AccessTokenList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
count, err := r.iam.OAuth2ServerService.CountAccessTokensByIdentityID(ctx, obj.ParentID)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot count oauth2 access tokens", log.Error(err))
|
||||
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return &count, nil
|
||||
}
|
||||
|
||||
r.logger.ErrorCtx(ctx, "unsupported resolver", log.Any("resolver", obj.Resolver))
|
||||
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
// OAuth2AccessToken returns schema.OAuth2AccessTokenResolver implementation.
|
||||
func (r *Resolver) OAuth2AccessToken() schema.OAuth2AccessTokenResolver {
|
||||
return &oAuth2AccessTokenResolver{r}
|
||||
}
|
||||
|
||||
// OAuth2AccessTokenConnection returns schema.OAuth2AccessTokenConnectionResolver implementation.
|
||||
func (r *Resolver) OAuth2AccessTokenConnection() schema.OAuth2AccessTokenConnectionResolver {
|
||||
return &oAuth2AccessTokenConnectionResolver{r}
|
||||
}
|
||||
|
||||
type oAuth2AccessTokenResolver struct{ *Resolver }
|
||||
type oAuth2AccessTokenConnectionResolver struct{ *Resolver }
|
||||
98
pkg/server/api/connect/v1/types/oauth2_access_token.go
Normal file
98
pkg/server/api/connect/v1/types/oauth2_access_token.go
Normal file
@@ -0,0 +1,98 @@
|
||||
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package types
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
)
|
||||
|
||||
type (
|
||||
CreateOAuth2AccessTokenInput struct {
|
||||
Name string `json:"name"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
Scopes []string `json:"scopes"`
|
||||
}
|
||||
|
||||
OAuth2AccessTokenConnection struct {
|
||||
TotalCount int
|
||||
Edges []*OAuth2AccessTokenEdge
|
||||
PageInfo PageInfo
|
||||
|
||||
Resolver any
|
||||
ParentID gid.GID
|
||||
}
|
||||
)
|
||||
|
||||
func (in *CreateOAuth2AccessTokenInput) ParsedScopes() (coredata.OAuth2Scopes, error) {
|
||||
if len(in.Scopes) == 0 {
|
||||
return nil, errors.New("scopes are required")
|
||||
}
|
||||
|
||||
scopes := make(coredata.OAuth2Scopes, len(in.Scopes))
|
||||
for i, scopeString := range in.Scopes {
|
||||
scopes[i] = coredata.OAuth2Scope(scopeString)
|
||||
}
|
||||
|
||||
return scopes, nil
|
||||
}
|
||||
|
||||
func NewOAuth2AccessTokenConnection(
|
||||
p *page.Page[*coredata.OAuth2AccessToken, coredata.OAuth2AccessTokenOrderField],
|
||||
resolver any,
|
||||
parentID gid.GID,
|
||||
) *OAuth2AccessTokenConnection {
|
||||
edges := make([]*OAuth2AccessTokenEdge, len(p.Data))
|
||||
for i, token := range p.Data {
|
||||
edges[i] = NewOAuth2AccessTokenEdge(token, p.Cursor.OrderBy.Field)
|
||||
}
|
||||
|
||||
return &OAuth2AccessTokenConnection{
|
||||
Edges: edges,
|
||||
PageInfo: *NewPageInfo(p),
|
||||
|
||||
Resolver: resolver,
|
||||
ParentID: parentID,
|
||||
}
|
||||
}
|
||||
|
||||
func NewOAuth2AccessTokenEdge(
|
||||
token *coredata.OAuth2AccessToken,
|
||||
orderField coredata.OAuth2AccessTokenOrderField,
|
||||
) *OAuth2AccessTokenEdge {
|
||||
return &OAuth2AccessTokenEdge{
|
||||
Node: NewOAuth2AccessToken(token),
|
||||
Cursor: token.CursorKey(orderField),
|
||||
}
|
||||
}
|
||||
|
||||
func NewOAuth2AccessToken(token *coredata.OAuth2AccessToken) *OAuth2AccessToken {
|
||||
scopes := make([]string, len(token.Scopes))
|
||||
for i, scope := range token.Scopes {
|
||||
scopes[i] = string(scope)
|
||||
}
|
||||
|
||||
return &OAuth2AccessToken{
|
||||
ID: token.ID,
|
||||
Name: token.Name,
|
||||
Scopes: scopes,
|
||||
ExpiresAt: token.ExpiresAt,
|
||||
CreatedAt: token.CreatedAt,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user