initial commit

This commit is contained in:
Giovanni Rezcjikov
2026-03-08 14:54:29 +03:00
commit f4e4fb21e3
75 changed files with 7407 additions and 0 deletions
@@ -0,0 +1,339 @@
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) 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) 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()
var consents []models.UserConsent
for rows.Next() {
var c models.UserConsent
var scopeJSON []byte
err := rows.Scan(
&c.ID,
&c.UserID,
&c.ClientID,
&c.ClientIdentifier,
&c.ClientName,
&scopeJSON,
&c.AuthorizedAt,
&c.LastUsedAt,
&c.RevokedAt,
)
if 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
}
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)
if err != nil {
return err
}
return nil
}
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.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())
AND uo.id = $2
ORDER BY uc.authorized_at DESC
`, userID, clientID)
if err != nil {
return nil, err
}
defer rows.Close()
var consents []models.UserConsent
for rows.Next() {
var c models.UserConsent
var scopeJSON []byte
err := rows.Scan(
&c.ID,
&c.UserID,
&c.ClientID,
&c.ClientIdentifier,
&c.ClientName,
&scopeJSON,
&c.AuthorizedAt,
&c.LastUsedAt,
&c.RevokedAt,
)
if 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
}
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)
}
@@ -0,0 +1,85 @@
package repositories
import (
"context"
"fmt"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type UserRepository struct {
db *pgxpool.Pool
}
func NewUserRepository(db *pgxpool.Pool) *UserRepository {
return &UserRepository{db: db}
}
func (r *UserRepository) IsUserExistsByEmail(ctx context.Context, email string) bool {
var exists bool
_ = r.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE email = $1)`, email).Scan(&exists)
return exists
}
func (r *UserRepository) CreateUser(ctx context.Context, user models.User) (*models.User, error) {
err := r.db.QueryRow(ctx, `
INSERT INTO users (email, password_hash, first_name, second_name, birth_date, sex)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, created_at, updated_at
`, user.Email, user.PasswordHash, user.FirstName, user.SecondName, user.BirthDate, user.Sex).
Scan(&user.ID, &user.CreatedAt, &user.UpdatedAt)
if err != nil {
return nil, fmt.Errorf("create user: %w", err)
}
return &user, nil
}
func (r *UserRepository) UpdateUser(ctx context.Context, user models.User) (*models.User, error) {
err := r.db.QueryRow(ctx, `
UPDATE users
SET first_name = $1,
second_name = $2,
birth_date = $3,
sex = $4,
password_hash = $5,
updated_at = now()
WHERE id = $6
RETURNING updated_at
`, user.FirstName, user.SecondName, user.BirthDate, user.Sex, user.PasswordHash, user.ID).
Scan(&user.UpdatedAt)
if err != nil {
return nil, fmt.Errorf("update user: %w", err)
}
return &user, nil
}
func (r *UserRepository) DeleteUser(ctx context.Context, id uuid.UUID) error {
_, err := r.db.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
return err
}
func (r *UserRepository) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
var u models.User
err := r.db.QueryRow(ctx, `
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
FROM users WHERE email = $1
`, email).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
if err != nil {
return nil, err
}
return &u, nil
}
func (r *UserRepository) GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error) {
var u models.User
err := r.db.QueryRow(ctx, `
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
FROM users WHERE id = $1
`, id).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
if err != nil {
return nil, err
}
return &u, nil
}