392 lines
12 KiB
Go
392 lines
12 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type OAuthRepository struct {
|
|
db *pgxpool.Pool
|
|
}
|
|
|
|
func NewOAuthRepository(db *pgxpool.Pool) *OAuthRepository {
|
|
return &OAuthRepository{db: db}
|
|
}
|
|
|
|
func (r *OAuthRepository) CreateOAuthClient(ctx context.Context, client models.OAuthClient) (*models.OAuthClient, error) {
|
|
err := r.db.QueryRow(ctx, `
|
|
INSERT INTO oauth_clients (client_id, client_secret, name, redirect_uris, grant_types, scopes, trusted)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
RETURNING id, is_active, created_at, updated_at
|
|
`, client.ClientID, client.ClientSecret, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted).
|
|
Scan(&client.ID, &client.IsActive, &client.CreatedAt, &client.UpdatedAt)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create OAuth client: %w", err)
|
|
}
|
|
return &client, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) GetOAuthClientByClientID(ctx context.Context, clientID string) (*models.OAuthClient, error) {
|
|
var client models.OAuthClient
|
|
err := r.db.QueryRow(ctx, `
|
|
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
|
FROM oauth_clients WHERE client_id = $1 AND is_active = true
|
|
`, clientID).Scan(
|
|
&client.ID, &client.ClientID, &client.ClientSecret, &client.Name,
|
|
&client.RedirectURIs, &client.GrantTypes, &client.Scopes,
|
|
&client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &client, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) GetOAuthClientByID(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error) {
|
|
var client models.OAuthClient
|
|
err := r.db.QueryRow(ctx, `
|
|
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
|
FROM oauth_clients WHERE id = $1 AND is_active = true
|
|
`, id).Scan(
|
|
&client.ID, &client.ClientID, &client.ClientSecret, &client.Name,
|
|
&client.RedirectURIs, &client.GrantTypes, &client.Scopes,
|
|
&client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &client, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) ListOAuthClients(ctx context.Context) ([]models.OAuthClient, error) {
|
|
rows, err := r.db.Query(ctx, `
|
|
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
|
FROM oauth_clients
|
|
ORDER BY created_at DESC
|
|
`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var clients []models.OAuthClient
|
|
for rows.Next() {
|
|
var c models.OAuthClient
|
|
if err := rows.Scan(
|
|
&c.ID, &c.ClientID, &c.ClientSecret, &c.Name,
|
|
&c.RedirectURIs, &c.GrantTypes, &c.Scopes,
|
|
&c.IsActive, &c.Trusted, &c.CreatedAt, &c.UpdatedAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
clients = append(clients, c)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return clients, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) GetOAuthClientByIDAdmin(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error) {
|
|
var client models.OAuthClient
|
|
err := r.db.QueryRow(ctx, `
|
|
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
|
FROM oauth_clients WHERE id = $1
|
|
`, id).Scan(
|
|
&client.ID, &client.ClientID, &client.ClientSecret, &client.Name,
|
|
&client.RedirectURIs, &client.GrantTypes, &client.Scopes,
|
|
&client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &client, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) UpdateOAuthClient(ctx context.Context, client models.OAuthClient) (*models.OAuthClient, error) {
|
|
err := r.db.QueryRow(ctx, `
|
|
UPDATE oauth_clients
|
|
SET name = $1,
|
|
redirect_uris = $2,
|
|
grant_types = $3,
|
|
scopes = $4,
|
|
trusted = $5,
|
|
is_active = $6,
|
|
updated_at = now()
|
|
WHERE id = $7
|
|
RETURNING updated_at
|
|
`, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes,
|
|
client.Trusted, client.IsActive, client.ID).
|
|
Scan(&client.UpdatedAt)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("update oauth client: %w", err)
|
|
}
|
|
return &client, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) DeactivateOAuthClient(ctx context.Context, id uuid.UUID) error {
|
|
_, err := r.db.Exec(ctx, `UPDATE oauth_clients SET is_active = false, updated_at = now() WHERE id = $1`, id)
|
|
return err
|
|
}
|
|
|
|
func (r *OAuthRepository) CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error) {
|
|
err := r.db.QueryRow(ctx, `
|
|
INSERT INTO authorization_codes (code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
RETURNING id, code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at
|
|
`, row.CodeHash, row.UserID, row.ClientID, row.RedirectURI, row.Scopes,
|
|
row.CodeChallenge, row.CodeChallengeMethod, row.ExpiresAt, row.ConsumedAt, row.CreatedAt).
|
|
Scan(&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI,
|
|
&row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod,
|
|
&row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create authorization code: %w", err)
|
|
}
|
|
return &row, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error) {
|
|
var row models.AuthorizationCodeRow
|
|
err := r.db.QueryRow(ctx, `
|
|
SELECT id, code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at
|
|
FROM authorization_codes WHERE code_hash = $1
|
|
`, codeHash).Scan(
|
|
&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI,
|
|
&row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod,
|
|
&row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &row, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error {
|
|
_, err := r.db.Exec(ctx, `
|
|
UPDATE authorization_codes SET consumed_at = now()
|
|
WHERE id = $1 AND consumed_at IS NULL
|
|
`, id)
|
|
return err
|
|
}
|
|
|
|
func (r *OAuthRepository) CreateRefreshToken(ctx context.Context, row models.RefreshTokenRow) (*models.RefreshTokenRow, error) {
|
|
err := r.db.QueryRow(ctx, `
|
|
INSERT INTO refresh_tokens (token_hash, user_id, client_id, scopes, expires_at, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6)
|
|
RETURNING id, token_hash, user_id, client_id, scopes, expires_at, created_at
|
|
`, row.TokenHash, row.UserID, row.ClientID, row.Scopes, row.ExpiresAt, row.CreatedAt).
|
|
Scan(&row.ID, &row.TokenHash, &row.UserID, &row.ClientID, &row.Scopes, &row.ExpiresAt, &row.CreatedAt)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create refresh token: %w", err)
|
|
}
|
|
return &row, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error) {
|
|
var row models.RefreshTokenRow
|
|
err := r.db.QueryRow(ctx, `
|
|
SELECT id, token_hash, user_id, client_id, scopes, expires_at, created_at
|
|
FROM refresh_tokens WHERE token_hash = $1
|
|
`, tokenHash).Scan(
|
|
&row.ID, &row.TokenHash, &row.UserID, &row.ClientID,
|
|
&row.Scopes, &row.ExpiresAt, &row.CreatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &row, nil
|
|
}
|
|
|
|
func (r *OAuthRepository) DeleteRefreshTokenByID(ctx context.Context, id uuid.UUID) error {
|
|
_, err := r.db.Exec(ctx, `DELETE FROM refresh_tokens WHERE id = $1`, id)
|
|
return err
|
|
}
|
|
|
|
func (r *OAuthRepository) DeleteRefreshTokensByUserID(ctx context.Context, userID uuid.UUID) error {
|
|
_, err := r.db.Exec(ctx, `DELETE FROM refresh_tokens WHERE user_id = $1`, userID)
|
|
return err
|
|
}
|
|
|
|
func (r *OAuthRepository) RecordUserConsent(
|
|
ctx context.Context,
|
|
userID, clientID uuid.UUID,
|
|
scopes []string,
|
|
) error {
|
|
scopeJSON, err := json.Marshal(scopes)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = r.db.Exec(ctx, `
|
|
INSERT INTO user_consents (user_id, client_id, scopes, authorized_at, last_used_at, revoked_at)
|
|
VALUES ($1, $2, $3, now(), now(), NULL)
|
|
ON CONFLICT (user_id, client_id)
|
|
WHERE revoked_at IS NULL
|
|
DO UPDATE SET scopes = EXCLUDED.scopes, last_used_at = now()
|
|
`, userID, clientID, scopeJSON)
|
|
|
|
return err
|
|
}
|
|
|
|
func (r *OAuthRepository) GetUserConsents(
|
|
ctx context.Context,
|
|
userID uuid.UUID,
|
|
) ([]models.UserConsent, error) {
|
|
rows, err := r.db.Query(ctx, `
|
|
SELECT
|
|
uc.id,
|
|
uc.user_id,
|
|
uc.client_id,
|
|
oc.client_id AS client_identifier,
|
|
oc.name AS client_name,
|
|
uc.scopes,
|
|
uc.authorized_at,
|
|
uc.last_used_at,
|
|
uc.revoked_at
|
|
FROM user_consents uc
|
|
JOIN oauth_clients oc ON uc.client_id = oc.id
|
|
WHERE uc.user_id = $1
|
|
AND uc.revoked_at IS NULL
|
|
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
|
ORDER BY uc.authorized_at DESC
|
|
`, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
return scanConsents(rows)
|
|
}
|
|
|
|
func (r *OAuthRepository) UpdateConsentLastUsed(
|
|
ctx context.Context,
|
|
userID, clientID uuid.UUID,
|
|
) error {
|
|
_, err := r.db.Exec(ctx, `
|
|
UPDATE user_consents
|
|
SET last_used_at = now()
|
|
WHERE user_id = $1
|
|
AND client_id = $2
|
|
AND revoked_at IS NULL
|
|
AND (expires_at IS NULL OR expires_at > now())
|
|
`, userID, clientID)
|
|
return err
|
|
}
|
|
|
|
func (r *OAuthRepository) GetUserConsentsByClientID(
|
|
ctx context.Context,
|
|
userID uuid.UUID,
|
|
clientID uuid.UUID,
|
|
) ([]models.UserConsent, error) {
|
|
rows, err := r.db.Query(ctx, `
|
|
SELECT
|
|
uc.id,
|
|
uc.user_id,
|
|
uc.client_id,
|
|
oc.client_id AS client_identifier,
|
|
oc.name AS client_name,
|
|
uc.scopes,
|
|
uc.authorized_at,
|
|
uc.last_used_at,
|
|
uc.revoked_at
|
|
FROM user_consents uc
|
|
JOIN oauth_clients oc ON uc.client_id = oc.id
|
|
WHERE uc.user_id = $1
|
|
AND uc.client_id = $2
|
|
AND uc.revoked_at IS NULL
|
|
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
|
ORDER BY uc.authorized_at DESC
|
|
`, userID, clientID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
return scanConsents(rows)
|
|
}
|
|
|
|
func (r *OAuthRepository) RevokeConsent(
|
|
ctx context.Context,
|
|
userID, clientID uuid.UUID,
|
|
revokedBy *uuid.UUID,
|
|
) error {
|
|
tx, err := r.db.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE user_consents
|
|
SET revoked_at = now(), revoked_by = $3
|
|
WHERE user_id = $1 AND client_id = $2 AND revoked_at IS NULL
|
|
`, userID, clientID, revokedBy)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
DELETE FROM refresh_tokens WHERE user_id = $1 AND client_id = $2
|
|
`, userID, clientID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
func (r *OAuthRepository) UpsertClient(ctx context.Context, client models.OAuthClient) error {
|
|
_, err := r.db.Exec(ctx, `
|
|
INSERT INTO oauth_clients (client_id, client_secret, name, redirect_uris, grant_types, scopes, trusted)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
ON CONFLICT (client_id) DO UPDATE SET
|
|
client_secret = EXCLUDED.client_secret,
|
|
name = EXCLUDED.name,
|
|
redirect_uris = EXCLUDED.redirect_uris,
|
|
grant_types = EXCLUDED.grant_types,
|
|
scopes = EXCLUDED.scopes,
|
|
updated_at = now()
|
|
`, client.ClientID, client.ClientSecret, client.Name,
|
|
client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted)
|
|
return err
|
|
}
|
|
|
|
func scanConsents(rows interface {
|
|
Next() bool
|
|
Scan(...any) error
|
|
Err() error
|
|
}) ([]models.UserConsent, error) {
|
|
var consents []models.UserConsent
|
|
|
|
for rows.Next() {
|
|
var c models.UserConsent
|
|
var scopeJSON []byte
|
|
|
|
if err := rows.Scan(
|
|
&c.ID, &c.UserID, &c.ClientID,
|
|
&c.ClientIdentifier, &c.ClientName,
|
|
&scopeJSON,
|
|
&c.AuthorizedAt, &c.LastUsedAt, &c.RevokedAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := json.Unmarshal(scopeJSON, &c.Scopes); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
consents = append(consents, c)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return consents, nil
|
|
}
|