feat: ci/cd
This commit is contained in:
+89
@@ -0,0 +1,89 @@
|
|||||||
|
kind: pipeline
|
||||||
|
type: docker
|
||||||
|
name: default
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: test backend
|
||||||
|
image: golang:1.25-alpine3.21
|
||||||
|
commands:
|
||||||
|
- cd kotosoft-id-backend
|
||||||
|
- go mod tidy
|
||||||
|
- go test ./...
|
||||||
|
|
||||||
|
- name: lint frontend
|
||||||
|
image: node:20-alpine
|
||||||
|
commands:
|
||||||
|
- cd kotosoft-id-frontend
|
||||||
|
- npm ci
|
||||||
|
- npm run lint
|
||||||
|
|
||||||
|
- name: build and push backend
|
||||||
|
image: docker:24
|
||||||
|
volumes:
|
||||||
|
- name: dockersock
|
||||||
|
path: /var/run/docker.sock
|
||||||
|
commands:
|
||||||
|
- docker build
|
||||||
|
-t localhost:5000/kotosoft_id_backend:latest
|
||||||
|
-f kotosoft-id-backend/Dockerfile
|
||||||
|
kotosoft-id-backend
|
||||||
|
- docker push localhost:5000/kotosoft_id_backend:latest
|
||||||
|
|
||||||
|
- name: build and push frontend
|
||||||
|
image: docker:24
|
||||||
|
volumes:
|
||||||
|
- name: dockersock
|
||||||
|
path: /var/run/docker.sock
|
||||||
|
commands:
|
||||||
|
- docker build
|
||||||
|
-t localhost:5000/kotosoft_id_frontend:latest
|
||||||
|
-f kotosoft-id-frontend/Dockerfile
|
||||||
|
kotosoft-id-frontend
|
||||||
|
- docker push localhost:5000/kotosoft_id_frontend:latest
|
||||||
|
|
||||||
|
- name: deploy
|
||||||
|
image: docker:24
|
||||||
|
volumes:
|
||||||
|
- name: dockersock
|
||||||
|
path: /var/run/docker.sock
|
||||||
|
- name: appdir
|
||||||
|
path: /opt/app
|
||||||
|
environment:
|
||||||
|
FRONTEND_URL:
|
||||||
|
from_secret: FRONTEND_URL
|
||||||
|
POSTGRES_URL:
|
||||||
|
from_secret: POSTGRES_URL
|
||||||
|
REDIS_URL:
|
||||||
|
from_secret: REDIS_URL
|
||||||
|
JWT_SECRET:
|
||||||
|
from_secret: JWT_SECRET
|
||||||
|
CLIENT_ID:
|
||||||
|
from_secret: CLIENT_ID
|
||||||
|
CLIENT_SECRET:
|
||||||
|
from_secret: CLIENT_SECRET
|
||||||
|
CLIENT_NAME:
|
||||||
|
from_secret: CLIENT_NAME
|
||||||
|
CLIENT_REDIRECT_URIS:
|
||||||
|
from_secret: CLIENT_REDIRECT_URIS
|
||||||
|
DOMAIN:
|
||||||
|
from_secret: DOMAIN
|
||||||
|
LETSENCRYPT_EMAIL:
|
||||||
|
from_secret: LETSENCRYPT_EMAIL
|
||||||
|
commands:
|
||||||
|
- apk add --no-cache docker-cli-compose
|
||||||
|
- cp docker-compose.yml /opt/app/docker-compose.yml
|
||||||
|
- cd /opt/app
|
||||||
|
- docker compose pull
|
||||||
|
- docker compose up -d --remove-orphans
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
- name: dockersock
|
||||||
|
host:
|
||||||
|
path: /var/run/docker.sock
|
||||||
|
- name: appdir
|
||||||
|
host:
|
||||||
|
path: /opt/drone/kotosoft-id
|
||||||
|
|
||||||
|
trigger:
|
||||||
|
branch:
|
||||||
|
- main
|
||||||
+2
-1
@@ -1,5 +1,6 @@
|
|||||||
kotosoft-id-frontend/node_modules
|
kotosoft-id-frontend/node_modules
|
||||||
kotosoft-id-frontend/.next/
|
kotosoft-id-frontend/.next
|
||||||
|
kotosoft-id-frontend/output
|
||||||
kotosoft-id-frontend/.env
|
kotosoft-id-frontend/.env
|
||||||
kotosoft-id-frontend/next-env.d.ts
|
kotosoft-id-frontend/next-env.d.ts
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
services:
|
||||||
|
kotosoft_id_backend:
|
||||||
|
image: host.docker.internal:5000/kotosoft_id_backend:latest
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
SERVER_ADDR: ":8080"
|
||||||
|
FRONTEND_URL: ${FRONTEND_URL}
|
||||||
|
POSTGRES_URL: ${POSTGRES_URL}
|
||||||
|
POSTGRES_MIGRATION_FILE_PATH: ./migrations/migrations.sql
|
||||||
|
REDIS_URL: ${REDIS_URL}
|
||||||
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
|
JWT_EXPIRATION_HOURS: ${JWT_EXPIRATION_HOURS:-24h}
|
||||||
|
|
||||||
|
CLIENT_ID: ${CLIENT_ID}
|
||||||
|
CLIENT_SECRET: ${CLIENT_SECRET}
|
||||||
|
CLIENT_NAME: ${CLIENT_NAME}
|
||||||
|
CLIENT_REDIRECT_URIS: ${CLIENT_REDIRECT_URIS}
|
||||||
|
expose:
|
||||||
|
- "8080"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
networks:
|
||||||
|
- kotosoft_id_network
|
||||||
|
|
||||||
|
kotosoft_id_frontend:
|
||||||
|
image: host.docker.internal:5000/kotosoft_id_frontend:latest
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
PUBLIC_URL: ${FRONTEND_URL}
|
||||||
|
KOTOSOFT_ID_API_URL: http://kotosoft_id_backend:8080
|
||||||
|
CLIENT_ID: ${CLIENT_ID}
|
||||||
|
CLIENT_SECRET: ${CLIENT_SECRET}
|
||||||
|
VIRTUAL_HOST: ${DOMAIN}
|
||||||
|
VIRTUAL_PORT: 3000
|
||||||
|
LETSENCRYPT_HOST: ${DOMAIN}
|
||||||
|
LETSENCRYPT_EMAIL: ${LETSENCRYPT_EMAIL}
|
||||||
|
expose:
|
||||||
|
- "3000"
|
||||||
|
depends_on:
|
||||||
|
- kotosoft_id_backend
|
||||||
|
networks:
|
||||||
|
- kotosoft_id_network
|
||||||
|
- proxy
|
||||||
|
|
||||||
|
networks:
|
||||||
|
kotosoft_id_net:
|
||||||
|
driver: bridge
|
||||||
|
proxy:
|
||||||
|
external: true
|
||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"github.com/dusiburg/kotosoft-id/internal/config"
|
"github.com/dusiburg/kotosoft-id/internal/config"
|
||||||
"github.com/dusiburg/kotosoft-id/internal/db"
|
"github.com/dusiburg/kotosoft-id/internal/db"
|
||||||
"github.com/dusiburg/kotosoft-id/internal/handlers"
|
"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/models"
|
||||||
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
||||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||||
@@ -17,64 +17,70 @@ import (
|
|||||||
func main() {
|
func main() {
|
||||||
cfg, err := config.New()
|
cfg, err := config.New()
|
||||||
if err != nil {
|
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 {
|
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 {
|
redis, err := db.ConnectRedis(cfg.Redis.URL)
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
rdb, err := db.ConnectRedis(cfg.Redis.URL)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatalf("redis: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
userRepo := repositories.NewUserRepository(pg.Pool)
|
userRepo := repositories.NewUserRepository(postgres.Pool)
|
||||||
oauthRepo := repositories.NewOAuthRepository(pg.Pool)
|
oauthRepo := repositories.NewOAuthRepository(postgres.Pool)
|
||||||
|
|
||||||
ctx := context.Background()
|
if err := seedClient(context.Background(), oauthRepo, cfg.Client); err != nil {
|
||||||
|
log.Fatalf("seed client: %v", err)
|
||||||
basicClient, err := ensureBasicClient(ctx, cfg, oauthRepo)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
svc := services.New(userRepo, oauthRepo, rdb.Client, services.TokenConfig{
|
svc := services.New(
|
||||||
|
userRepo,
|
||||||
|
oauthRepo,
|
||||||
|
redis.Client,
|
||||||
|
services.TokenConfig{
|
||||||
AccessTTL: cfg.JWT.TTL,
|
AccessTTL: cfg.JWT.TTL,
|
||||||
RefreshTTL: cfg.JWT.TTL * 7,
|
RefreshTTL: cfg.JWT.TTL * 7,
|
||||||
}, basicClient)
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
limiter := services.NewRateLimiter(redis.Client)
|
||||||
|
|
||||||
authHandler := handlers.NewAuthHandler(svc)
|
authHandler := handlers.NewAuthHandler(svc)
|
||||||
oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL)
|
oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL)
|
||||||
consentHandler := handlers.NewConsentHandler(svc)
|
consentHandler := handlers.NewConsentHandler(svc)
|
||||||
|
|
||||||
r := apphttp.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo)
|
router := http.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo, limiter)
|
||||||
log.Fatal(r.Run(cfg.Server.Addr))
|
|
||||||
|
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) {
|
func seedClient(ctx context.Context, repo *repositories.OAuthRepository, cfg config.Client) error {
|
||||||
client, err := repo.GetOAuthClientByClientID(ctx, cfg.Client.ID)
|
hashedSecret, err := services.HashClientSecret(cfg.Secret)
|
||||||
if err == nil {
|
|
||||||
return client, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
hashedSecret, err := services.HashClientSecret(cfg.Client.Secret)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return repo.CreateOAuthClient(ctx, models.OAuthClient{
|
redirectURIsJSON, _ := json.Marshal(cfg.RedirectURIs)
|
||||||
ClientID: cfg.Client.ID,
|
grantTypesJSON, _ := json.Marshal(cfg.GrantTypes)
|
||||||
|
scopesJSON, _ := json.Marshal(cfg.Scopes)
|
||||||
|
|
||||||
|
return repo.UpsertClient(ctx, models.OAuthClient{
|
||||||
|
ClientID: cfg.ID,
|
||||||
ClientSecret: hashedSecret,
|
ClientSecret: hashedSecret,
|
||||||
Name: cfg.Client.Name,
|
Name: cfg.Name,
|
||||||
RedirectURIs: json.RawMessage(cfg.Client.RedirectURIsJSON()),
|
RedirectURIs: redirectURIsJSON,
|
||||||
GrantTypes: json.RawMessage(cfg.Client.GrantTypesJSON()),
|
GrantTypes: grantTypesJSON,
|
||||||
Scopes: json.RawMessage(cfg.Client.ScopesJSON()),
|
Scopes: scopesJSON,
|
||||||
Trusted: true,
|
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
|
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 {
|
if err != nil {
|
||||||
c.Error(models.ErrUnauthorized)
|
c.Error(models.ErrUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !client.Trusted {
|
||||||
if !service.Trusted {
|
|
||||||
c.Error(models.ErrForbidden)
|
c.Error(models.ErrForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -59,12 +61,23 @@ func (h *AuthHandler) Refresh(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
pair, err := h.svc.RefreshTokens(c.Request.Context(), input.RefreshToken)
|
id, secret, ok := c.Request.BasicAuth()
|
||||||
if err != nil {
|
if !ok {
|
||||||
c.Error(err)
|
c.Error(models.ErrUnauthorized)
|
||||||
return
|
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)
|
c.JSON(http.StatusOK, pair)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/dusiburg/kotosoft-id/internal/handlers"
|
"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/models"
|
||||||
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
||||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||||
@@ -11,7 +12,7 @@ import (
|
|||||||
"github.com/google/uuid"
|
"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 := gin.Default()
|
||||||
r.Use(errorMiddleware())
|
r.Use(errorMiddleware())
|
||||||
|
|
||||||
@@ -19,7 +20,7 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
|||||||
{
|
{
|
||||||
o.GET("/authorize", oauth.Authorize)
|
o.GET("/authorize", oauth.Authorize)
|
||||||
o.GET("/session/:token", oauth.GetSession)
|
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/attach", oauth.SessionAttach)
|
||||||
o.POST("/session/approve", oauth.SessionApprove)
|
o.POST("/session/approve", oauth.SessionApprove)
|
||||||
o.POST("/token", oauth.Token)
|
o.POST("/token", oauth.Token)
|
||||||
@@ -29,7 +30,7 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
|||||||
api := r.Group("/api/v1")
|
api := r.Group("/api/v1")
|
||||||
{
|
{
|
||||||
a := api.Group("/auth")
|
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)
|
a.POST("/refresh", auth.Refresh)
|
||||||
|
|
||||||
me := api.Group("/me")
|
me := api.Group("/me")
|
||||||
@@ -65,7 +66,7 @@ func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, r
|
|||||||
return
|
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.Error(models.ErrForbidden)
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
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) {
|
func bearerToken(c *gin.Context) (string, bool) {
|
||||||
return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
|
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"}
|
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"}
|
ErrNotFound = &APIError{Code: 404, Slug: "not_found", Message: "Resource not found"}
|
||||||
ErrAlreadyExists = &APIError{Code: 409, Slug: "already_exists", Message: "Resource already exists"}
|
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"}
|
ErrInternal = &APIError{Code: 500, Slug: "internal", Message: "Internal server error"}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ func (r *OAuthRepository) CreateOAuthClient(ctx context.Context, client models.O
|
|||||||
RETURNING id, is_active, created_at, updated_at
|
RETURNING id, is_active, created_at, updated_at
|
||||||
`, client.ClientID, client.ClientSecret, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted).
|
`, client.ClientID, client.ClientSecret, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted).
|
||||||
Scan(&client.ID, &client.IsActive, &client.CreatedAt, &client.UpdatedAt)
|
Scan(&client.ID, &client.IsActive, &client.CreatedAt, &client.UpdatedAt)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to create OAuth client: %w", err)
|
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, `
|
err := r.db.QueryRow(ctx, `
|
||||||
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
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
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -49,7 +52,11 @@ func (r *OAuthRepository) GetOAuthClientByID(ctx context.Context, id uuid.UUID)
|
|||||||
err := r.db.QueryRow(ctx, `
|
err := r.db.QueryRow(ctx, `
|
||||||
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
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
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
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)
|
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)
|
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
|
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).
|
`, row.CodeHash, row.UserID, row.ClientID, row.RedirectURI, row.Scopes,
|
||||||
Scan(&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI, &row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod, &row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt)
|
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 {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("create authorization code: %w", err)
|
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, `
|
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
|
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
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -107,7 +121,10 @@ func (r *OAuthRepository) GetRefreshTokenByHash(ctx context.Context, tokenHash s
|
|||||||
err := r.db.QueryRow(ctx, `
|
err := r.db.QueryRow(ctx, `
|
||||||
SELECT id, token_hash, user_id, client_id, scopes, expires_at, created_at
|
SELECT id, token_hash, user_id, client_id, scopes, expires_at, created_at
|
||||||
FROM refresh_tokens WHERE token_hash = $1
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -119,32 +136,27 @@ func (r *OAuthRepository) DeleteRefreshTokenByID(ctx context.Context, id uuid.UU
|
|||||||
return err
|
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(
|
func (r *OAuthRepository) RecordUserConsent(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
userID, clientID uuid.UUID,
|
userID, clientID uuid.UUID,
|
||||||
scopes []string,
|
scopes []string,
|
||||||
) error {
|
) error {
|
||||||
|
|
||||||
scopeJSON, err := json.Marshal(scopes)
|
scopeJSON, err := json.Marshal(scopes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = r.db.Exec(ctx, `
|
_, err = r.db.Exec(ctx, `
|
||||||
INSERT INTO user_consents (
|
INSERT INTO user_consents (user_id, client_id, scopes, authorized_at, last_used_at, revoked_at)
|
||||||
user_id,
|
|
||||||
client_id,
|
|
||||||
scopes,
|
|
||||||
authorized_at,
|
|
||||||
last_used_at,
|
|
||||||
revoked_at
|
|
||||||
)
|
|
||||||
VALUES ($1, $2, $3, now(), now(), NULL)
|
VALUES ($1, $2, $3, now(), now(), NULL)
|
||||||
ON CONFLICT (user_id, client_id)
|
ON CONFLICT (user_id, client_id)
|
||||||
WHERE revoked_at IS NULL
|
WHERE revoked_at IS NULL
|
||||||
DO UPDATE SET
|
DO UPDATE SET scopes = EXCLUDED.scopes, last_used_at = now()
|
||||||
scopes = EXCLUDED.scopes,
|
|
||||||
last_used_at = now()
|
|
||||||
`, userID, clientID, scopeJSON)
|
`, userID, clientID, scopeJSON)
|
||||||
|
|
||||||
return err
|
return err
|
||||||
@@ -154,7 +166,6 @@ func (r *OAuthRepository) GetUserConsents(
|
|||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
userID uuid.UUID,
|
userID uuid.UUID,
|
||||||
) ([]models.UserConsent, error) {
|
) ([]models.UserConsent, error) {
|
||||||
|
|
||||||
rows, err := r.db.Query(ctx, `
|
rows, err := r.db.Query(ctx, `
|
||||||
SELECT
|
SELECT
|
||||||
uc.id,
|
uc.id,
|
||||||
@@ -173,52 +184,18 @@ func (r *OAuthRepository) GetUserConsents(
|
|||||||
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
||||||
ORDER BY uc.authorized_at DESC
|
ORDER BY uc.authorized_at DESC
|
||||||
`, userID)
|
`, userID)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
var consents []models.UserConsent
|
return scanConsents(rows)
|
||||||
|
|
||||||
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(
|
func (r *OAuthRepository) UpdateConsentLastUsed(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
userID, clientID uuid.UUID,
|
userID, clientID uuid.UUID,
|
||||||
) error {
|
) error {
|
||||||
|
|
||||||
_, err := r.db.Exec(ctx, `
|
_, err := r.db.Exec(ctx, `
|
||||||
UPDATE user_consents
|
UPDATE user_consents
|
||||||
SET last_used_at = now()
|
SET last_used_at = now()
|
||||||
@@ -227,20 +204,14 @@ func (r *OAuthRepository) UpdateConsentLastUsed(
|
|||||||
AND revoked_at IS NULL
|
AND revoked_at IS NULL
|
||||||
AND (expires_at IS NULL OR expires_at > now())
|
AND (expires_at IS NULL OR expires_at > now())
|
||||||
`, userID, clientID)
|
`, userID, clientID)
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *OAuthRepository) GetUserConsentsByClientID(
|
func (r *OAuthRepository) GetUserConsentsByClientID(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
userID uuid.UUID,
|
userID uuid.UUID,
|
||||||
clientID uuid.UUID,
|
clientID uuid.UUID,
|
||||||
) ([]models.UserConsent, error) {
|
) ([]models.UserConsent, error) {
|
||||||
|
|
||||||
rows, err := r.db.Query(ctx, `
|
rows, err := r.db.Query(ctx, `
|
||||||
SELECT
|
SELECT
|
||||||
uc.id,
|
uc.id,
|
||||||
@@ -250,39 +221,87 @@ func (r *OAuthRepository) GetUserConsentsByClientID(
|
|||||||
oc.name AS client_name,
|
oc.name AS client_name,
|
||||||
uc.scopes,
|
uc.scopes,
|
||||||
uc.authorized_at,
|
uc.authorized_at,
|
||||||
|
uc.last_used_at,
|
||||||
uc.revoked_at
|
uc.revoked_at
|
||||||
FROM user_consents uc
|
FROM user_consents uc
|
||||||
JOIN oauth_clients oc ON uc.client_id = oc.id
|
JOIN oauth_clients oc ON uc.client_id = oc.id
|
||||||
WHERE uc.user_id = $1
|
WHERE uc.user_id = $1
|
||||||
|
AND uc.client_id = $2
|
||||||
AND uc.revoked_at IS NULL
|
AND uc.revoked_at IS NULL
|
||||||
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
||||||
AND uo.id = $2
|
|
||||||
ORDER BY uc.authorized_at DESC
|
ORDER BY uc.authorized_at DESC
|
||||||
`, userID, clientID)
|
`, userID, clientID)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
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
|
var consents []models.UserConsent
|
||||||
|
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var c models.UserConsent
|
var c models.UserConsent
|
||||||
var scopeJSON []byte
|
var scopeJSON []byte
|
||||||
|
|
||||||
err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&c.ID,
|
&c.ID, &c.UserID, &c.ClientID,
|
||||||
&c.UserID,
|
&c.ClientIdentifier, &c.ClientName,
|
||||||
&c.ClientID,
|
|
||||||
&c.ClientIdentifier,
|
|
||||||
&c.ClientName,
|
|
||||||
&scopeJSON,
|
&scopeJSON,
|
||||||
&c.AuthorizedAt,
|
&c.AuthorizedAt, &c.LastUsedAt, &c.RevokedAt,
|
||||||
&c.LastUsedAt,
|
); err != nil {
|
||||||
&c.RevokedAt,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,41 +318,3 @@ func (r *OAuthRepository) GetUserConsentsByClientID(
|
|||||||
|
|
||||||
return consents, nil
|
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) {
|
func (s *Service) ValidateAccessToken(ctx context.Context, token string) (*TokenInfo, error) {
|
||||||
token = strings.TrimSpace(token)
|
token = strings.TrimSpace(token)
|
||||||
if token == "" {
|
if token == "" {
|
||||||
@@ -105,15 +73,19 @@ func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input mod
|
|||||||
if input.FirstName != "" {
|
if input.FirstName != "" {
|
||||||
user.FirstName = input.FirstName
|
user.FirstName = input.FirstName
|
||||||
}
|
}
|
||||||
|
|
||||||
if input.SecondName != "" {
|
if input.SecondName != "" {
|
||||||
user.SecondName = input.SecondName
|
user.SecondName = input.SecondName
|
||||||
}
|
}
|
||||||
|
|
||||||
if input.BirthDate != nil {
|
if input.BirthDate != nil {
|
||||||
user.BirthDate = input.BirthDate
|
user.BirthDate = input.BirthDate
|
||||||
}
|
}
|
||||||
|
|
||||||
if input.Sex != "" {
|
if input.Sex != "" {
|
||||||
user.Sex = input.Sex
|
user.Sex = input.Sex
|
||||||
}
|
}
|
||||||
|
|
||||||
if input.Password != "" {
|
if input.Password != "" {
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -121,15 +93,22 @@ func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input mod
|
|||||||
}
|
}
|
||||||
user.PasswordHash = string(hash)
|
user.PasswordHash = string(hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
user.UpdatedAt = time.Now()
|
user.UpdatedAt = time.Now()
|
||||||
|
|
||||||
return s.users.UpdateUser(ctx, *user)
|
return s.users.UpdateUser(ctx, *user)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) DeleteProfile(ctx context.Context, userID uuid.UUID, accessToken string) error {
|
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 {
|
if err := s.users.DeleteUser(ctx, userID); err != nil {
|
||||||
return models.ErrInternal
|
return models.ErrInternal
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = s.redis.Del(ctx, accessTokenPrefix+accessToken)
|
_ = s.redis.Del(ctx, accessTokenPrefix+accessToken)
|
||||||
|
|
||||||
return nil
|
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) {
|
func (s *Service) SessionLogin(ctx context.Context, token, email, password string) (string, error) {
|
||||||
sess, err := s.GetOAuthSession(ctx, token)
|
sess, err := s.GetOAuthSession(ctx, token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", ErrInvalidGrant
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := s.users.GetUserByEmail(ctx, email)
|
user, err := s.users.GetUserByEmail(ctx, email)
|
||||||
if err != nil || bcryptCompare(user.PasswordHash, password) != nil {
|
if err != nil || bcryptCompare(user.PasswordHash, password) != nil {
|
||||||
return "", models.ErrUnauthorized
|
return "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
|
|
||||||
sess.UserID = user.ID
|
sess.UserID = user.ID
|
||||||
@@ -114,12 +114,7 @@ func (s *Service) SessionLogin(ctx context.Context, token, email, password strin
|
|||||||
return "", ErrInvalidClient
|
return "", ErrInvalidClient
|
||||||
}
|
}
|
||||||
|
|
||||||
if client.Trusted {
|
if client.Trusted || s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) {
|
||||||
return s.SessionApprove(ctx, token)
|
|
||||||
}
|
|
||||||
|
|
||||||
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
|
||||||
if hasUserConsents {
|
|
||||||
return s.SessionApprove(ctx, token)
|
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) {
|
func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken string) (string, error) {
|
||||||
info, err := s.ValidateAccessToken(ctx, accessToken)
|
info, err := s.ValidateAccessToken(ctx, accessToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", models.ErrUnauthorized
|
return "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
|
|
||||||
sess, err := s.GetOAuthSession(ctx, sessionToken)
|
sess, err := s.GetOAuthSession(ctx, sessionToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", ErrInvalidGrant
|
||||||
}
|
}
|
||||||
|
|
||||||
sess.UserID = info.UserID
|
sess.UserID = info.UserID
|
||||||
@@ -146,12 +141,8 @@ func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken s
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", ErrInvalidClient
|
return "", ErrInvalidClient
|
||||||
}
|
}
|
||||||
if client.Trusted {
|
|
||||||
return s.SessionApprove(ctx, sessionToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
if client.Trusted || s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) {
|
||||||
if hasUserConsents {
|
|
||||||
return s.SessionApprove(ctx, sessionToken)
|
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) {
|
func (s *Service) SessionApprove(ctx context.Context, token string) (string, error) {
|
||||||
sess, err := s.GetOAuthSession(ctx, token)
|
sess, err := s.GetOAuthSession(ctx, token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", ErrInvalidGrant
|
||||||
}
|
}
|
||||||
if sess.UserID == uuid.Nil {
|
if sess.UserID == uuid.Nil {
|
||||||
return "", ErrInvalidGrant
|
return "", ErrInvalidGrant
|
||||||
@@ -178,7 +169,7 @@ func (s *Service) SessionApprove(ctx context.Context, token string) (string, err
|
|||||||
}
|
}
|
||||||
|
|
||||||
_ = s.redis.Del(ctx, oauthSessionPrefix+token)
|
_ = 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)
|
redirectURL, _ := url.Parse(sess.RedirectURI)
|
||||||
q := redirectURL.Query()
|
q := redirectURL.Query()
|
||||||
@@ -221,7 +212,7 @@ func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redir
|
|||||||
return nil, models.ErrInternal
|
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))
|
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
|
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 {
|
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
|
||||||
return nil, models.ErrInternal
|
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)
|
user, err := s.users.GetUserByID(ctx, row.UserID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, models.ErrInternal
|
return nil, models.ErrInternal
|
||||||
}
|
}
|
||||||
|
|
||||||
scopes := scopesFromJSON(row.Scopes)
|
|
||||||
if !ScopesAllowed(client.Scopes, scopes) {
|
|
||||||
return nil, ErrInvalidGrant
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.issuePair(ctx, user, client.ID, scopes)
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) createAuthCode(
|
func (s *Service) createAuthCode(ctx context.Context, userID, clientID uuid.UUID, redirectURI string, scopes []string, codeChallenge string) (string, error) {
|
||||||
ctx context.Context,
|
|
||||||
userID, clientID uuid.UUID,
|
|
||||||
redirectURI string,
|
|
||||||
scopes []string,
|
|
||||||
codeChallenge string,
|
|
||||||
) (string, error) {
|
|
||||||
rawCode, err := newOpaqueToken(32)
|
rawCode, err := newOpaqueToken(32)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", models.ErrInternal
|
return "", models.ErrInternal
|
||||||
@@ -330,6 +315,7 @@ func (s *Service) issuePair(ctx context.Context, user *models.User, clientID uui
|
|||||||
Scopes: scopes,
|
Scopes: scopes,
|
||||||
ClientID: clientID,
|
ClientID: clientID,
|
||||||
}
|
}
|
||||||
|
|
||||||
data, _ := json.Marshal(accessData)
|
data, _ := json.Marshal(accessData)
|
||||||
if err := s.redis.Set(ctx, accessTokenPrefix+accessToken, data, s.tokens.AccessTTL).Err(); err != nil {
|
if err := s.redis.Set(ctx, accessTokenPrefix+accessToken, data, s.tokens.AccessTTL).Err(); err != nil {
|
||||||
return nil, models.ErrInternal
|
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)
|
CreateRefreshToken(ctx context.Context, row models.RefreshTokenRow) (*models.RefreshTokenRow, error)
|
||||||
GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error)
|
GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error)
|
||||||
DeleteRefreshTokenByID(ctx context.Context, id uuid.UUID) 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
|
RecordUserConsent(ctx context.Context, userID, clientID uuid.UUID, scopes []string) error
|
||||||
GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error)
|
GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error)
|
||||||
UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error
|
UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error
|
||||||
@@ -59,7 +60,6 @@ type Service struct {
|
|||||||
oauth OAuthRepo
|
oauth OAuthRepo
|
||||||
redis *redis.Client
|
redis *redis.Client
|
||||||
tokens TokenConfig
|
tokens TokenConfig
|
||||||
basicClient *models.OAuthClient
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(
|
func New(
|
||||||
@@ -67,14 +67,12 @@ func New(
|
|||||||
oauth OAuthRepo,
|
oauth OAuthRepo,
|
||||||
rdb *redis.Client,
|
rdb *redis.Client,
|
||||||
tokenCfg TokenConfig,
|
tokenCfg TokenConfig,
|
||||||
basicClient *models.OAuthClient,
|
|
||||||
) *Service {
|
) *Service {
|
||||||
return &Service{
|
return &Service{
|
||||||
users: users,
|
users: users,
|
||||||
oauth: oauth,
|
oauth: oauth,
|
||||||
redis: rdb,
|
redis: rdb,
|
||||||
tokens: tokenCfg,
|
tokens: tokenCfg,
|
||||||
basicClient: basicClient,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export async function clearTokens() {
|
|||||||
store.delete("refresh_token");
|
store.delete("refresh_token");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function tryRefresh(): Promise<boolean> {
|
export async function tryRefresh(): Promise<boolean> {
|
||||||
if (refreshPromise) return refreshPromise;
|
if (refreshPromise) return refreshPromise;
|
||||||
|
|
||||||
refreshPromise = (async () => {
|
refreshPromise = (async () => {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { Consent } from "@/types"
|
import { Consent } from "@/types"
|
||||||
import { cookies } from "next/headers"
|
import { cookies } from "next/headers"
|
||||||
|
import { clearTokens, tryRefresh } from "./auth"
|
||||||
|
|
||||||
export async function getConsents() {
|
export async function getConsents() {
|
||||||
const store = await cookies()
|
const store = await cookies()
|
||||||
@@ -16,14 +17,23 @@ export async function getConsents() {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
const refreshed = await tryRefresh();
|
||||||
|
if (!refreshed) {
|
||||||
|
await clearTokens();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return getConsents();
|
||||||
|
}
|
||||||
|
|
||||||
if (!response.ok) return []
|
if (!response.ok) return []
|
||||||
|
|
||||||
var consents = await response.json() as Consent[];
|
var consents = await response.json() as Consent[];
|
||||||
consents.forEach((consent: Consent) => {
|
consents.forEach((consent: Consent) => {
|
||||||
if (consent.client_id == process.env.CLIENT_ID) {
|
if (consent.client_id == process.env.CLIENT_ID) {
|
||||||
consent.isRevokable == false
|
consent.isRevokable = false
|
||||||
} else {
|
} else {
|
||||||
consent.isRevokable == true
|
consent.isRevokable = true
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -35,7 +45,7 @@ export async function revokeConsent(clientId: string) {
|
|||||||
const accessToken = store.get("access_token")?.value
|
const accessToken = store.get("access_token")?.value
|
||||||
|
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/applications/${clientId}`,
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/consents/${clientId}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import Applications from "./items/applications";
|
|||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
userData: User | null;
|
userData: User | null;
|
||||||
consentsData: Consent[] | [];
|
consentsData: Consent[] | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function MeClient({ userData, consentsData }: Props) {
|
export default function MeClient({ userData, consentsData }: Props) {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { enUS } from "date-fns/locale";
|
|||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
consents: Consent[] | [];
|
consents: Consent[] | null;
|
||||||
setConsents: (consents: Consent[]) => void;
|
setConsents: (consents: Consent[]) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ export default function Applications({ consents, setConsents }: Props) {
|
|||||||
<h1 className="text-xl">{t("title")}</h1>
|
<h1 className="text-xl">{t("title")}</h1>
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{consents.map((consent) => (
|
{consents?.map((consent) => (
|
||||||
<Item key={consent.client_id}>
|
<Item key={consent.client_id}>
|
||||||
<ItemContent>
|
<ItemContent>
|
||||||
<ItemTitle>{consent.client_name}</ItemTitle>
|
<ItemTitle>{consent.client_name}</ItemTitle>
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { getSession } from "@/actions/oauth";
|
import { getSession } from "@/actions/oauth";
|
||||||
import { isRedirectError } from "next/dist/client/components/redirect-error";
|
import { isRedirectError } from "next/dist/client/components/redirect-error";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export default async function OAuthPage({
|
export default async function OAuthPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
@@ -14,10 +17,28 @@ export default async function OAuthPage({
|
|||||||
const data = await getSession(session);
|
const data = await getSession(session);
|
||||||
if (!data) redirect("/oauth/error");
|
if (!data) redirect("/oauth/error");
|
||||||
|
|
||||||
const isAuthenticated =
|
const store = await cookies();
|
||||||
data.user_id && data.user_id !== "00000000-0000-0000-0000-000000000000";
|
const accessToken = store.get("access_token")?.value;
|
||||||
|
|
||||||
redirect(isAuthenticated ? `/consent?session=${session}` : `/login?session=${session}`);
|
if (accessToken) {
|
||||||
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/attach`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${accessToken}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ session }),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const body = await res.json();
|
||||||
|
if (body.redirect_url) redirect(body.redirect_url);
|
||||||
|
redirect(`/consent?session=${session}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
redirect(`/login?session=${session}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (isRedirectError(error)) throw error;
|
if (isRedirectError(error)) throw error;
|
||||||
console.error("OAuth page error:", error);
|
console.error("OAuth page error:", error);
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
FROM node:20 AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json* ./
|
||||||
|
RUN npm install --include=dev
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM node:20 AS production
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json* ./
|
||||||
|
COPY --from=builder /app/node_modules ./node_modules
|
||||||
|
COPY --from=builder /app/.next ./.next
|
||||||
|
COPY --from=builder /app/public ./public
|
||||||
|
COPY --from=builder /app/messages ./messages
|
||||||
|
RUN npm prune --omit=dev
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["npm", "start", "--", "-p", "80", "-H", "0.0.0.0"]
|
||||||
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||||
|
CMD wget -q --spider http://localhost:80/ || exit 1
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
import createNextIntlPlugin from "next-intl/plugin";
|
import createNextIntlPlugin from "next-intl/plugin";
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {};
|
||||||
/* config options here */
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const withNextIntl = createNextIntlPlugin();
|
const withNextIntl = createNextIntlPlugin();
|
||||||
export default withNextIntl(nextConfig);
|
export default withNextIntl(nextConfig);
|
||||||
|
|||||||
Reference in New Issue
Block a user