feat: ci/cd
This commit is contained in:
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/dusiburg/kotosoft-id/internal/config"
|
||||
"github.com/dusiburg/kotosoft-id/internal/db"
|
||||
"github.com/dusiburg/kotosoft-id/internal/handlers"
|
||||
apphttp "github.com/dusiburg/kotosoft-id/internal/http"
|
||||
http "github.com/dusiburg/kotosoft-id/internal/http"
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||
@@ -17,64 +17,70 @@ import (
|
||||
func main() {
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
log.Fatalf("config: %v", err)
|
||||
}
|
||||
|
||||
pg, err := db.ConnectPostgres(cfg.Postgres.URL)
|
||||
postgres, err := db.ConnectPostgres(cfg.Postgres.URL)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
log.Fatalf("postgres: %v", err)
|
||||
}
|
||||
if err := db.RunMigrations(cfg.Postgres.MigrationFilePath, postgres.Pool); err != nil {
|
||||
log.Fatalf("migrations: %v", err)
|
||||
}
|
||||
|
||||
if err := db.RunMigrations(cfg.Postgres.MigrationFilePath, pg.Pool); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
rdb, err := db.ConnectRedis(cfg.Redis.URL)
|
||||
redis, err := db.ConnectRedis(cfg.Redis.URL)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
log.Fatalf("redis: %v", err)
|
||||
}
|
||||
|
||||
userRepo := repositories.NewUserRepository(pg.Pool)
|
||||
oauthRepo := repositories.NewOAuthRepository(pg.Pool)
|
||||
userRepo := repositories.NewUserRepository(postgres.Pool)
|
||||
oauthRepo := repositories.NewOAuthRepository(postgres.Pool)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
basicClient, err := ensureBasicClient(ctx, cfg, oauthRepo)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
if err := seedClient(context.Background(), oauthRepo, cfg.Client); err != nil {
|
||||
log.Fatalf("seed client: %v", err)
|
||||
}
|
||||
|
||||
svc := services.New(userRepo, oauthRepo, rdb.Client, services.TokenConfig{
|
||||
AccessTTL: cfg.JWT.TTL,
|
||||
RefreshTTL: cfg.JWT.TTL * 7,
|
||||
}, basicClient)
|
||||
svc := services.New(
|
||||
userRepo,
|
||||
oauthRepo,
|
||||
redis.Client,
|
||||
services.TokenConfig{
|
||||
AccessTTL: cfg.JWT.TTL,
|
||||
RefreshTTL: cfg.JWT.TTL * 7,
|
||||
},
|
||||
)
|
||||
|
||||
limiter := services.NewRateLimiter(redis.Client)
|
||||
|
||||
authHandler := handlers.NewAuthHandler(svc)
|
||||
oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL)
|
||||
consentHandler := handlers.NewConsentHandler(svc)
|
||||
|
||||
r := apphttp.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo)
|
||||
log.Fatal(r.Run(cfg.Server.Addr))
|
||||
router := http.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo, limiter)
|
||||
|
||||
log.Printf("starting server on %s", cfg.Server.Addr)
|
||||
if err := router.Run(cfg.Server.Addr); err != nil {
|
||||
log.Fatalf("server: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func ensureBasicClient(ctx context.Context, cfg *config.Conf, repo *repositories.OAuthRepository) (*models.OAuthClient, error) {
|
||||
client, err := repo.GetOAuthClientByClientID(ctx, cfg.Client.ID)
|
||||
if err == nil {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
hashedSecret, err := services.HashClientSecret(cfg.Client.Secret)
|
||||
func seedClient(ctx context.Context, repo *repositories.OAuthRepository, cfg config.Client) error {
|
||||
hashedSecret, err := services.HashClientSecret(cfg.Secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
return repo.CreateOAuthClient(ctx, models.OAuthClient{
|
||||
ClientID: cfg.Client.ID,
|
||||
redirectURIsJSON, _ := json.Marshal(cfg.RedirectURIs)
|
||||
grantTypesJSON, _ := json.Marshal(cfg.GrantTypes)
|
||||
scopesJSON, _ := json.Marshal(cfg.Scopes)
|
||||
|
||||
return repo.UpsertClient(ctx, models.OAuthClient{
|
||||
ClientID: cfg.ID,
|
||||
ClientSecret: hashedSecret,
|
||||
Name: cfg.Client.Name,
|
||||
RedirectURIs: json.RawMessage(cfg.Client.RedirectURIsJSON()),
|
||||
GrantTypes: json.RawMessage(cfg.Client.GrantTypesJSON()),
|
||||
Scopes: json.RawMessage(cfg.Client.ScopesJSON()),
|
||||
Name: cfg.Name,
|
||||
RedirectURIs: redirectURIsJSON,
|
||||
GrantTypes: grantTypesJSON,
|
||||
Scopes: scopesJSON,
|
||||
Trusted: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
FROM golang:1.23-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||
-trimpath \
|
||||
-ldflags="-s -w" \
|
||||
-o /app/server \
|
||||
./cmd/server
|
||||
|
||||
FROM alpine:3.20
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /app/server .
|
||||
COPY --from=builder /app/migrations ./migrations
|
||||
|
||||
RUN addgroup -S app && adduser -S app -G app
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["./server"]
|
||||
@@ -30,13 +30,15 @@ func (h *AuthHandler) Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
service, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{ClientID: id, ClientSecret: secret})
|
||||
client, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{
|
||||
ClientID: id,
|
||||
ClientSecret: secret,
|
||||
})
|
||||
if err != nil {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if !service.Trusted {
|
||||
if !client.Trusted {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
@@ -59,12 +61,23 @@ func (h *AuthHandler) Refresh(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
pair, err := h.svc.RefreshTokens(c.Request.Context(), input.RefreshToken)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
id, secret, ok := c.Request.BasicAuth()
|
||||
if !ok {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
pair, err := h.svc.ExchangeRefreshToken(
|
||||
c.Request.Context(),
|
||||
services.ClientAuth{ClientID: id, ClientSecret: secret},
|
||||
input.RefreshToken,
|
||||
)
|
||||
if err != nil {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
pair.User = nil
|
||||
c.JSON(http.StatusOK, pair)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/handlers"
|
||||
"github.com/dusiburg/kotosoft-id/internal/middleware"
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||
@@ -11,7 +12,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, svc *services.Service, repo *repositories.OAuthRepository) *gin.Engine {
|
||||
func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, svc *services.Service, repo *repositories.OAuthRepository, limiter *services.RateLimiter) *gin.Engine {
|
||||
r := gin.Default()
|
||||
r.Use(errorMiddleware())
|
||||
|
||||
@@ -19,7 +20,7 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
||||
{
|
||||
o.GET("/authorize", oauth.Authorize)
|
||||
o.GET("/session/:token", oauth.GetSession)
|
||||
o.POST("/session/login", oauth.SessionLogin)
|
||||
o.POST("/session/login", middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn), oauth.SessionLogin)
|
||||
o.POST("/session/attach", oauth.SessionAttach)
|
||||
o.POST("/session/approve", oauth.SessionApprove)
|
||||
o.POST("/token", oauth.Token)
|
||||
@@ -29,7 +30,7 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
a := api.Group("/auth")
|
||||
a.POST("/register", auth.Register)
|
||||
a.POST("/register", middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")), auth.Register)
|
||||
a.POST("/refresh", auth.Refresh)
|
||||
|
||||
me := api.Group("/me")
|
||||
@@ -65,7 +66,7 @@ func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, r
|
||||
return
|
||||
}
|
||||
|
||||
if err, _ := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil {
|
||||
if _, err := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil {
|
||||
c.Error(models.ErrForbidden)
|
||||
c.Abort()
|
||||
return
|
||||
@@ -93,16 +94,6 @@ func errorMiddleware() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
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 ")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func RateLimit(
|
||||
limiter *services.RateLimiter,
|
||||
cfg services.RateLimitConfig,
|
||||
keyFn func(c *gin.Context) string,
|
||||
) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
key := keyFn(c)
|
||||
|
||||
allowed, remaining, _ := limiter.Allow(c.Request.Context(), key, cfg)
|
||||
|
||||
c.Header("X-RateLimit-Limit", itoa(cfg.Max))
|
||||
c.Header("X-RateLimit-Remaining", itoa(remaining))
|
||||
|
||||
if !allowed {
|
||||
c.JSON(http.StatusTooManyRequests, models.ErrTooManyRequests)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func LoginKeyFn(c *gin.Context) string {
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
_ = c.ShouldBindBodyWithJSON(&body)
|
||||
if body.Email != "" {
|
||||
return "login:" + c.ClientIP() + ":" + body.Email
|
||||
}
|
||||
return "login:" + c.ClientIP()
|
||||
}
|
||||
|
||||
func IPKeyFn(prefix string) func(c *gin.Context) string {
|
||||
return func(c *gin.Context) string {
|
||||
return prefix + ":" + c.ClientIP()
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
if n < 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
buf := make([]byte, 0, 10)
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
for n > 0 {
|
||||
buf = append([]byte{byte('0' + n%10)}, buf...)
|
||||
n /= 10
|
||||
}
|
||||
return string(buf)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ var (
|
||||
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"}
|
||||
ErrTooManyRequests = &APIError{Code: 429, Slug: "too_many_requests", Message: "Too many requests"}
|
||||
ErrInternal = &APIError{Code: 500, Slug: "internal", Message: "Internal server error"}
|
||||
)
|
||||
|
||||
|
||||
@@ -20,12 +20,11 @@ func NewOAuthRepository(db *pgxpool.Pool) *OAuthRepository {
|
||||
|
||||
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).
|
||||
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)
|
||||
}
|
||||
@@ -37,7 +36,11 @@ func (r *OAuthRepository) GetOAuthClientByClientID(ctx context.Context, clientID
|
||||
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)
|
||||
`, 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
|
||||
}
|
||||
@@ -49,7 +52,11 @@ func (r *OAuthRepository) GetOAuthClientByID(ctx context.Context, id uuid.UUID)
|
||||
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)
|
||||
`, 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
|
||||
}
|
||||
@@ -61,8 +68,11 @@ func (r *OAuthRepository) CreateAuthorizationCode(ctx context.Context, row model
|
||||
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)
|
||||
`, 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)
|
||||
}
|
||||
@@ -74,7 +84,11 @@ func (r *OAuthRepository) GetAuthorizationCodeByHash(ctx context.Context, codeHa
|
||||
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)
|
||||
`, 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
|
||||
}
|
||||
@@ -107,7 +121,10 @@ func (r *OAuthRepository) GetRefreshTokenByHash(ctx context.Context, tokenHash s
|
||||
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)
|
||||
`, tokenHash).Scan(
|
||||
&row.ID, &row.TokenHash, &row.UserID, &row.ClientID,
|
||||
&row.Scopes, &row.ExpiresAt, &row.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -119,32 +136,27 @@ func (r *OAuthRepository) DeleteRefreshTokenByID(ctx context.Context, id uuid.UU
|
||||
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
|
||||
)
|
||||
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()
|
||||
DO UPDATE SET scopes = EXCLUDED.scopes, last_used_at = now()
|
||||
`, userID, clientID, scopeJSON)
|
||||
|
||||
return err
|
||||
@@ -154,14 +166,13 @@ func (r *OAuthRepository) GetUserConsents(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) ([]models.UserConsent, error) {
|
||||
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT
|
||||
SELECT
|
||||
uc.id,
|
||||
uc.user_id,
|
||||
uc.client_id,
|
||||
oc.client_id AS client_identifier,
|
||||
oc.name AS client_name,
|
||||
oc.name AS client_name,
|
||||
uc.scopes,
|
||||
uc.authorized_at,
|
||||
uc.last_used_at,
|
||||
@@ -173,52 +184,18 @@ func (r *OAuthRepository) GetUserConsents(
|
||||
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
|
||||
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()
|
||||
@@ -227,12 +204,7 @@ func (r *OAuthRepository) UpdateConsentLastUsed(
|
||||
AND revoked_at IS NULL
|
||||
AND (expires_at IS NULL OR expires_at > now())
|
||||
`, userID, clientID)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *OAuthRepository) GetUserConsentsByClientID(
|
||||
@@ -240,49 +212,96 @@ func (r *OAuthRepository) GetUserConsentsByClientID(
|
||||
userID uuid.UUID,
|
||||
clientID uuid.UUID,
|
||||
) ([]models.UserConsent, error) {
|
||||
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT
|
||||
SELECT
|
||||
uc.id,
|
||||
uc.user_id,
|
||||
uc.client_id,
|
||||
oc.client_id AS client_identifier,
|
||||
oc.name AS client_name,
|
||||
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())
|
||||
AND uo.id = $2
|
||||
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
|
||||
|
||||
err := rows.Scan(
|
||||
&c.ID,
|
||||
&c.UserID,
|
||||
&c.ClientID,
|
||||
&c.ClientIdentifier,
|
||||
&c.ClientName,
|
||||
if err := rows.Scan(
|
||||
&c.ID, &c.UserID, &c.ClientID,
|
||||
&c.ClientIdentifier, &c.ClientName,
|
||||
&scopeJSON,
|
||||
&c.AuthorizedAt,
|
||||
&c.LastUsedAt,
|
||||
&c.RevokedAt,
|
||||
)
|
||||
if err != nil {
|
||||
&c.AuthorizedAt, &c.LastUsedAt, &c.RevokedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -299,41 +318,3 @@ func (r *OAuthRepository) GetUserConsentsByClientID(
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -41,38 +41,6 @@ func (s *Service) Register(ctx context.Context, input models.UserRegisterInput)
|
||||
})
|
||||
}
|
||||
|
||||
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 == "" {
|
||||
@@ -105,15 +73,19 @@ func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input mod
|
||||
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 {
|
||||
@@ -121,15 +93,22 @@ func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input mod
|
||||
}
|
||||
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.oauth.DeleteRefreshTokensByUserID(ctx, userID); err != nil {
|
||||
return models.ErrInternal
|
||||
}
|
||||
|
||||
if err := s.users.DeleteUser(ctx, userID); err != nil {
|
||||
return models.ErrInternal
|
||||
}
|
||||
|
||||
_ = s.redis.Del(ctx, accessTokenPrefix+accessToken)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -96,12 +96,12 @@ func (s *Service) saveSession(ctx context.Context, token string, sess *OAuthSess
|
||||
func (s *Service) SessionLogin(ctx context.Context, token, email, password string) (string, error) {
|
||||
sess, err := s.GetOAuthSession(ctx, token)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", ErrInvalidGrant
|
||||
}
|
||||
|
||||
user, err := s.users.GetUserByEmail(ctx, email)
|
||||
if err != nil || bcryptCompare(user.PasswordHash, password) != nil {
|
||||
return "", models.ErrUnauthorized
|
||||
return "", ErrAccessDenied
|
||||
}
|
||||
|
||||
sess.UserID = user.ID
|
||||
@@ -114,12 +114,7 @@ func (s *Service) SessionLogin(ctx context.Context, token, email, password strin
|
||||
return "", ErrInvalidClient
|
||||
}
|
||||
|
||||
if client.Trusted {
|
||||
return s.SessionApprove(ctx, token)
|
||||
}
|
||||
|
||||
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||
if hasUserConsents {
|
||||
if client.Trusted || s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) {
|
||||
return s.SessionApprove(ctx, token)
|
||||
}
|
||||
|
||||
@@ -129,12 +124,12 @@ func (s *Service) SessionLogin(ctx context.Context, token, email, password strin
|
||||
func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken string) (string, error) {
|
||||
info, err := s.ValidateAccessToken(ctx, accessToken)
|
||||
if err != nil {
|
||||
return "", models.ErrUnauthorized
|
||||
return "", ErrAccessDenied
|
||||
}
|
||||
|
||||
sess, err := s.GetOAuthSession(ctx, sessionToken)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", ErrInvalidGrant
|
||||
}
|
||||
|
||||
sess.UserID = info.UserID
|
||||
@@ -146,12 +141,8 @@ func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken s
|
||||
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 {
|
||||
if client.Trusted || s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) {
|
||||
return s.SessionApprove(ctx, sessionToken)
|
||||
}
|
||||
|
||||
@@ -161,7 +152,7 @@ func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken s
|
||||
func (s *Service) SessionApprove(ctx context.Context, token string) (string, error) {
|
||||
sess, err := s.GetOAuthSession(ctx, token)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", ErrInvalidGrant
|
||||
}
|
||||
if sess.UserID == uuid.Nil {
|
||||
return "", ErrInvalidGrant
|
||||
@@ -178,7 +169,7 @@ func (s *Service) SessionApprove(ctx context.Context, token string) (string, err
|
||||
}
|
||||
|
||||
_ = s.redis.Del(ctx, oauthSessionPrefix+token)
|
||||
s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||
_ = s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||
|
||||
redirectURL, _ := url.Parse(sess.RedirectURI)
|
||||
q := redirectURL.Query()
|
||||
@@ -221,7 +212,7 @@ func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redir
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
|
||||
_ = s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
|
||||
|
||||
return s.issuePair(ctx, user, client.ID, scopesFromJSON(row.Scopes))
|
||||
}
|
||||
@@ -241,22 +232,22 @@ func (s *Service) ExchangeRefreshToken(ctx context.Context, auth ClientAuth, raw
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
|
||||
_ = 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)
|
||||
}
|
||||
|
||||
@@ -275,13 +266,7 @@ func (s *Service) RevokeToken(ctx context.Context, auth ClientAuth, rawToken str
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) createAuthCode(
|
||||
ctx context.Context,
|
||||
userID, clientID uuid.UUID,
|
||||
redirectURI string,
|
||||
scopes []string,
|
||||
codeChallenge string,
|
||||
) (string, error) {
|
||||
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
|
||||
@@ -330,6 +315,7 @@ func (s *Service) issuePair(ctx context.Context, user *models.User, clientID uui
|
||||
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
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RateLimitConfig struct {
|
||||
Max int
|
||||
Window time.Duration
|
||||
BlockFor time.Duration
|
||||
}
|
||||
|
||||
var (
|
||||
LoginRateLimit = RateLimitConfig{
|
||||
Max: 10,
|
||||
Window: 15 * time.Minute,
|
||||
BlockFor: 15 * time.Minute,
|
||||
}
|
||||
|
||||
RegisterRateLimit = RateLimitConfig{
|
||||
Max: 5,
|
||||
Window: time.Hour,
|
||||
}
|
||||
)
|
||||
|
||||
type RateLimiter struct {
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
func NewRateLimiter(rdb *redis.Client) *RateLimiter {
|
||||
return &RateLimiter{redis: rdb}
|
||||
}
|
||||
|
||||
func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig) (bool, int, error) {
|
||||
blockKey := fmt.Sprintf("rl_block:%s", key)
|
||||
counterKey := fmt.Sprintf("rl_count:%s", key)
|
||||
|
||||
if cfg.BlockFor > 0 {
|
||||
blocked, err := r.redis.Exists(ctx, blockKey).Result()
|
||||
if err != nil {
|
||||
return true, 0, nil
|
||||
}
|
||||
if blocked > 0 {
|
||||
return false, 0, nil
|
||||
}
|
||||
}
|
||||
|
||||
pipe := r.redis.Pipeline()
|
||||
incrCmd := pipe.Incr(ctx, counterKey)
|
||||
pipe.Expire(ctx, counterKey, cfg.Window)
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return true, 0, nil
|
||||
}
|
||||
|
||||
count := int(incrCmd.Val())
|
||||
remaining := cfg.Max - count
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
|
||||
if count > cfg.Max {
|
||||
if cfg.BlockFor > 0 {
|
||||
_ = r.redis.Set(ctx, blockKey, 1, cfg.BlockFor).Err()
|
||||
}
|
||||
return false, 0, nil
|
||||
}
|
||||
|
||||
return true, remaining, nil
|
||||
}
|
||||
|
||||
func (r *RateLimiter) Reset(ctx context.Context, key string) {
|
||||
_ = r.redis.Del(ctx, fmt.Sprintf("rl_count:%s", key), fmt.Sprintf("rl_block:%s", key))
|
||||
}
|
||||
@@ -37,6 +37,7 @@ type OAuthRepo interface {
|
||||
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
|
||||
DeleteRefreshTokensByUserID(ctx context.Context, userID 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
|
||||
@@ -55,11 +56,10 @@ type ClientAuth struct {
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users UserRepo
|
||||
oauth OAuthRepo
|
||||
redis *redis.Client
|
||||
tokens TokenConfig
|
||||
basicClient *models.OAuthClient
|
||||
users UserRepo
|
||||
oauth OAuthRepo
|
||||
redis *redis.Client
|
||||
tokens TokenConfig
|
||||
}
|
||||
|
||||
func New(
|
||||
@@ -67,14 +67,12 @@ func New(
|
||||
oauth OAuthRepo,
|
||||
rdb *redis.Client,
|
||||
tokenCfg TokenConfig,
|
||||
basicClient *models.OAuthClient,
|
||||
) *Service {
|
||||
return &Service{
|
||||
users: users,
|
||||
oauth: oauth,
|
||||
redis: rdb,
|
||||
tokens: tokenCfg,
|
||||
basicClient: basicClient,
|
||||
users: users,
|
||||
oauth: oauth,
|
||||
redis: rdb,
|
||||
tokens: tokenCfg,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user