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,89 @@
package config
import (
"strings"
"time"
"github.com/caarlos0/env/v11"
"github.com/joho/godotenv"
)
type Conf struct {
Server Server
Postgres Postgres
Redis Redis
Client Client
JWT JWT
}
type Server struct {
Addr string `env:"SERVER_ADDR" envDefault:":8080"`
FrontendURL string `env:"FRONTEND_URL,required"`
}
type Postgres struct {
URL string `env:"POSTGRES_URL,required"`
MigrationFilePath string `env:"POSTGRES_MIGRATION_FILE_PATH,required"`
}
type Redis struct {
URL string `env:"REDIS_URL,required"`
}
type Client struct {
ID string `env:"CLIENT_ID,required"`
Secret string `env:"CLIENT_SECRET,required"`
Name string `env:"CLIENT_NAME" envDefault:"Basic Client"`
RedirectURIs []string `env:"CLIENT_REDIRECT_URIS" envSeparator:","`
GrantTypes []string `env:"CLIENT_GRANT_TYPES" envSeparator:"," envDefault:"refresh_token"`
Scopes []string `env:"CLIENT_SCOPES" envSeparator:"," envDefault:"profile:read,profile:edit,profile:consent:read,profile:consent:delete,auth:register"`
}
type JWT struct {
Secret string `env:"JWT_SECRET,required"`
TTL time.Duration `env:"JWT_TTL" envDefault:"24h"`
}
func New() (*Conf, error) {
_ = godotenv.Load()
var conf Conf
if err := env.Parse(&conf); err != nil {
return nil, err
}
return &conf, nil
}
func (c *Client) RedirectURIsJSON() string {
if len(c.RedirectURIs) == 0 {
return "[]"
}
var b strings.Builder
b.WriteString("[\"")
b.WriteString(strings.Join(c.RedirectURIs, "\",\""))
b.WriteString("\"]")
return b.String()
}
func (c *Client) GrantTypesJSON() string {
if len(c.GrantTypes) == 0 {
return "[]"
}
var b strings.Builder
b.WriteString("[\"")
b.WriteString(strings.Join(c.GrantTypes, "\",\""))
b.WriteString("\"]")
return b.String()
}
func (c *Client) ScopesJSON() string {
if len(c.Scopes) == 0 {
return "[]"
}
var b strings.Builder
b.WriteString("[\"")
b.WriteString(strings.Join(c.Scopes, "\",\""))
b.WriteString("\"]")
return b.String()
}
@@ -0,0 +1,23 @@
package db
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5/pgxpool"
)
func RunMigrations(migrationFilePath string, pool *pgxpool.Pool) error {
sql, err := os.ReadFile(migrationFilePath)
if err != nil {
return fmt.Errorf("failed to execute migrations: %w", err)
}
_, err = pool.Exec(context.Background(), string(sql))
if err != nil {
return fmt.Errorf("failed to execute migrations: %w", err)
}
return nil
}
@@ -0,0 +1,29 @@
package db
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type DB struct {
Pool *pgxpool.Pool
}
func ConnectPostgres(url string) (*DB, error) {
pool, err := pgxpool.New(context.Background(), url)
if err != nil {
return nil, fmt.Errorf("failed to create DB: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := pool.Ping(ctx); err != nil {
return nil, fmt.Errorf("failed to connect to DB: %w", err)
}
return &DB{Pool: pool}, nil
}
+31
View File
@@ -0,0 +1,31 @@
package db
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
type RedisDB struct {
Client *redis.Client
}
func ConnectRedis(url string) (*RedisDB, error) {
opt, err := redis.ParseURL(url)
if err != nil {
return nil, fmt.Errorf("invalid Redis URL: %w", err)
}
rdb := redis.NewClient(opt)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := rdb.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("failed to connect to Redis: %w", err)
}
return &RedisDB{Client: rdb}, nil
}
@@ -0,0 +1,115 @@
package handlers
import (
"net/http"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/dusiburg/kotosoft-id/internal/services"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type AuthHandler struct {
svc *services.Service
}
func NewAuthHandler(svc *services.Service) *AuthHandler {
return &AuthHandler{svc: svc}
}
func (h *AuthHandler) Register(c *gin.Context) {
var input models.UserRegisterInput
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
id, secret, ok := c.Request.BasicAuth()
if !ok {
c.Error(models.ErrUnauthorized)
return
}
service, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{ClientID: id, ClientSecret: secret})
if err != nil {
c.Error(models.ErrUnauthorized)
return
}
if !service.Trusted {
c.Error(models.ErrForbidden)
return
}
user, err := h.svc.Register(c.Request.Context(), input)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusCreated, user)
}
func (h *AuthHandler) Refresh(c *gin.Context) {
var input struct {
RefreshToken string `json:"refresh_token" binding:"required"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
pair, err := h.svc.RefreshTokens(c.Request.Context(), input.RefreshToken)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, pair)
}
func (h *AuthHandler) Profile(c *gin.Context) {
userID := mustUserID(c)
user, err := h.svc.GetUserByID(c.Request.Context(), userID)
if err != nil {
c.Error(models.ErrNotFound)
return
}
c.JSON(http.StatusOK, user)
}
func (h *AuthHandler) UpdateProfile(c *gin.Context) {
userID := mustUserID(c)
var input models.UserUpdateInput
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
user, err := h.svc.UpdateProfile(c.Request.Context(), userID, input)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, user)
}
func (h *AuthHandler) DeleteProfile(c *gin.Context) {
userID := mustUserID(c)
token, _ := bearerToken(c)
if err := h.svc.DeleteProfile(c.Request.Context(), userID, token); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func mustUserID(c *gin.Context) uuid.UUID {
return c.MustGet("user_id").(uuid.UUID)
}
@@ -0,0 +1,40 @@
package handlers
import (
"net/http"
"github.com/dusiburg/kotosoft-id/internal/services"
"github.com/gin-gonic/gin"
)
type ConsentHandler struct {
svc *services.Service
}
func NewConsentHandler(svc *services.Service) *ConsentHandler {
return &ConsentHandler{svc: svc}
}
func (h *ConsentHandler) GetUserConsents(c *gin.Context) {
userID := mustUserID(c)
consents, err := h.svc.GetUserConsents(c.Request.Context(), userID)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, consents)
}
func (h *ConsentHandler) RevokeAppAccess(c *gin.Context) {
userID := mustUserID(c)
clientID := c.Param("clientId")
if err := h.svc.RevokeConsent(c.Request.Context(), userID, clientID); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
@@ -0,0 +1,206 @@
package handlers
import (
"net/http"
"strings"
"github.com/dusiburg/kotosoft-id/internal/services"
"github.com/gin-gonic/gin"
)
type OAuthHandler struct {
svc *services.Service
frontendURL string
}
func NewOAuthHandler(svc *services.Service, frontendURL string) *OAuthHandler {
return &OAuthHandler{svc: svc, frontendURL: frontendURL}
}
func (h *OAuthHandler) Authorize(c *gin.Context) {
token, err := h.svc.CreateOAuthSession(
c.Request.Context(),
c.Query("client_id"),
c.Query("redirect_uri"),
c.Query("scope"),
c.Query("state"),
c.Query("code_challenge"),
c.Query("code_challenge_method"),
)
if err != nil {
oauthErrorJSON(c, err)
return
}
c.Redirect(http.StatusFound, h.frontendURL+"/oauth?session="+token)
}
func (h *OAuthHandler) GetSession(c *gin.Context) {
sess, err := h.svc.GetOAuthSession(c.Request.Context(), c.Param("token"))
if err != nil {
oauthErrorJSON(c, services.ErrInvalidGrant)
return
}
c.JSON(http.StatusOK, sess)
}
func (h *OAuthHandler) SessionLogin(c *gin.Context) {
var input struct {
Session string `json:"session" binding:"required"`
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}
if err := c.ShouldBindJSON(&input); err != nil {
oauthErrorJSON(c, services.ErrInvalidRequest)
return
}
redirectURL, err := h.svc.SessionLogin(c.Request.Context(), input.Session, input.Email, input.Password)
if err != nil {
if err == services.ErrInvalidGrant {
oauthErrorJSON(c, services.ErrInvalidGrant)
} else {
oauthErrorJSON(c, services.ErrAccessDenied)
}
return
}
if redirectURL != "" {
c.JSON(http.StatusOK, gin.H{"redirect_url": redirectURL})
return
}
c.Status(http.StatusOK)
}
func (h *OAuthHandler) SessionAttach(c *gin.Context) {
var input struct {
Session string `json:"session" binding:"required"`
}
if err := c.ShouldBindJSON(&input); err != nil {
oauthErrorJSON(c, services.ErrInvalidRequest)
return
}
accessToken, ok := bearerToken(c)
if !ok {
oauthErrorJSON(c, services.ErrInvalidClient)
return
}
redirectURL, err := h.svc.SessionAttach(c.Request.Context(), input.Session, accessToken)
if err != nil {
oauthErrorJSON(c, services.ErrAccessDenied)
return
}
if redirectURL != "" {
c.JSON(http.StatusOK, gin.H{"redirect_url": redirectURL})
return
}
c.Status(http.StatusOK)
}
func (h *OAuthHandler) SessionApprove(c *gin.Context) {
var input struct {
Session string `json:"session" binding:"required"`
Allow bool `json:"allow"`
}
if err := c.ShouldBindJSON(&input); err != nil {
oauthErrorJSON(c, services.ErrInvalidRequest)
return
}
if !input.Allow {
oauthErrorJSON(c, services.ErrAccessDenied)
return
}
redirectURL, err := h.svc.SessionApprove(c.Request.Context(), input.Session)
if err != nil {
oauthErrorJSON(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"redirect_url": redirectURL})
}
func (h *OAuthHandler) Token(c *gin.Context) {
auth := h.extractClientAuth(c)
switch c.PostForm("grant_type") {
case "authorization_code":
pair, err := h.svc.ExchangeCode(
c.Request.Context(), auth,
c.PostForm("code"),
c.PostForm("redirect_uri"),
c.PostForm("code_verifier"),
)
if err != nil {
oauthErrorJSON(c, err)
return
}
pair.User = nil
c.JSON(http.StatusOK, pair)
case "refresh_token":
pair, err := h.svc.ExchangeRefreshToken(c.Request.Context(), auth, c.PostForm("refresh_token"))
if err != nil {
oauthErrorJSON(c, err)
return
}
pair.User = nil
c.JSON(http.StatusOK, pair)
default:
oauthErrorJSON(c, services.ErrUnsupportedGrantType)
}
}
func (h *OAuthHandler) Revoke(c *gin.Context) {
_ = h.svc.RevokeToken(c.Request.Context(), h.extractClientAuth(c), c.PostForm("token"))
c.Status(http.StatusOK)
}
func (h *OAuthHandler) extractClientAuth(c *gin.Context) services.ClientAuth {
if id, secret, ok := c.Request.BasicAuth(); ok {
return services.ClientAuth{ClientID: id, ClientSecret: secret}
}
return services.ClientAuth{
ClientID: c.PostForm("client_id"),
ClientSecret: c.PostForm("client_secret"),
}
}
func bearerToken(c *gin.Context) (string, bool) {
return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
}
func oauthErrorJSON(c *gin.Context, err error) {
code, desc, status := oauthErrorDetails(err)
if code == "invalid_client" {
c.Header("WWW-Authenticate", `Basic realm="oauth"`)
}
c.JSON(status, gin.H{"error": code, "error_description": desc})
}
func oauthErrorDetails(err error) (code, desc string, status int) {
switch err {
case services.ErrInvalidRequest:
return "invalid_request", "Invalid request parameters", http.StatusBadRequest
case services.ErrUnauthorizedClient:
return "unauthorized_client", "Client not authorized", http.StatusBadRequest
case services.ErrAccessDenied:
return "access_denied", "Access denied", http.StatusForbidden
case services.ErrInvalidClient:
return "invalid_client", "Invalid client credentials", http.StatusUnauthorized
case services.ErrInvalidGrant:
return "invalid_grant", "Invalid or expired grant", http.StatusBadRequest
case services.ErrUnsupportedGrantType:
return "unsupported_grant_type", "Grant type not supported", http.StatusBadRequest
default:
return "server_error", "An unexpected error occurred", http.StatusInternalServerError
}
}
+117
View File
@@ -0,0 +1,117 @@
package http
import (
"strings"
"github.com/dusiburg/kotosoft-id/internal/handlers"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/dusiburg/kotosoft-id/internal/repositories"
"github.com/dusiburg/kotosoft-id/internal/services"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, svc *services.Service, repo *repositories.OAuthRepository) *gin.Engine {
r := gin.Default()
r.Use(errorMiddleware())
o := r.Group("/oauth")
{
o.GET("/authorize", oauth.Authorize)
o.GET("/session/:token", oauth.GetSession)
o.POST("/session/login", oauth.SessionLogin)
o.POST("/session/attach", oauth.SessionAttach)
o.POST("/session/approve", oauth.SessionApprove)
o.POST("/token", oauth.Token)
o.POST("/revoke", oauth.Revoke)
}
api := r.Group("/api/v1")
{
a := api.Group("/auth")
a.POST("/register", auth.Register)
a.POST("/refresh", auth.Refresh)
me := api.Group("/me")
me.GET("", authMiddleware(svc, repo, "profile:read"), auth.Profile)
me.PATCH("", authMiddleware(svc, repo, "profile:edit"), auth.UpdateProfile)
me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile)
me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents)
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
}
return r
}
func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, requiredScopes ...string) gin.HandlerFunc {
return func(c *gin.Context) {
token, ok := bearerToken(c)
if !ok {
c.Error(models.ErrUnauthorized)
c.Abort()
return
}
info, err := svc.ValidateAccessToken(c.Request.Context(), token)
if err != nil {
c.Error(models.ErrUnauthorized)
c.Abort()
return
}
if len(requiredScopes) > 0 && !services.ScopesContain(info.Scopes, requiredScopes) {
c.Error(models.ErrInsufficientScope)
c.Abort()
return
}
if err, _ := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil {
c.Error(models.ErrForbidden)
c.Abort()
return
}
c.Set("user_id", info.UserID)
c.Next()
}
}
func errorMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) == 0 || c.Writer.Written() {
return
}
err := c.Errors.Last().Err
if apiErr, ok := err.(*models.APIError); ok {
c.JSON(apiErr.Code, apiErr)
return
}
c.JSON(500, models.ErrInternal)
}
}
func clientAuthFromRequest(c *gin.Context) services.ClientAuth {
if id, secret, ok := c.Request.BasicAuth(); ok {
return services.ClientAuth{ClientID: id, ClientSecret: secret}
}
return services.ClientAuth{
ClientID: c.PostForm("client_id"),
ClientSecret: c.PostForm("client_secret"),
}
}
func bearerToken(c *gin.Context) (string, bool) {
return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
}
func UserIDFromContext(c *gin.Context) (uuid.UUID, bool) {
v, ok := c.Get("user_id")
if !ok {
return uuid.Nil, false
}
id, ok := v.(uuid.UUID)
return id, ok
}
@@ -0,0 +1,47 @@
package models
type APIError struct {
Code int `json:"-"`
Message string `json:"message"`
Slug string `json:"error"`
Cause error `json:"-"`
}
var (
ErrBadRequest = &APIError{Code: 400, Slug: "bad_request", Message: "Invalid request"}
ErrUnauthorized = &APIError{Code: 401, Slug: "unauthorized", Message: "Incorrect credentials"}
ErrForbidden = &APIError{Code: 403, Slug: "forbidden", Message: "Forbidden"}
ErrInsufficientScope = &APIError{Code: 403, Slug: "insufficient_scope", Message: "The access token does not contain the required scope"}
ErrNotFound = &APIError{Code: 404, Slug: "not_found", Message: "Resource not found"}
ErrAlreadyExists = &APIError{Code: 409, Slug: "already_exists", Message: "Resource already exists"}
ErrInternal = &APIError{Code: 500, Slug: "internal", Message: "Internal server error"}
)
func (e *APIError) Error() string {
return e.Slug
}
func (e *APIError) WithMessage(msg string) *APIError {
if e == nil {
return (&APIError{Code: 500, Slug: "internal", Message: "Internal server error"}).WithMessage(msg)
}
cp := *e
cp.Message = msg
return &cp
}
func (e *APIError) WithCause(cause error) *APIError {
if e == nil {
return (&APIError{Code: 500, Slug: "internal", Message: "Internal server error"}).WithCause(cause)
}
cp := *e
cp.Cause = cause
return &cp
}
func (e *APIError) Unwrap() error {
if e == nil {
return nil
}
return e.Cause
}
@@ -0,0 +1,58 @@
package models
import (
"encoding/json"
"time"
"github.com/google/uuid"
)
type OAuthClient struct {
ID uuid.UUID `db:"id" json:"id"`
ClientID string `db:"client_id" json:"client_id"`
ClientSecret string `db:"client_secret" json:"client_secret"`
Name string `db:"name" json:"name"`
RedirectURIs json.RawMessage `db:"redirect_uris" json:"redirect_uris"`
GrantTypes json.RawMessage `db:"grant_types" json:"grant_types"`
Scopes json.RawMessage `db:"scopes" json:"scopes,omitempty"`
IsActive bool `db:"is_active" json:"is_active"`
Trusted bool `db:"trusted" json:"trusted"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
type RefreshTokenRow struct {
ID uuid.UUID `db:"id"`
TokenHash string `db:"token_hash"`
UserID uuid.UUID `db:"user_id"`
ClientID uuid.UUID `db:"client_id"`
Scopes json.RawMessage `db:"scopes"`
ExpiresAt time.Time `db:"expires_at"`
CreatedAt time.Time `db:"created_at"`
}
type AuthorizationCodeRow struct {
ID uuid.UUID `db:"id"`
CodeHash string `db:"code_hash"`
UserID uuid.UUID `db:"user_id"`
ClientID uuid.UUID `db:"client_id"`
RedirectURI string `db:"redirect_uri"`
Scopes json.RawMessage `db:"scopes"`
CodeChallenge string `db:"code_challenge"`
CodeChallengeMethod string `db:"code_challenge_method"`
ExpiresAt time.Time `db:"expires_at"`
ConsumedAt *time.Time `db:"consumed_at"`
CreatedAt time.Time `db:"created_at"`
}
type UserConsent struct {
ID uuid.UUID `json:"id"`
UserID uuid.UUID `json:"-"`
ClientID uuid.UUID `json:"-"`
ClientIdentifier string `json:"client_id"`
ClientName string `json:"client_name"`
Scopes []string `json:"scopes"`
AuthorizedAt time.Time `json:"authorized_at"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
}
@@ -0,0 +1,36 @@
package models
import (
"time"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID `db:"id" json:"id"`
Email string `db:"email" json:"email"`
PasswordHash string `db:"password_hash" json:"-"`
FirstName string `db:"first_name" json:"first_name"`
SecondName string `db:"second_name" json:"second_name"`
BirthDate *time.Time `db:"birth_date" json:"birth_date,omitempty"`
Sex string `db:"sex" json:"sex"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
type UserRegisterInput struct {
Email string `json:"email" binding:"required,min=3"`
Password string `json:"password" binding:"required,min=8"`
FirstName string `json:"first_name" binding:"required,min=2,max=64"`
SecondName string `json:"second_name" binding:"required,min=2,max=64"`
BirthDate *time.Time `json:"birth_date" binding:"omitempty"`
Sex string `json:"sex" binding:"required,oneof=MALE FEMALE"`
}
type UserUpdateInput struct {
FirstName string `json:"first_name" binding:"omitempty,min=2,max=64"`
SecondName string `json:"second_name" binding:"omitempty,min=2,max=64"`
BirthDate *time.Time `json:"birth_date"`
Sex string `json:"sex" binding:"omitempty,oneof=MALE FEMALE"`
Password string `json:"password" binding:"omitempty,min=8"`
}
@@ -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
}
@@ -0,0 +1,135 @@
package services
import (
"context"
"encoding/json"
"strings"
"time"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
type TokenInfo struct {
UserID uuid.UUID
Scopes []string
ClientID uuid.UUID
}
func (s *Service) GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error) {
return s.users.GetUserByID(ctx, id)
}
func (s *Service) Register(ctx context.Context, input models.UserRegisterInput) (*models.User, error) {
if s.users.IsUserExistsByEmail(ctx, input.Email) {
return nil, models.ErrAlreadyExists
}
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
return nil, models.ErrInternal
}
return s.users.CreateUser(ctx, models.User{
Email: input.Email,
PasswordHash: string(hash),
FirstName: input.FirstName,
SecondName: input.SecondName,
BirthDate: input.BirthDate,
Sex: input.Sex,
})
}
func (s *Service) RefreshTokens(ctx context.Context, rawToken string) (*TokenPair, error) {
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
if err != nil {
return nil, models.ErrUnauthorized
}
if time.Now().After(row.ExpiresAt) {
return nil, models.ErrUnauthorized
}
client, err := s.oauth.GetOAuthClientByID(ctx, row.ClientID)
if err != nil {
return nil, models.ErrInternal
}
scopes := scopesFromJSON(row.Scopes)
if !ScopesAllowed(client.Scopes, scopes) {
return nil, ErrInvalidGrant
}
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
return nil, models.ErrInternal
}
user, err := s.users.GetUserByID(ctx, row.UserID)
if err != nil {
return nil, models.ErrUnauthorized
}
return s.issuePair(ctx, user, client.ID, scopes)
}
func (s *Service) ValidateAccessToken(ctx context.Context, token string) (*TokenInfo, error) {
token = strings.TrimSpace(token)
if token == "" {
return nil, models.ErrUnauthorized
}
data, err := s.redis.Get(ctx, accessTokenPrefix+token).Bytes()
if err != nil {
return nil, models.ErrUnauthorized
}
var info struct {
UserID uuid.UUID `json:"user_id"`
Scopes []string `json:"scopes"`
ClientID uuid.UUID `json:"client_id"`
}
if err := json.Unmarshal(data, &info); err != nil {
return nil, models.ErrUnauthorized
}
return &TokenInfo{UserID: info.UserID, Scopes: info.Scopes, ClientID: info.ClientID}, nil
}
func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input models.UserUpdateInput) (*models.User, error) {
user, err := s.users.GetUserByID(ctx, userID)
if err != nil {
return nil, models.ErrNotFound
}
if input.FirstName != "" {
user.FirstName = input.FirstName
}
if input.SecondName != "" {
user.SecondName = input.SecondName
}
if input.BirthDate != nil {
user.BirthDate = input.BirthDate
}
if input.Sex != "" {
user.Sex = input.Sex
}
if input.Password != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
return nil, models.ErrInternal
}
user.PasswordHash = string(hash)
}
user.UpdatedAt = time.Now()
return s.users.UpdateUser(ctx, *user)
}
func (s *Service) DeleteProfile(ctx context.Context, userID uuid.UUID, accessToken string) error {
if err := s.users.DeleteUser(ctx, userID); err != nil {
return models.ErrInternal
}
_ = s.redis.Del(ctx, accessTokenPrefix+accessToken)
return nil
}
@@ -0,0 +1,54 @@
package services
import (
"context"
"fmt"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
)
func (s *Service) GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error) {
return s.oauth.GetUserConsents(ctx, userID)
}
func (s *Service) HasUserConsent(ctx context.Context, userId uuid.UUID, clientId uuid.UUID, scopes []string) bool {
allConsents, err := s.oauth.GetUserConsentsByClientID(ctx, userId, clientId)
if err != nil {
return false
}
consents := make(map[string]bool)
for _, scopes := range allConsents {
for _, scope := range scopes.Scopes {
consents[scope] = true
}
}
for _, scope := range scopes {
if !consents[scope] {
return false
}
}
return true
}
func (s *Service) RevokeConsent(ctx context.Context, userID uuid.UUID, clientID string) error {
client, err := s.oauth.GetOAuthClientByClientID(ctx, clientID)
if err != nil {
return models.ErrNotFound
}
if err := s.oauth.RevokeConsent(ctx, userID, client.ID, &userID); err != nil {
return err
}
tokens, _ := s.redis.SMembers(ctx, fmt.Sprintf("user_client_tokens:%s:%s", userID, client.ID)).Result()
for _, token := range tokens {
s.redis.Del(ctx, accessTokenPrefix+token)
}
s.redis.Del(ctx, fmt.Sprintf("user_client_tokens:%s:%s", userID, client.ID))
return nil
}
@@ -0,0 +1,132 @@
package services
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
)
func newOpaqueToken(nBytes int) (string, error) {
b := make([]byte, nBytes)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func sha256Hex(v string) string {
h := sha256.Sum256([]byte(v))
return hex.EncodeToString(h[:])
}
func pkceVerifyS256(verifier, challenge string) bool {
sum := sha256.Sum256([]byte(verifier))
got := base64.RawURLEncoding.EncodeToString(sum[:])
return subtle.ConstantTimeCompare([]byte(got), []byte(challenge)) == 1
}
func parseScopes(scope string) []string {
scope = strings.TrimSpace(scope)
if scope == "" {
return nil
}
seen := make(map[string]struct{})
var out []string
for _, p := range strings.Fields(scope) {
if _, dup := seen[p]; !dup {
seen[p] = struct{}{}
out = append(out, p)
}
}
return out
}
func ScopesAllowed(clientScopesJSON json.RawMessage, requested []string) bool {
if len(requested) == 0 {
return true
}
allowed := scopesFromJSON(clientScopesJSON)
set := make(map[string]struct{}, len(allowed))
for _, a := range allowed {
set[a] = struct{}{}
}
for _, r := range requested {
if _, ok := set[r]; !ok {
return false
}
}
return true
}
func scopesFromJSON(b json.RawMessage) []string {
if len(b) == 0 {
return nil
}
var out []string
_ = json.Unmarshal(b, &out)
return out
}
func redirectURIMatches(redirectURIsJSON json.RawMessage, redirectURI string) bool {
var uris []string
if err := json.Unmarshal(redirectURIsJSON, &uris); err != nil {
return false
}
for _, u := range uris {
if u == redirectURI {
return true
}
}
return false
}
func verifyClientSecret(stored, provided string) bool {
if stored == "" {
return true
}
if provided == "" {
return false
}
if strings.HasPrefix(stored, "$2") {
return bcrypt.CompareHashAndPassword([]byte(stored), []byte(provided)) == nil
}
return subtle.ConstantTimeCompare([]byte(stored), []byte(provided)) == 1
}
func HashClientSecret(secret string) (string, error) {
if secret == "" {
return "", nil
}
b, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
if err != nil {
return "", fmt.Errorf("hash client secret: %w", err)
}
return string(b), nil
}
func bcryptCompare(hash, password string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}
func ScopesContain(tokenScopes []string, required []string) bool {
if len(required) == 0 {
return true
}
set := make(map[string]struct{}, len(tokenScopes))
for _, s := range tokenScopes {
set[s] = struct{}{}
}
for _, r := range required {
if _, ok := set[r]; !ok {
return false
}
}
return true
}
@@ -0,0 +1,358 @@
package services
import (
"context"
"encoding/json"
"net/url"
"strings"
"time"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
)
type OAuthSession struct {
ClientID string `json:"client_id"`
ClientName string `json:"client_name"`
RedirectURI string `json:"redirect_uri"`
Scopes []string `json:"scopes"`
State string `json:"state"`
CodeChallenge string `json:"code_challenge"`
CodeChallengeMethod string `json:"code_challenge_method"`
UserID uuid.UUID `json:"user_id,omitempty"`
}
type TokenPair struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token,omitempty"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
Scope string `json:"scope,omitempty"`
User *models.User `json:"user,omitempty"`
}
func (s *Service) CreateOAuthSession(
ctx context.Context,
clientID, redirectURI, scope, state, codeChallenge, codeChallengeMethod string,
) (string, error) {
if clientID == "" || redirectURI == "" || codeChallenge == "" {
return "", ErrInvalidRequest
}
if codeChallengeMethod != "" && codeChallengeMethod != "S256" {
return "", ErrInvalidRequest
}
client, err := s.oauth.GetOAuthClientByClientID(ctx, clientID)
if err != nil {
return "", ErrUnauthorizedClient
}
if !redirectURIMatches(client.RedirectURIs, redirectURI) {
return "", ErrInvalidRequest
}
scopes := parseScopes(scope)
if len(scopes) > 0 && !ScopesAllowed(client.Scopes, scopes) {
return "", ErrInvalidRequest
}
token, err := newOpaqueToken(24)
if err != nil {
return "", models.ErrInternal
}
sess := OAuthSession{
ClientID: client.ClientID,
ClientName: client.Name,
RedirectURI: redirectURI,
Scopes: scopes,
State: state,
CodeChallenge: codeChallenge,
CodeChallengeMethod: "S256",
}
if err := s.saveSession(ctx, token, &sess); err != nil {
return "", models.ErrInternal
}
return token, nil
}
func (s *Service) GetOAuthSession(ctx context.Context, token string) (*OAuthSession, error) {
data, err := s.redis.Get(ctx, oauthSessionPrefix+token).Bytes()
if err != nil {
return nil, ErrInvalidGrant
}
var sess OAuthSession
if err := json.Unmarshal(data, &sess); err != nil {
return nil, ErrInvalidGrant
}
return &sess, nil
}
func (s *Service) saveSession(ctx context.Context, token string, sess *OAuthSession) error {
data, _ := json.Marshal(sess)
return s.redis.Set(ctx, oauthSessionPrefix+token, data, oauthSessionTTL).Err()
}
func (s *Service) SessionLogin(ctx context.Context, token, email, password string) (string, error) {
sess, err := s.GetOAuthSession(ctx, token)
if err != nil {
return "", err
}
user, err := s.users.GetUserByEmail(ctx, email)
if err != nil || bcryptCompare(user.PasswordHash, password) != nil {
return "", models.ErrUnauthorized
}
sess.UserID = user.ID
if err := s.saveSession(ctx, token, sess); err != nil {
return "", models.ErrInternal
}
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
if err != nil {
return "", ErrInvalidClient
}
if client.Trusted {
return s.SessionApprove(ctx, token)
}
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
if hasUserConsents {
return s.SessionApprove(ctx, token)
}
return "", nil
}
func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken string) (string, error) {
info, err := s.ValidateAccessToken(ctx, accessToken)
if err != nil {
return "", models.ErrUnauthorized
}
sess, err := s.GetOAuthSession(ctx, sessionToken)
if err != nil {
return "", err
}
sess.UserID = info.UserID
if err := s.saveSession(ctx, sessionToken, sess); err != nil {
return "", models.ErrInternal
}
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
if err != nil {
return "", ErrInvalidClient
}
if client.Trusted {
return s.SessionApprove(ctx, sessionToken)
}
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
if hasUserConsents {
return s.SessionApprove(ctx, sessionToken)
}
return "", nil
}
func (s *Service) SessionApprove(ctx context.Context, token string) (string, error) {
sess, err := s.GetOAuthSession(ctx, token)
if err != nil {
return "", err
}
if sess.UserID == uuid.Nil {
return "", ErrInvalidGrant
}
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
if err != nil {
return "", ErrInvalidClient
}
code, err := s.createAuthCode(ctx, sess.UserID, client.ID, sess.RedirectURI, sess.Scopes, sess.CodeChallenge)
if err != nil {
return "", err
}
_ = s.redis.Del(ctx, oauthSessionPrefix+token)
s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
redirectURL, _ := url.Parse(sess.RedirectURI)
q := redirectURL.Query()
q.Set("code", code)
if sess.State != "" {
q.Set("state", sess.State)
}
redirectURL.RawQuery = q.Encode()
return redirectURL.String(), nil
}
func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redirectURI, codeVerifier string) (*TokenPair, error) {
if auth.ClientID == "" || code == "" || redirectURI == "" || codeVerifier == "" {
return nil, ErrInvalidRequest
}
client, err := s.AuthenticateClient(ctx, auth)
if err != nil {
return nil, err
}
row, err := s.oauth.GetAuthorizationCodeByHash(ctx, sha256Hex(code))
if err != nil || row.ConsumedAt != nil || time.Now().After(row.ExpiresAt) {
return nil, ErrInvalidGrant
}
if row.ClientID != client.ID || row.RedirectURI != redirectURI {
return nil, ErrInvalidGrant
}
if !pkceVerifyS256(codeVerifier, row.CodeChallenge) {
return nil, ErrInvalidGrant
}
if err := s.oauth.ConsumeAuthorizationCodeByID(ctx, row.ID); err != nil {
return nil, models.ErrInternal
}
user, err := s.users.GetUserByID(ctx, row.UserID)
if err != nil {
return nil, models.ErrInternal
}
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
return s.issuePair(ctx, user, client.ID, scopesFromJSON(row.Scopes))
}
func (s *Service) ExchangeRefreshToken(ctx context.Context, auth ClientAuth, rawToken string) (*TokenPair, error) {
if auth.ClientID == "" || rawToken == "" {
return nil, ErrInvalidRequest
}
client, err := s.AuthenticateClient(ctx, auth)
if err != nil {
return nil, err
}
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
if err != nil || time.Now().After(row.ExpiresAt) || row.ClientID != client.ID {
return nil, ErrInvalidGrant
}
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
return nil, models.ErrInternal
}
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
user, err := s.users.GetUserByID(ctx, row.UserID)
if err != nil {
return nil, models.ErrInternal
}
scopes := scopesFromJSON(row.Scopes)
if !ScopesAllowed(client.Scopes, scopes) {
return nil, ErrInvalidGrant
}
return s.issuePair(ctx, user, client.ID, scopes)
}
func (s *Service) RevokeToken(ctx context.Context, auth ClientAuth, rawToken string) error {
client, err := s.AuthenticateClient(ctx, auth)
if err != nil {
return err
}
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
if err != nil || row.ClientID != client.ID {
return nil
}
_ = s.oauth.DeleteRefreshTokenByID(ctx, row.ID)
return nil
}
func (s *Service) createAuthCode(
ctx context.Context,
userID, clientID uuid.UUID,
redirectURI string,
scopes []string,
codeChallenge string,
) (string, error) {
rawCode, err := newOpaqueToken(32)
if err != nil {
return "", models.ErrInternal
}
scopeJSON, _ := json.Marshal(scopes)
now := time.Now()
_, err = s.oauth.CreateAuthorizationCode(ctx, models.AuthorizationCodeRow{
CodeHash: sha256Hex(rawCode),
UserID: userID,
ClientID: clientID,
RedirectURI: redirectURI,
Scopes: scopeJSON,
CodeChallenge: codeChallenge,
CodeChallengeMethod: "S256",
ExpiresAt: now.Add(5 * time.Minute),
CreatedAt: now,
})
if err != nil {
return "", models.ErrInternal
}
return rawCode, nil
}
func (s *Service) issuePair(ctx context.Context, user *models.User, clientID uuid.UUID, scopes []string) (*TokenPair, error) {
accessToken, err := newOpaqueToken(32)
if err != nil {
return nil, models.ErrInternal
}
rawRefresh, err := newOpaqueToken(32)
if err != nil {
return nil, models.ErrInternal
}
scopeJSON, _ := json.Marshal(scopes)
now := time.Now()
accessData := struct {
UserID uuid.UUID `json:"user_id"`
Scopes []string `json:"scopes"`
ClientID uuid.UUID `json:"client_id"`
}{
UserID: user.ID,
Scopes: scopes,
ClientID: clientID,
}
data, _ := json.Marshal(accessData)
if err := s.redis.Set(ctx, accessTokenPrefix+accessToken, data, s.tokens.AccessTTL).Err(); err != nil {
return nil, models.ErrInternal
}
_, err = s.oauth.CreateRefreshToken(ctx, models.RefreshTokenRow{
TokenHash: sha256Hex(rawRefresh),
UserID: user.ID,
ClientID: clientID,
Scopes: scopeJSON,
ExpiresAt: now.Add(s.tokens.RefreshTTL),
CreatedAt: now,
})
if err != nil {
return nil, models.ErrInternal
}
return &TokenPair{
AccessToken: accessToken,
RefreshToken: rawRefresh,
TokenType: "Bearer",
ExpiresIn: int64(s.tokens.AccessTTL.Seconds()),
Scope: strings.Join(scopes, " "),
User: user,
}, nil
}
@@ -0,0 +1,96 @@
package services
import (
"context"
"errors"
"time"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
var (
ErrInvalidRequest = errors.New("invalid_request")
ErrUnauthorizedClient = errors.New("unauthorized_client")
ErrInvalidClient = errors.New("invalid_client")
ErrInvalidGrant = errors.New("invalid_grant")
ErrUnsupportedGrantType = errors.New("unsupported_grant_type")
ErrAccessDenied = errors.New("access_denied")
)
type UserRepo interface {
CreateUser(ctx context.Context, user models.User) (*models.User, error)
UpdateUser(ctx context.Context, user models.User) (*models.User, error)
DeleteUser(ctx context.Context, id uuid.UUID) error
GetUserByEmail(ctx context.Context, email string) (*models.User, error)
GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error)
IsUserExistsByEmail(ctx context.Context, email string) bool
}
type OAuthRepo interface {
GetOAuthClientByClientID(ctx context.Context, clientID string) (*models.OAuthClient, error)
GetOAuthClientByID(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error)
CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error)
GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error)
ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error
CreateRefreshToken(ctx context.Context, row models.RefreshTokenRow) (*models.RefreshTokenRow, error)
GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error)
DeleteRefreshTokenByID(ctx context.Context, id uuid.UUID) error
RecordUserConsent(ctx context.Context, userID, clientID uuid.UUID, scopes []string) error
GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error)
UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error
GetUserConsentsByClientID(ctx context.Context, userID uuid.UUID, clientID uuid.UUID) ([]models.UserConsent, error)
RevokeConsent(ctx context.Context, userID, clientID uuid.UUID, revokedBy *uuid.UUID) error
}
type TokenConfig struct {
AccessTTL time.Duration
RefreshTTL time.Duration
}
type ClientAuth struct {
ClientID string
ClientSecret string
}
type Service struct {
users UserRepo
oauth OAuthRepo
redis *redis.Client
tokens TokenConfig
basicClient *models.OAuthClient
}
func New(
users UserRepo,
oauth OAuthRepo,
rdb *redis.Client,
tokenCfg TokenConfig,
basicClient *models.OAuthClient,
) *Service {
return &Service{
users: users,
oauth: oauth,
redis: rdb,
tokens: tokenCfg,
basicClient: basicClient,
}
}
func (s *Service) AuthenticateClient(ctx context.Context, auth ClientAuth) (*models.OAuthClient, error) {
client, err := s.oauth.GetOAuthClientByClientID(ctx, auth.ClientID)
if err != nil {
return nil, ErrInvalidClient
}
if !verifyClientSecret(client.ClientSecret, auth.ClientSecret) {
return nil, ErrInvalidClient
}
return client, nil
}
const (
oauthSessionPrefix = "oauth_session:"
accessTokenPrefix = "access_token:"
oauthSessionTTL = 10 * time.Minute
)