Compare commits

...
10 Commits
Author SHA1 Message Date
Ivan Rezchikov e9655740d5 migrate from drone to gitea actions
Build and Deploy / test-backend (push) Successful in 8m4s
Build and Deploy / lint-frontend (push) Successful in 1m34s
Build and Deploy / build-backend (push) Successful in 1m2s
Build and Deploy / build-frontend (push) Successful in 2m45s
Build and Deploy / deploy (push) Successful in 5s
2026-09-15 16:52:16 +03:00
Ivan Rezchikov 057ee6e0d7 migrate from drone to gitea actions 2026-09-15 16:51:44 +03:00
Ivan Rezchikov 0f9cacf619 ci/cd: gitea deploy 2026-09-15 16:50:21 +03:00
Ivan Rezchikov 62859e8537 ci/cd: gitea deploy 2026-09-15 16:47:42 +03:00
Ivan Rezchikov 8b0a3d143b v2: fixed oauth errors, oauth clients native control added 2026-09-15 16:21:53 +03:00
Ivan Rezchikov 83e1849d73 rem: register ratelimiter 2026-07-22 13:29:20 +03:00
Ivan Rezchikov bd5c47b832 fixes 2026-07-17 13:19:09 +03:00
Ivan Rezchikov 1b2629b5eb docker fixes 2026-07-17 13:13:42 +03:00
Ivan Rezchikov 6cdd095b4a feat: favicon added 2026-07-13 18:51:27 +03:00
Ivan Rezchikov b3276dc927 fix: header z-index 2026-07-13 18:41:37 +03:00
59 changed files with 1553 additions and 3242 deletions
+4 -4
View File
@@ -26,10 +26,10 @@ steps:
path: /opt/app path: /opt/app
commands: commands:
- docker build - docker build
-t localhost:5000/kotosoft_id_backend:latest -t 172.17.0.1:5000/kotosoft_id_backend:latest
-f kotosoft-id-backend/Dockerfile -f kotosoft-id-backend/Dockerfile
kotosoft-id-backend kotosoft-id-backend
- docker push localhost:5000/kotosoft_id_backend:latest - docker push 172.17.0.1:5000/kotosoft_id_backend:latest
- name: build and push frontend - name: build and push frontend
image: docker:24 image: docker:24
@@ -38,10 +38,10 @@ steps:
path: /var/run/docker.sock path: /var/run/docker.sock
commands: commands:
- docker build - docker build
-t localhost:5000/kotosoft_id_frontend:latest -t 172.17.0.1:5000/kotosoft_id_frontend:latest
-f kotosoft-id-frontend/Dockerfile -f kotosoft-id-frontend/Dockerfile
kotosoft-id-frontend kotosoft-id-frontend
- docker push localhost:5000/kotosoft_id_frontend:latest - docker push 172.17.0.1:5000/kotosoft_id_frontend:latest
- name: deploy - name: deploy
image: docker:24 image: docker:24
+110
View File
@@ -0,0 +1,110 @@
name: Build and Deploy
on:
push:
branches:
- main
jobs:
test-backend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Test backend
run: |
docker run --rm \
-v "$PWD/kotosoft-id-backend:/app" \
-w /app \
golang:1.25-alpine3.21 \
sh -c 'go mod tidy && go test ./...'
lint-frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Lint frontend
run: |
docker run --rm \
-v "$PWD/kotosoft-id-frontend:/app" \
-w /app \
node:20-alpine \
sh -c 'npm install && npm run lint'
build-backend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build backend
run: |
docker build \
-t 172.17.0.1:5000/kotosoft_id_backend:latest \
-f kotosoft-id-backend/Dockerfile \
kotosoft-id-backend
- name: Push backend
run: |
docker push 172.17.0.1:5000/kotosoft_id_backend:latest
build-frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build frontend
run: |
docker build \
-t 172.17.0.1:5000/kotosoft_id_frontend:latest \
-f kotosoft-id-frontend/Dockerfile \
kotosoft-id-frontend
- name: Push frontend
run: |
docker push 172.17.0.1:5000/kotosoft_id_frontend:latest
deploy:
runs-on: ubuntu-latest
needs:
- test-backend
- lint-frontend
- build-backend
- build-frontend
env:
FRONTEND_URL: ${{ secrets.FRONTEND_URL }}
BACKEND_URL: ${{ secrets.BACKEND_URL }}
POSTGRES_URL: ${{ secrets.POSTGRES_URL }}
REDIS_URL: ${{ secrets.REDIS_URL }}
JWT_SECRET: ${{ secrets.JWT_SECRET }}
CLIENT_ID: ${{ secrets.CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
CLIENT_NAME: ${{ secrets.CLIENT_NAME }}
CLIENT_REDIRECT_URIS: ${{ secrets.CLIENT_REDIRECT_URIS }}
DOMAIN: ${{ secrets.DOMAIN }}
API_DOMAIN: ${{ secrets.API_DOMAIN }}
LETSENCRYPT_EMAIL: ${{ secrets.LETSENCRYPT_EMAIL }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Deploy
run: |
mkdir -p /opt/app
cp docker-compose.yml /opt/app/docker-compose.yml
cd /opt/app
docker compose -p kotosoft pull
docker compose -p kotosoft up -d --remove-orphans
+4 -4
View File
@@ -1,6 +1,6 @@
services: services:
kotosoft_id_backend: kotosoft_id_backend:
image: localhost:5000/kotosoft_id_backend:latest image: 172.17.0.1:5000/kotosoft_id_backend:latest
restart: unless-stopped restart: unless-stopped
environment: environment:
SERVER_ADDR: ":8080" SERVER_ADDR: ":8080"
@@ -8,8 +8,8 @@ services:
POSTGRES_URL: ${POSTGRES_URL} POSTGRES_URL: ${POSTGRES_URL}
POSTGRES_MIGRATION_FILE_PATH: ./migrations/migrations.sql POSTGRES_MIGRATION_FILE_PATH: ./migrations/migrations.sql
REDIS_URL: ${REDIS_URL} REDIS_URL: ${REDIS_URL}
JWT_SECRET: ${JWT_SECRET} ACCESS_TOKEN_TTL: ${ACCESS_TOKEN_TTL:-24h}
JWT_EXPIRATION_HOURS: ${JWT_EXPIRATION_HOURS:-24h} REFRESH_TOKEN_TTL: ${REFRESH_TOKEN_TTL:-168h}
CLIENT_ID: ${CLIENT_ID} CLIENT_ID: ${CLIENT_ID}
CLIENT_SECRET: ${CLIENT_SECRET} CLIENT_SECRET: ${CLIENT_SECRET}
CLIENT_NAME: ${CLIENT_NAME} CLIENT_NAME: ${CLIENT_NAME}
@@ -26,7 +26,7 @@ services:
- eu_net - eu_net
kotosoft_id_frontend: kotosoft_id_frontend:
image: localhost:5000/kotosoft_id_frontend:latest image: 172.17.0.1:5000/kotosoft_id_frontend:latest
restart: unless-stopped restart: unless-stopped
environment: environment:
PUBLIC_URL: ${FRONTEND_URL} PUBLIC_URL: ${FRONTEND_URL}
+4 -9
View File
@@ -35,8 +35,6 @@ func main() {
userRepo := repositories.NewUserRepository(postgres.Pool) userRepo := repositories.NewUserRepository(postgres.Pool)
oauthRepo := repositories.NewOAuthRepository(postgres.Pool) oauthRepo := repositories.NewOAuthRepository(postgres.Pool)
positionRepo := repositories.NewPositionRepository(postgres.Pool)
citizenshipRepo := repositories.NewCitizenshipRepository(postgres.Pool)
if err := seedClient(context.Background(), oauthRepo, cfg.Client); err != nil { if err := seedClient(context.Background(), oauthRepo, cfg.Client); err != nil {
log.Fatalf("seed client: %v", err) log.Fatalf("seed client: %v", err)
@@ -45,11 +43,10 @@ func main() {
svc := services.New( svc := services.New(
userRepo, userRepo,
oauthRepo, oauthRepo,
positionRepo,
redis.Client, redis.Client,
services.TokenConfig{ services.TokenConfig{
AccessTTL: cfg.JWT.TTL, AccessTTL: cfg.Tokens.AccessTTL,
RefreshTTL: cfg.JWT.TTL * 7, RefreshTTL: cfg.Tokens.RefreshTTL,
}, },
) )
@@ -58,11 +55,9 @@ func main() {
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)
positionsHandler := handlers.NewPositionsHandler(svc) clientHandler := handlers.NewClientHandler(svc)
citizenshipSvc := services.NewCitizenshipService(citizenshipRepo)
citizenshipHandler := handlers.NewCitizenshipHandler(citizenshipSvc)
router := http.NewRouter(authHandler, oauthHandler, consentHandler, positionsHandler, citizenshipHandler, svc, oauthRepo, limiter) router := http.NewRouter(authHandler, oauthHandler, consentHandler, clientHandler, svc, oauthRepo, limiter)
log.Printf("starting server on %s", cfg.Server.Addr) log.Printf("starting server on %s", cfg.Server.Addr)
if err := router.Run(cfg.Server.Addr); err != nil { if err := router.Run(cfg.Server.Addr); err != nil {
+1 -2
View File
@@ -8,6 +8,7 @@ require (
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.8.0 github.com/jackc/pgx/v5 v5.8.0
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/redis/go-redis/v9 v9.18.0
golang.org/x/crypto v0.48.0 golang.org/x/crypto v0.48.0
) )
@@ -24,7 +25,6 @@ require (
github.com/go-playground/validator/v10 v10.27.0 // indirect github.com/go-playground/validator/v10 v10.27.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-json v0.10.2 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect github.com/goccy/go-yaml v1.18.0 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect
@@ -37,7 +37,6 @@ require (
github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.5.1 // indirect github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect github.com/quic-go/quic-go v0.54.0 // indirect
github.com/redis/go-redis/v9 v9.18.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect github.com/ugorji/go/codec v1.3.0 // indirect
go.uber.org/atomic v1.11.0 // indirect go.uber.org/atomic v1.11.0 // indirect
+6 -2
View File
@@ -1,3 +1,7 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
@@ -31,8 +35,6 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
@@ -84,6 +86,8 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU= go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
@@ -13,7 +13,7 @@ type Conf struct {
Postgres Postgres Postgres Postgres
Redis Redis Redis Redis
Client Client Client Client
JWT JWT Tokens Tokens
} }
type Server struct { type Server struct {
@@ -39,9 +39,12 @@ type Client struct {
Scopes []string `env:"CLIENT_SCOPES" envSeparator:"," envDefault:"profile:read,profile:edit,profile:consent:read,profile:consent:delete,auth:register"` Scopes []string `env:"CLIENT_SCOPES" envSeparator:"," envDefault:"profile:read,profile:edit,profile:consent:read,profile:consent:delete,auth:register"`
} }
type JWT struct { // Tokens holds the TTLs for opaque access/refresh tokens.
Secret string `env:"JWT_SECRET,required"` // NOTE: tokens issued by this service are opaque (random), not JWTs —
TTL time.Duration `env:"JWT_TTL" envDefault:"24h"` // this used to be a "JWT" config section with an unused JWT_SECRET var.
type Tokens struct {
AccessTTL time.Duration `env:"ACCESS_TOKEN_TTL" envDefault:"24h"`
RefreshTTL time.Duration `env:"REFRESH_TOKEN_TTL" envDefault:"168h"`
} }
func New() (*Conf, error) { func New() (*Conf, error) {
@@ -1,72 +0,0 @@
package handlers
import (
"net/http"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/dusiburg/kotosoft-id/internal/services"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type CitizenshipHandler struct {
s *services.CitizenshipService
}
func NewCitizenshipHandler(s *services.CitizenshipService) *CitizenshipHandler {
return &CitizenshipHandler{s: s}
}
func (h *CitizenshipHandler) GetCitizenshipApplicationByUserId(c *gin.Context) {
userID := mustUserID(c)
application, err := h.s.GetCitizenshipApplicationByUserId(c.Request.Context(), userID)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, application)
}
func (h *CitizenshipHandler) CreateCitizenshipApplication(c *gin.Context) {
userID := mustUserID(c)
var input models.CreateCitizenshipApplicationInput
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
application, err := h.s.CreateCitizenshipApplication(c.Request.Context(), userID, input.RegionID)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusCreated, application)
}
func (h *CitizenshipHandler) ReviewCitizenshipApplication(c *gin.Context) {
reviewerID := mustUserID(c)
applicationID, err := uuid.Parse(c.Param("id"))
if err != nil {
c.Error(models.ErrBadRequest)
return
}
var input models.ReviewCitizenshipApplicationInput
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
application, err := h.s.ReviewCitizenshipApplication(c.Request.Context(), applicationID, reviewerID, input)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, application)
}
@@ -0,0 +1,104 @@
package handlers
import (
"net/http"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/dusiburg/kotosoft-id/internal/services"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type ClientHandler struct {
svc *services.Service
}
func NewClientHandler(svc *services.Service) *ClientHandler {
return &ClientHandler{svc: svc}
}
func (h *ClientHandler) Create(c *gin.Context) {
var input models.ClientCreateInput
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
client, rawSecret, err := h.svc.CreateClient(c.Request.Context(), input)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusCreated, gin.H{
"id": client.ID,
"client_id": client.ClientID,
"client_secret": rawSecret,
"name": client.Name,
"redirect_uris": client.RedirectURIs,
"grant_types": client.GrantTypes,
"scopes": client.Scopes,
"trusted": client.Trusted,
"is_active": client.IsActive,
"created_at": client.CreatedAt,
})
}
func (h *ClientHandler) List(c *gin.Context) {
clients, err := h.svc.ListClients(c.Request.Context())
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, clients)
}
func (h *ClientHandler) Get(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
c.Error(models.ErrBadRequest)
return
}
client, err := h.svc.GetClient(c.Request.Context(), id)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, client)
}
func (h *ClientHandler) Update(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
c.Error(models.ErrBadRequest)
return
}
var input models.ClientUpdateInput
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
client, err := h.svc.UpdateClient(c.Request.Context(), id, input)
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, client)
}
func (h *ClientHandler) Deactivate(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.DeactivateClient(c.Request.Context(), id); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
@@ -58,11 +58,7 @@ func (h *OAuthHandler) SessionLogin(c *gin.Context) {
redirectURL, err := h.svc.SessionLogin(c.Request.Context(), input.Session, input.Email, input.Password) redirectURL, err := h.svc.SessionLogin(c.Request.Context(), input.Session, input.Email, input.Password)
if err != nil { if err != nil {
if err == services.ErrInvalidGrant { oauthErrorJSON(c, err)
oauthErrorJSON(c, services.ErrInvalidGrant)
} else {
oauthErrorJSON(c, services.ErrAccessDenied)
}
return return
} }
@@ -91,7 +87,7 @@ func (h *OAuthHandler) SessionAttach(c *gin.Context) {
redirectURL, err := h.svc.SessionAttach(c.Request.Context(), input.Session, accessToken) redirectURL, err := h.svc.SessionAttach(c.Request.Context(), input.Session, accessToken)
if err != nil { if err != nil {
oauthErrorJSON(c, services.ErrAccessDenied) oauthErrorJSON(c, err)
return return
} }
@@ -114,7 +110,12 @@ func (h *OAuthHandler) SessionApprove(c *gin.Context) {
} }
if !input.Allow { if !input.Allow {
oauthErrorJSON(c, services.ErrAccessDenied) redirectURL, err := h.svc.SessionDeny(c.Request.Context(), input.Session)
if err != nil {
oauthErrorJSON(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"redirect_url": redirectURL})
return return
} }
@@ -1,280 +0,0 @@
package handlers
import (
"net/http"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/dusiburg/kotosoft-id/internal/services"
)
type PositionsHandler struct {
svc *services.Service
}
func NewPositionsHandler(svc *services.Service) *PositionsHandler {
return &PositionsHandler{svc: svc}
}
func localeFromRequest(c *gin.Context) string {
if l := c.GetHeader("X-Locale"); l != "" {
return l
}
if l := c.GetHeader("Accept-Language"); l != "" {
return l
}
return "en"
}
func userIDFromContext(c *gin.Context) (uuid.UUID, bool) {
v, ok := c.Get("user_id")
if !ok {
return uuid.Nil, false
}
id, ok := v.(uuid.UUID)
return id, ok
}
func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
userID, ok := userIDFromContext(c)
if !ok {
c.Error(models.ErrUnauthorized)
return
}
positions, err := h.svc.GetUserPositions(c.Request.Context(), userID, localeFromRequest(c))
if err != nil {
c.Error(models.ErrInternal)
return
}
c.JSON(http.StatusOK, positions)
}
func (h *PositionsHandler) ListPositions(c *gin.Context) {
positions, err := h.svc.GetAllPositions(c.Request.Context(), localeFromRequest(c))
if err != nil {
c.Error(models.ErrInternal)
return
}
c.JSON(http.StatusOK, positions)
}
type upsertPositionRequest struct {
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
Description *string `json:"description"`
}
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
var req upsertPositionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.UpsertPositionForLocale(c.Request.Context(), req.Code, localeFromRequest(c), req.Name, req.Description); err != nil {
c.Error(models.ErrInternal)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) UpdatePosition(c *gin.Context) {
var req struct {
Name string `json:"name" binding:"required"`
Description *string `json:"description"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.UpsertPositionForLocale(c.Request.Context(), c.Param("code"), localeFromRequest(c), req.Name, req.Description); err != nil {
c.Error(models.ErrInternal)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) DeletePosition(c *gin.Context) {
if err := h.svc.DeletePosition(c.Request.Context(), c.Param("code")); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
type permissionCodeRequest struct {
PermissionCode string `json:"permission_code" binding:"required"`
}
func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) {
var req permissionCodeRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.AddPermissionToPosition(c.Request.Context(), c.Param("code"), req.PermissionCode); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) RemovePermissionFromPosition(c *gin.Context) {
if err := h.svc.RemovePermissionFromPosition(c.Request.Context(), c.Param("code"), c.Param("permissionCode")); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) ListPermissions(c *gin.Context) {
perms, err := h.svc.GetAllPermissionsForLocale(c.Request.Context(), localeFromRequest(c))
if err != nil {
c.Error(models.ErrInternal)
return
}
c.JSON(http.StatusOK, perms)
}
func (h *PositionsHandler) ListUsersWithPositions(c *gin.Context) {
users, err := h.svc.GetUsersWithPositions(c.Request.Context(), localeFromRequest(c))
if err != nil {
c.Error(models.ErrInternal)
return
}
c.JSON(http.StatusOK, users)
}
func (h *PositionsHandler) AssignPosition(c *gin.Context) {
adminID, ok := userIDFromContext(c)
if !ok {
c.Error(models.ErrUnauthorized)
return
}
targetUserID, err := uuid.Parse(c.Param("userId"))
if err != nil {
c.Error(models.ErrBadRequest)
return
}
var input models.AssignPositionInput
if err := c.ShouldBindJSON(&input); err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.AssignPosition(c.Request.Context(), adminID, targetUserID, input); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) RevokePosition(c *gin.Context) {
targetUserID, err := uuid.Parse(c.Param("userId"))
if err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.RevokePosition(c.Request.Context(), targetUserID, c.Param("code")); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) CreatePermission(c *gin.Context) {
var req struct {
Code string `json:"code" binding:"required"`
Description *string `json:"description"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.CreatePermission(c.Request.Context(), req.Code, localeFromRequest(c), req.Description); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) UpdatePermission(c *gin.Context) {
var req struct {
Description *string `json:"description"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(models.ErrBadRequest)
return
}
if err := h.svc.UpdatePermission(c.Request.Context(), c.Param("code"), localeFromRequest(c), req.Description); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) DeletePermission(c *gin.Context) {
if err := h.svc.DeletePermission(c.Request.Context(), c.Param("code")); err != nil {
c.Error(err)
return
}
c.Status(http.StatusNoContent)
}
func (h *PositionsHandler) Introspect(c *gin.Context) {
var req struct {
Token string `json:"token" form:"token" binding:"required"`
}
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing token"})
return
}
id, secret, ok := c.Request.BasicAuth()
if !ok {
c.Header("WWW-Authenticate", `Basic realm="oauth"`)
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid_client"})
return
}
if _, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{
ClientID: id,
ClientSecret: secret,
}); err != nil {
c.Header("WWW-Authenticate", `Basic realm="oauth"`)
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid_client"})
return
}
resp, err := h.svc.IntrospectToken(c.Request.Context(), req.Token)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "server_error"})
return
}
c.JSON(http.StatusOK, resp)
}
+9 -91
View File
@@ -16,8 +16,7 @@ func NewRouter(
auth *handlers.AuthHandler, auth *handlers.AuthHandler,
oauth *handlers.OAuthHandler, oauth *handlers.OAuthHandler,
consents *handlers.ConsentHandler, consents *handlers.ConsentHandler,
positions *handlers.PositionsHandler, clients *handlers.ClientHandler,
citizenship *handlers.CitizenshipHandler,
svc *services.Service, svc *services.Service,
repo *repositories.OAuthRepository, repo *repositories.OAuthRepository,
limiter *services.RateLimiter, limiter *services.RateLimiter,
@@ -50,8 +49,6 @@ func NewRouter(
middleware.RateLimit(limiter, services.RevokeRateLimit, middleware.RevokeKeyFn), middleware.RateLimit(limiter, services.RevokeRateLimit, middleware.RevokeKeyFn),
oauth.Revoke, oauth.Revoke,
) )
o.POST("/introspect", positions.Introspect)
} }
api := r.Group("/api/v1") api := r.Group("/api/v1")
@@ -72,101 +69,22 @@ func NewRouter(
me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile) me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile)
me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents) me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents)
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess) me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions)
me.GET("/citizenship", authMiddleware(svc, repo, "profile:read"), citizenship.GetCitizenshipApplicationByUserId)
me.POST("/citizenship", authMiddleware(svc, repo, "profile:edit"), citizenship.CreateCitizenshipApplication)
admin := api.Group("/admin", authMiddleware(svc, repo)) admin := api.Group("/admin")
admin.Use(authMiddleware(svc, repo), middleware.AdminOnly())
{ {
admin.PATCH("/citizenship/applications/:id", middleware.AdminOnly(), citizenship.ReviewCitizenshipApplication) c := admin.Group("/clients")
c.POST("", clients.Create)
manage := admin.Group("", permissionMiddleware(svc, "positions.manage")) c.GET("", clients.List)
{ c.GET("/:id", clients.Get)
manage.GET("/permissions", positions.ListPermissions) c.PATCH("/:id", clients.Update)
manage.POST("/permissions", positions.CreatePermission) c.DELETE("/:id", clients.Deactivate)
manage.PUT("/permissions/:code", positions.UpdatePermission)
manage.DELETE("/permissions/:code", positions.DeletePermission)
manage.GET("/positions", positions.ListPositions)
manage.POST("/positions", positions.UpsertPosition)
manage.PUT("/positions/:code", positions.UpdatePosition)
manage.DELETE("/positions/:code", positions.DeletePosition)
manage.POST("/positions/:code/permissions", positions.AddPermissionToPosition)
manage.DELETE("/positions/:code/permissions/:permissionCode", positions.RemovePermissionFromPosition)
}
usersRead := admin.Group("", permissionAnyMiddleware(svc, "positions.assign", "positions.revoke"))
{
usersRead.GET("/users", positions.ListUsersWithPositions)
}
assign := admin.Group("", permissionMiddleware(svc, "positions.assign"))
{
assign.POST("/users/:userId/positions", positions.AssignPosition)
}
revoke := admin.Group("", permissionMiddleware(svc, "positions.revoke"))
{
revoke.DELETE("/users/:userId/positions/:code", positions.RevokePosition)
}
} }
} }
return r return r
} }
func permissionAnyMiddleware(svc *services.Service, requiredPermissions ...string) gin.HandlerFunc {
return func(c *gin.Context) {
userID, ok := UserIDFromContext(c)
if !ok {
c.Error(models.ErrUnauthorized)
c.Abort()
return
}
for _, permission := range requiredPermissions {
allowed, err := svc.UserHasPermission(c.Request.Context(), userID, permission)
if err != nil {
c.Error(models.ErrInternal)
c.Abort()
return
}
if allowed {
c.Next()
return
}
}
c.Error(models.ErrForbidden.WithMessage("Missing required permissions"))
c.Abort()
}
}
func permissionMiddleware(svc *services.Service, requiredPermission string) gin.HandlerFunc {
return func(c *gin.Context) {
userID, ok := UserIDFromContext(c)
if !ok {
c.Error(models.ErrUnauthorized)
c.Abort()
return
}
allowed, err := svc.UserHasPermission(c.Request.Context(), userID, requiredPermission)
if err != nil {
c.Error(models.ErrInternal)
c.Abort()
return
}
if !allowed {
c.Error(models.ErrForbidden.WithMessage("Missing required permission: " + requiredPermission))
c.Abort()
return
}
c.Next()
}
}
func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, requiredScopes ...string) gin.HandlerFunc { func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, requiredScopes ...string) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
token, ok := bearerToken(c) token, ok := bearerToken(c)
@@ -1,35 +0,0 @@
package models
import (
"time"
"github.com/google/uuid"
)
type CitizenshipApplicationStatus string
const (
StatusPending CitizenshipApplicationStatus = "pending"
StatusApproved CitizenshipApplicationStatus = "approved"
StatusRejected CitizenshipApplicationStatus = "rejected"
)
type CitizenshipApplication struct {
Id uuid.UUID `db:"id" json:"id"`
UserId uuid.UUID `db:"user_id" json:"user_id"`
Status CitizenshipApplicationStatus `db:"status" json:"status"`
RegionId uuid.UUID `db:"region_id" json:"region_id"`
ReviewedBy *uuid.UUID `db:"reviewed_by" json:"reviewed_by,omitempty"`
ReviewedAt *time.Time `db:"reviewed_at" json:"reviewed_at,omitempty"`
RejectReason *string `db:"reject_reason" json:"reject_reason,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
type CreateCitizenshipApplicationInput struct {
RegionID uuid.UUID `json:"region_id" binding:"required"`
}
type ReviewCitizenshipApplicationInput struct {
Status CitizenshipApplicationStatus `json:"status" binding:"required"`
RejectReason *string `json:"reject_reason"`
}
@@ -45,6 +45,22 @@ type AuthorizationCodeRow struct {
CreatedAt time.Time `db:"created_at"` CreatedAt time.Time `db:"created_at"`
} }
type ClientCreateInput struct {
Name string `json:"name" binding:"required,min=2,max=128"`
RedirectURIs []string `json:"redirect_uris" binding:"required,min=1,dive,url"`
GrantTypes []string `json:"grant_types" binding:"required,min=1,dive,oneof=authorization_code refresh_token"`
Scopes []string `json:"scopes" binding:"required,min=1,dive,min=1"`
}
type ClientUpdateInput struct {
Name *string `json:"name" binding:"omitempty,min=2,max=128"`
RedirectURIs *[]string `json:"redirect_uris" binding:"omitempty,min=1,dive,url"`
GrantTypes *[]string `json:"grant_types" binding:"omitempty,min=1,dive,oneof=authorization_code refresh_token"`
Scopes *[]string `json:"scopes" binding:"omitempty,min=1,dive,min=1"`
Trusted *bool `json:"trusted"`
IsActive *bool `json:"is_active"`
}
type UserConsent struct { type UserConsent struct {
ID uuid.UUID `json:"id"` ID uuid.UUID `json:"id"`
UserID uuid.UUID `json:"-"` UserID uuid.UUID `json:"-"`
@@ -1,56 +0,0 @@
package models
import (
"time"
"github.com/google/uuid"
)
type Permission struct {
ID uuid.UUID `db:"id" json:"id"`
Code string `db:"code" json:"code"`
Name string `db:"name" json:"name"`
Description string `db:"description" json:"description"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
type Position struct {
ID uuid.UUID `db:"id" json:"id"`
Code string `db:"code" json:"code"`
Permissions []Permission `db:"-" json:"permissions,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
type PositionTranslation struct {
PositionID uuid.UUID `db:"position_id" json:"position_id"`
Locale string `db:"locale" json:"locale"`
Name string `db:"name" json:"name"`
Description *string `db:"description" json:"description,omitempty"`
}
type UserPosition struct {
ID uuid.UUID `db:"id" json:"id"`
UserID uuid.UUID `db:"user_id" json:"user_id"`
PositionID uuid.UUID `db:"position_id" json:"position_id"`
AssignedBy *uuid.UUID `db:"assigned_by" json:"assigned_by,omitempty"`
ValidFrom time.Time `db:"valid_from" json:"valid_from"`
ValidTo *time.Time `db:"valid_to" json:"valid_to,omitempty"`
}
type PositionLocalized struct {
Code string `json:"code"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Permissions []Permission `json:"permissions"`
}
type AssignPositionInput struct {
PositionCode string `json:"position_code" binding:"required"`
ValidFrom time.Time `json:"valid_from" binding:"omitempty"`
ValidTo *time.Time `json:"valid_to" binding:"omitempty"`
}
type RevokePositionInput struct {
PositionCode string `json:"position_code" binding:"required"`
}
@@ -1,25 +0,0 @@
package models
import (
"time"
"github.com/google/uuid"
)
type Region struct {
ID uuid.UUID `db:"id" json:"id"`
Code string `db:"code" json:"code"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
type RegionTranslation struct {
RegionID uuid.UUID `db:"region_id" json:"region_id"`
Locale string `db:"locale" json:"locale"`
Name string `db:"name" json:"name"`
}
type RegionLocalized struct {
ID uuid.UUID `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
}
@@ -19,15 +19,6 @@ type User struct {
UpdatedAt time.Time `db:"updated_at" json:"updated_at"` UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
} }
type UserWithPositions struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
FirstName string `json:"first_name"`
SecondName string `json:"second_name"`
IsAdmin bool `json:"is_admin"`
Positions []PositionLocalized `json:"positions"`
}
type UserRegisterInput struct { type UserRegisterInput struct {
Email string `json:"email" binding:"required,min=3"` Email string `json:"email" binding:"required,min=3"`
Password string `json:"password" binding:"required,min=8"` Password string `json:"password" binding:"required,min=8"`
@@ -1,88 +0,0 @@
package repositories
import (
"context"
"errors"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type CitizenshipRepository struct {
db *pgxpool.Pool
}
func NewCitizenshipRepository(db *pgxpool.Pool) *CitizenshipRepository {
return &CitizenshipRepository{db: db}
}
func (r *CitizenshipRepository) GetApplicationByUserId(ctx context.Context, userID uuid.UUID) (*models.CitizenshipApplication, error) {
var a models.CitizenshipApplication
err := r.db.QueryRow(
ctx,
`SELECT id, user_id, status, region_id, reviewed_by, reviewed_at, reject_reason, created_at
FROM citizenship_applications WHERE user_id = $1`,
userID,
).Scan(
&a.Id, &a.UserId, &a.Status, &a.RegionId,
&a.ReviewedBy, &a.ReviewedAt, &a.RejectReason, &a.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &a, nil
}
func (r *CitizenshipRepository) GetApplicationById(ctx context.Context, id uuid.UUID) (*models.CitizenshipApplication, error) {
var a models.CitizenshipApplication
err := r.db.QueryRow(
ctx,
`SELECT id, user_id, status, region_id, reviewed_by, reviewed_at, reject_reason, created_at
FROM citizenship_applications WHERE id = $1`,
id,
).Scan(
&a.Id, &a.UserId, &a.Status, &a.RegionId,
&a.ReviewedBy, &a.ReviewedAt, &a.RejectReason, &a.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &a, nil
}
func (r *CitizenshipRepository) CreateApplication(ctx context.Context, application models.CitizenshipApplication) (*models.CitizenshipApplication, error) {
err := r.db.QueryRow(
ctx,
`INSERT INTO citizenship_applications (user_id, region_id, status)
VALUES ($1, $2, $3)
RETURNING id, status, created_at`,
application.UserId, application.RegionId, application.Status,
).Scan(&application.Id, &application.Status, &application.CreatedAt)
if err != nil {
return nil, err
}
return &application, nil
}
func (r *CitizenshipRepository) UpdateApplication(ctx context.Context, id uuid.UUID, status models.CitizenshipApplicationStatus, reviewedBy uuid.UUID, rejectReason *string) error {
_, err := r.db.Exec(ctx, `
UPDATE citizenship_applications
SET status = $1, reviewed_by = $2, reviewed_at = now(), reject_reason = $3
WHERE id = $4
`, status, reviewedBy, rejectReason, id)
return err
}
@@ -63,6 +63,77 @@ func (r *OAuthRepository) GetOAuthClientByID(ctx context.Context, id uuid.UUID)
return &client, nil return &client, nil
} }
func (r *OAuthRepository) ListOAuthClients(ctx context.Context) ([]models.OAuthClient, error) {
rows, err := r.db.Query(ctx, `
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
FROM oauth_clients
ORDER BY created_at DESC
`)
if err != nil {
return nil, err
}
defer rows.Close()
var clients []models.OAuthClient
for rows.Next() {
var c models.OAuthClient
if err := rows.Scan(
&c.ID, &c.ClientID, &c.ClientSecret, &c.Name,
&c.RedirectURIs, &c.GrantTypes, &c.Scopes,
&c.IsActive, &c.Trusted, &c.CreatedAt, &c.UpdatedAt,
); err != nil {
return nil, err
}
clients = append(clients, c)
}
if err := rows.Err(); err != nil {
return nil, err
}
return clients, nil
}
func (r *OAuthRepository) GetOAuthClientByIDAdmin(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error) {
var client models.OAuthClient
err := r.db.QueryRow(ctx, `
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
FROM oauth_clients WHERE id = $1
`, id).Scan(
&client.ID, &client.ClientID, &client.ClientSecret, &client.Name,
&client.RedirectURIs, &client.GrantTypes, &client.Scopes,
&client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt,
)
if err != nil {
return nil, err
}
return &client, nil
}
func (r *OAuthRepository) UpdateOAuthClient(ctx context.Context, client models.OAuthClient) (*models.OAuthClient, error) {
err := r.db.QueryRow(ctx, `
UPDATE oauth_clients
SET name = $1,
redirect_uris = $2,
grant_types = $3,
scopes = $4,
trusted = $5,
is_active = $6,
updated_at = now()
WHERE id = $7
RETURNING updated_at
`, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes,
client.Trusted, client.IsActive, client.ID).
Scan(&client.UpdatedAt)
if err != nil {
return nil, fmt.Errorf("update oauth client: %w", err)
}
return &client, nil
}
func (r *OAuthRepository) DeactivateOAuthClient(ctx context.Context, id uuid.UUID) error {
_, err := r.db.Exec(ctx, `UPDATE oauth_clients SET is_active = false, updated_at = now() WHERE id = $1`, id)
return err
}
func (r *OAuthRepository) CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error) { func (r *OAuthRepository) CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error) {
err := r.db.QueryRow(ctx, ` err := r.db.QueryRow(ctx, `
INSERT INTO authorization_codes (code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at) INSERT INTO authorization_codes (code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at)
@@ -1,474 +0,0 @@
package repositories
import (
"context"
"strings"
"time"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type PositionRepository struct {
db *pgxpool.Pool
}
func NewPositionRepository(db *pgxpool.Pool) *PositionRepository {
return &PositionRepository{db: db}
}
func (r *PositionRepository) GetAllPermissions(ctx context.Context, locale string) ([]models.Permission, error) {
rows, err := r.db.Query(ctx, `
SELECT p.id,
p.code,
COALESCE(pl.name, pe.name, p.code) AS name,
COALESCE(pl.description, pe.description, p.description, '') AS description,
p.created_at
FROM permissions p
LEFT JOIN permission_translations pl
ON pl.permission_id = p.id AND pl.locale = $1
LEFT JOIN permission_translations pe
ON pe.permission_id = p.id AND pe.locale = 'en'
ORDER BY code
`, strings.ToLower(locale))
if err != nil {
return nil, err
}
defer rows.Close()
var result []models.Permission
for rows.Next() {
var p models.Permission
if err := rows.Scan(&p.ID, &p.Code, &p.Name, &p.Description, &p.CreatedAt); err != nil {
return nil, err
}
result = append(result, p)
}
return result, rows.Err()
}
func (r *PositionRepository) CreatePermission(ctx context.Context, code, locale string, description *string) error {
tx, err := r.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var permissionID uuid.UUID
err = tx.QueryRow(ctx, `
INSERT INTO permissions (code, description)
VALUES ($1, $2)
RETURNING id
`, code, description).Scan(&permissionID)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `
INSERT INTO permission_translations (permission_id, locale, name, description)
VALUES ($1, $2, $3, $4)
ON CONFLICT (permission_id, locale) DO UPDATE
SET name = EXCLUDED.name, description = EXCLUDED.description
`, permissionID, strings.ToLower(locale), code, description)
if err != nil {
return err
}
return tx.Commit(ctx)
}
func (r *PositionRepository) UpdatePermission(ctx context.Context, code, locale string, description *string) error {
tx, err := r.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var permissionID uuid.UUID
err = tx.QueryRow(ctx, `
UPDATE permissions
SET description = $2
WHERE code = $1
RETURNING id
`, code, description).Scan(&permissionID)
if err != nil {
return models.ErrNotFound
}
_, err = tx.Exec(ctx, `
INSERT INTO permission_translations (permission_id, locale, name, description)
VALUES ($1, $2, $3, $4)
ON CONFLICT (permission_id, locale) DO UPDATE
SET name = EXCLUDED.name, description = EXCLUDED.description
`, permissionID, strings.ToLower(locale), code, description)
if err != nil {
return err
}
return tx.Commit(ctx)
}
func (r *PositionRepository) DeletePermission(ctx context.Context, code string) error {
tag, err := r.db.Exec(ctx, `DELETE FROM permissions WHERE code = $1`, code)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return models.ErrNotFound
}
return nil
}
func (r *PositionRepository) GetPermissionByCode(ctx context.Context, code string) (*models.Permission, error) {
var p models.Permission
err := r.db.QueryRow(ctx, `
SELECT id, code, COALESCE(description, ''), created_at
FROM permissions WHERE code = $1
`, code).Scan(&p.ID, &p.Code, &p.Description, &p.CreatedAt)
if err != nil {
return nil, err
}
return &p, nil
}
func (r *PositionRepository) GetPositionPermissions(ctx context.Context, positionID uuid.UUID, locale string) ([]models.Permission, error) {
rows, err := r.db.Query(ctx, `
SELECT p.id,
p.code,
COALESCE(pl.name, pe.name, p.code) AS name,
COALESCE(pl.description, pe.description, p.description, '') AS description,
p.created_at
FROM position_permissions pp
JOIN permissions p ON pp.permission_id = p.id
LEFT JOIN permission_translations pl
ON pl.permission_id = p.id AND pl.locale = $2
LEFT JOIN permission_translations pe
ON pe.permission_id = p.id AND pe.locale = 'en'
WHERE pp.position_id = $1
ORDER BY p.code
`, positionID, strings.ToLower(locale))
if err != nil {
return nil, err
}
defer rows.Close()
var result []models.Permission
for rows.Next() {
var p models.Permission
if err := rows.Scan(&p.ID, &p.Code, &p.Name, &p.Description, &p.CreatedAt); err != nil {
return nil, err
}
result = append(result, p)
}
return result, rows.Err()
}
func (r *PositionRepository) AddPermissionToPosition(ctx context.Context, positionID, permissionID uuid.UUID) error {
_, err := r.db.Exec(ctx, `
INSERT INTO position_permissions (position_id, permission_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
`, positionID, permissionID)
return err
}
func (r *PositionRepository) RemovePermissionFromPosition(ctx context.Context, positionID, permissionID uuid.UUID) error {
_, err := r.db.Exec(ctx, `
DELETE FROM position_permissions
WHERE position_id = $1 AND permission_id = $2
`, positionID, permissionID)
return err
}
func (r *PositionRepository) GetPositionByCode(ctx context.Context, code string) (*models.Position, error) {
var p models.Position
err := r.db.QueryRow(ctx, `
SELECT id, code, created_at, updated_at
FROM positions WHERE code = $1
`, code).Scan(&p.ID, &p.Code, &p.CreatedAt, &p.UpdatedAt)
if err != nil {
return nil, err
}
return &p, nil
}
func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error) {
rows, err := r.db.Query(ctx, `
SELECT p.id, p.code,
COALESCE(pt.name, p.code) AS name,
pt.description
FROM user_positions up
JOIN positions p ON up.position_id = p.id
LEFT JOIN position_translations pt
ON pt.position_id = p.id AND pt.locale = $2
WHERE up.user_id = $1
AND (up.valid_to IS NULL OR up.valid_to > now())
ORDER BY name
`, userID, strings.ToLower(locale))
if err != nil {
return nil, err
}
defer rows.Close()
var positions []posRow
for rows.Next() {
var r posRow
if err := rows.Scan(&r.id, &r.p.Code, &r.p.Name, &r.p.Description); err != nil {
return nil, err
}
positions = append(positions, r)
}
if err := rows.Err(); err != nil {
return nil, err
}
permMap, err := r.getPositionPermissionsBatch(ctx, positionIDs(positions), locale)
if err != nil {
return nil, err
}
result := make([]models.PositionLocalized, len(positions))
for i, pos := range positions {
pos.p.Permissions = permMap[pos.id]
if pos.p.Permissions == nil {
pos.p.Permissions = []models.Permission{}
}
result[i] = pos.p
}
return result, nil
}
func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) {
rows, err := r.db.Query(ctx, `
SELECT p.id, p.code,
COALESCE(pt.name, p.code) AS name,
pt.description
FROM positions p
LEFT JOIN position_translations pt
ON pt.position_id = p.id AND pt.locale = $1
ORDER BY name
`, strings.ToLower(locale))
if err != nil {
return nil, err
}
defer rows.Close()
var positions []posRow
for rows.Next() {
var r posRow
if err := rows.Scan(&r.id, &r.p.Code, &r.p.Name, &r.p.Description); err != nil {
return nil, err
}
positions = append(positions, r)
}
if err := rows.Err(); err != nil {
return nil, err
}
permMap, err := r.getPositionPermissionsBatch(ctx, positionIDs(positions), locale)
if err != nil {
return nil, err
}
result := make([]models.PositionLocalized, len(positions))
for i, pos := range positions {
pos.p.Permissions = permMap[pos.id]
if pos.p.Permissions == nil {
pos.p.Permissions = []models.Permission{}
}
result[i] = pos.p
}
return result, nil
}
func (r *PositionRepository) GetUsersWithPositions(ctx context.Context, locale string) ([]models.UserWithPositions, error) {
rows, err := r.db.Query(ctx, `
SELECT id, email, first_name, second_name, is_admin
FROM users
ORDER BY first_name, second_name, email
`)
if err != nil {
return nil, err
}
defer rows.Close()
var result []models.UserWithPositions
for rows.Next() {
var u models.UserWithPositions
if err := rows.Scan(&u.ID, &u.Email, &u.FirstName, &u.SecondName, &u.IsAdmin); err != nil {
return nil, err
}
positions, err := r.GetUserPositions(ctx, u.ID, locale)
if err != nil {
return nil, err
}
if positions == nil {
positions = []models.PositionLocalized{}
}
u.Positions = positions
result = append(result, u)
}
return result, rows.Err()
}
type posRow struct {
id uuid.UUID
p models.PositionLocalized
}
func (pr posRow) getID() uuid.UUID { return pr.id }
func positionIDs(items []posRow) []uuid.UUID {
ids := make([]uuid.UUID, len(items))
for i, item := range items {
ids[i] = item.id
}
return ids
}
func (r *PositionRepository) getPositionPermissionsBatch(ctx context.Context, pIDs []uuid.UUID, locale string) (map[uuid.UUID][]models.Permission, error) {
if len(pIDs) == 0 {
return nil, nil
}
rows, err := r.db.Query(ctx, `
SELECT pp.position_id,
p.id, p.code,
COALESCE(pl.name, pe.name, p.code) AS name,
COALESCE(pl.description, pe.description, p.description, '') AS description,
p.created_at
FROM position_permissions pp
JOIN permissions p ON pp.permission_id = p.id
LEFT JOIN permission_translations pl
ON pl.permission_id = p.id AND pl.locale = $2
LEFT JOIN permission_translations pe
ON pe.permission_id = p.id AND pe.locale = 'en'
WHERE pp.position_id = ANY($1)
ORDER BY pp.position_id, p.code
`, pIDs, strings.ToLower(locale))
if err != nil {
return nil, err
}
defer rows.Close()
result := make(map[uuid.UUID][]models.Permission)
for rows.Next() {
var positionID uuid.UUID
var perm models.Permission
if err := rows.Scan(&positionID, &perm.ID, &perm.Code, &perm.Name, &perm.Description, &perm.CreatedAt); err != nil {
return nil, err
}
result[positionID] = append(result[positionID], perm)
}
return result, rows.Err()
}
func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error {
tx, err := r.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var positionID uuid.UUID
err = tx.QueryRow(ctx, `
INSERT INTO positions (code)
VALUES ($1)
ON CONFLICT (code) DO UPDATE SET updated_at = now()
RETURNING id
`, code).Scan(&positionID)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `
INSERT INTO position_translations (position_id, locale, name, description)
VALUES ($1, $2, $3, $4)
ON CONFLICT (position_id, locale) DO UPDATE
SET name = EXCLUDED.name, description = EXCLUDED.description
`, positionID, strings.ToLower(locale), name, description)
if err != nil {
return err
}
return tx.Commit(ctx)
}
func (r *PositionRepository) DeletePositionByCode(ctx context.Context, code string) error {
_, err := r.db.Exec(ctx, `DELETE FROM positions WHERE code = $1`, code)
return err
}
func (r *PositionRepository) AssignPosition(ctx context.Context, userID, positionID uuid.UUID, assignedBy *uuid.UUID, validFrom time.Time, validTo *time.Time) error {
_, err := r.db.Exec(ctx, `
INSERT INTO user_positions (user_id, position_id, assigned_by, valid_from, valid_to)
VALUES ($1, $2, $3, COALESCE($4, now()), $5)
`, userID, positionID, assignedBy, validFrom, validTo)
return err
}
func (r *PositionRepository) RevokePosition(ctx context.Context, userID, positionID uuid.UUID) error {
_, err := r.db.Exec(ctx, `
UPDATE user_positions
SET valid_to = now()
WHERE user_id = $1
AND position_id = $2
AND valid_to IS NULL
`, userID, positionID)
return err
}
func (r *PositionRepository) UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, string, error) {
var positionCode string
err := r.db.QueryRow(ctx, `
SELECT p.code
FROM user_positions up
JOIN positions p ON up.position_id = p.id
JOIN position_permissions pp ON pp.position_id = p.id
JOIN permissions perm ON pp.permission_id = perm.id
WHERE up.user_id = $1
AND perm.code = $2
AND (up.valid_to IS NULL OR up.valid_to > now())
LIMIT 1
`, userID, permissionCode).Scan(&positionCode)
if err != nil {
return false, "", nil
}
return true, positionCode, nil
}
func (r *PositionRepository) GetUserPermissions(ctx context.Context, userID uuid.UUID, locale string) ([]models.Permission, error) {
rows, err := r.db.Query(ctx, `
SELECT DISTINCT perm.id,
perm.code,
COALESCE(pl.name, pe.name, perm.code) AS name,
COALESCE(pl.description, pe.description, perm.description, '') AS description,
perm.created_at
FROM user_positions up
JOIN position_permissions pp ON pp.position_id = up.position_id
JOIN permissions perm ON pp.permission_id = perm.id
LEFT JOIN permission_translations pl
ON pl.permission_id = perm.id AND pl.locale = $2
LEFT JOIN permission_translations pe
ON pe.permission_id = perm.id AND pe.locale = 'en'
WHERE up.user_id = $1
AND (up.valid_to IS NULL OR up.valid_to > now())
ORDER BY perm.code
`, userID, strings.ToLower(locale))
if err != nil {
return nil, err
}
defer rows.Close()
var result []models.Permission
for rows.Next() {
var p models.Permission
if err := rows.Scan(&p.ID, &p.Code, &p.Name, &p.Description, &p.CreatedAt); err != nil {
return nil, err
}
result = append(result, p)
}
return result, rows.Err()
}
@@ -43,18 +43,6 @@ func (s *Service) Register(ctx context.Context, input models.UserRegisterInput)
return nil, err return nil, err
} }
count, err := s.users.CountUsers(ctx)
if err != nil {
return nil, models.ErrInternal
}
if count == 1 {
position, err := s.positions.GetPositionByCode(ctx, "kotosoft_id_staff")
if err == nil {
now := time.Now()
_ = s.positions.AssignPosition(ctx, user.ID, position.ID, nil, now, nil)
}
}
return user, nil return user, nil
} }
@@ -1,86 +0,0 @@
package services
import (
"context"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/dusiburg/kotosoft-id/internal/repositories"
"github.com/google/uuid"
)
type CitizenshipService struct {
r *repositories.CitizenshipRepository
}
func NewCitizenshipService(r *repositories.CitizenshipRepository) *CitizenshipService {
return &CitizenshipService{r: r}
}
func (s *CitizenshipService) GetCitizenshipApplicationByUserId(ctx context.Context, userID uuid.UUID) (*models.CitizenshipApplication, error) {
application, err := s.r.GetApplicationByUserId(ctx, userID)
if err != nil {
return nil, models.ErrInternal
}
if application == nil {
return nil, models.ErrNotFound
}
return application, nil
}
func (s *CitizenshipService) CreateCitizenshipApplication(ctx context.Context, userID, regionID uuid.UUID) (*models.CitizenshipApplication, error) {
exists, err := s.r.GetApplicationByUserId(ctx, userID)
if err != nil {
return nil, models.ErrInternal
}
if exists != nil {
return nil, models.ErrAlreadyExists
}
application, err := s.r.CreateApplication(ctx, models.CitizenshipApplication{
UserId: userID,
Status: models.StatusPending,
RegionId: regionID,
})
if err != nil {
return nil, models.ErrInternal
}
return application, nil
}
func (s *CitizenshipService) ReviewCitizenshipApplication(ctx context.Context, applicationID, reviewerID uuid.UUID, input models.ReviewCitizenshipApplicationInput) (*models.CitizenshipApplication, error) {
if input.Status != models.StatusApproved && input.Status != models.StatusRejected {
return nil, models.ErrBadRequest
}
if input.Status == models.StatusRejected && (input.RejectReason == nil || *input.RejectReason == "") {
return nil, models.ErrBadRequest.WithMessage("Reject reason is required")
}
application, err := s.r.GetApplicationById(ctx, applicationID)
if err != nil {
return nil, models.ErrInternal
}
if application == nil {
return nil, models.ErrNotFound
}
if application.Status != models.StatusPending {
return nil, models.ErrBadRequest.WithMessage("Application is not pending")
}
rejectReason := input.RejectReason
if input.Status == models.StatusApproved {
rejectReason = nil
}
if err := s.r.UpdateApplication(ctx, applicationID, input.Status, reviewerID, rejectReason); err != nil {
return nil, models.ErrInternal
}
updated, err := s.r.GetApplicationById(ctx, applicationID)
if err != nil {
return nil, models.ErrInternal
}
return updated, nil
}
@@ -0,0 +1,97 @@
package services
import (
"context"
"encoding/json"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
)
func (s *Service) CreateClient(ctx context.Context, input models.ClientCreateInput) (*models.OAuthClient, string, error) {
clientID, err := newOpaqueToken(12)
if err != nil {
return nil, "", models.ErrInternal
}
rawSecret, err := newOpaqueToken(32)
if err != nil {
return nil, "", models.ErrInternal
}
hashedSecret, err := HashClientSecret(rawSecret)
if err != nil {
return nil, "", models.ErrInternal
}
redirectURIsJSON, _ := json.Marshal(input.RedirectURIs)
grantTypesJSON, _ := json.Marshal(input.GrantTypes)
scopesJSON, _ := json.Marshal(input.Scopes)
client, err := s.oauth.CreateOAuthClient(ctx, models.OAuthClient{
ClientID: clientID,
ClientSecret: hashedSecret,
Name: input.Name,
RedirectURIs: redirectURIsJSON,
GrantTypes: grantTypesJSON,
Scopes: scopesJSON,
Trusted: false,
})
if err != nil {
return nil, "", models.ErrInternal
}
return client, rawSecret, nil
}
func (s *Service) ListClients(ctx context.Context) ([]models.OAuthClient, error) {
return s.oauth.ListOAuthClients(ctx)
}
func (s *Service) GetClient(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error) {
client, err := s.oauth.GetOAuthClientByIDAdmin(ctx, id)
if err != nil {
return nil, models.ErrNotFound
}
return client, nil
}
func (s *Service) UpdateClient(ctx context.Context, id uuid.UUID, input models.ClientUpdateInput) (*models.OAuthClient, error) {
client, err := s.oauth.GetOAuthClientByIDAdmin(ctx, id)
if err != nil {
return nil, models.ErrNotFound
}
if input.Name != nil {
client.Name = *input.Name
}
if input.RedirectURIs != nil {
b, _ := json.Marshal(*input.RedirectURIs)
client.RedirectURIs = b
}
if input.GrantTypes != nil {
b, _ := json.Marshal(*input.GrantTypes)
client.GrantTypes = b
}
if input.Scopes != nil {
b, _ := json.Marshal(*input.Scopes)
client.Scopes = b
}
if input.Trusted != nil {
client.Trusted = *input.Trusted
}
if input.IsActive != nil {
client.IsActive = *input.IsActive
}
updated, err := s.oauth.UpdateOAuthClient(ctx, *client)
if err != nil {
return nil, models.ErrInternal
}
return updated, nil
}
func (s *Service) DeactivateClient(ctx context.Context, id uuid.UUID) error {
if err := s.oauth.DeactivateOAuthClient(ctx, id); err != nil {
return models.ErrInternal
}
return nil
}
+30 -3
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"net/url" "net/url"
"strings" "strings"
"time" "time"
@@ -156,10 +157,14 @@ 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) data, err := s.redis.GetDel(ctx, oauthSessionPrefix+token).Bytes()
if err != nil { if err != nil {
return "", ErrInvalidGrant return "", ErrInvalidGrant
} }
var sess OAuthSession
if err := json.Unmarshal(data, &sess); err != nil {
return "", ErrInvalidGrant
}
if sess.UserID == uuid.Nil { if sess.UserID == uuid.Nil {
return "", ErrInvalidGrant return "", ErrInvalidGrant
} }
@@ -174,8 +179,9 @@ func (s *Service) SessionApprove(ctx context.Context, token string) (string, err
return "", err return "", err
} }
_ = s.redis.Del(ctx, oauthSessionPrefix+token) if err := s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes); err != nil {
_ = s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) log.Printf("oauth: failed to record consent for user %s client %s: %v", sess.UserID, client.ClientID, err)
}
redirectURL, _ := url.Parse(sess.RedirectURI) redirectURL, _ := url.Parse(sess.RedirectURI)
q := redirectURL.Query() q := redirectURL.Query()
@@ -188,6 +194,27 @@ func (s *Service) SessionApprove(ctx context.Context, token string) (string, err
return redirectURL.String(), nil return redirectURL.String(), nil
} }
func (s *Service) SessionDeny(ctx context.Context, token string) (string, error) {
data, err := s.redis.GetDel(ctx, oauthSessionPrefix+token).Bytes()
if err != nil {
return "", ErrInvalidGrant
}
var sess OAuthSession
if err := json.Unmarshal(data, &sess); err != nil {
return "", ErrInvalidGrant
}
redirectURL, _ := url.Parse(sess.RedirectURI)
q := redirectURL.Query()
q.Set("error", "access_denied")
if sess.State != "" {
q.Set("state", sess.State)
}
redirectURL.RawQuery = q.Encode()
return redirectURL.String(), nil
}
func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redirectURI, codeVerifier string) (*TokenPair, error) { func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redirectURI, codeVerifier string) (*TokenPair, error) {
if auth.ClientID == "" || code == "" || redirectURI == "" || codeVerifier == "" { if auth.ClientID == "" || code == "" || redirectURI == "" || codeVerifier == "" {
return nil, ErrInvalidRequest return nil, ErrInvalidRequest
@@ -1,174 +0,0 @@
package services
import (
"context"
"time"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/google/uuid"
)
func (s *Service) GetAllPermissions(ctx context.Context) ([]models.Permission, error) {
return s.positions.GetAllPermissions(ctx, "en")
}
func (s *Service) AddPermissionToPosition(ctx context.Context, positionCode, permissionCode string) error {
position, err := s.positions.GetPositionByCode(ctx, positionCode)
if err != nil {
return models.ErrNotFound
}
permission, err := s.positions.GetPermissionByCode(ctx, permissionCode)
if err != nil {
return models.ErrNotFound
}
return s.positions.AddPermissionToPosition(ctx, position.ID, permission.ID)
}
func (s *Service) RemovePermissionFromPosition(ctx context.Context, positionCode, permissionCode string) error {
position, err := s.positions.GetPositionByCode(ctx, positionCode)
if err != nil {
return models.ErrNotFound
}
permission, err := s.positions.GetPermissionByCode(ctx, permissionCode)
if err != nil {
return models.ErrNotFound
}
return s.positions.RemovePermissionFromPosition(ctx, position.ID, permission.ID)
}
func (s *Service) GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error) {
if locale == "" {
locale = "en"
}
return s.positions.GetUserPositions(ctx, userID, locale)
}
func (s *Service) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) {
if locale == "" {
locale = "en"
}
return s.positions.GetAllPositions(ctx, locale)
}
func (s *Service) GetUsersWithPositions(ctx context.Context, locale string) ([]models.UserWithPositions, error) {
if locale == "" {
locale = "en"
}
return s.positions.GetUsersWithPositions(ctx, locale)
}
func (s *Service) UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error {
if locale == "" {
locale = "en"
}
return s.positions.UpsertPositionForLocale(ctx, code, locale, name, description)
}
func (s *Service) DeletePosition(ctx context.Context, code string) error {
return s.positions.DeletePositionByCode(ctx, code)
}
func (s *Service) AssignPosition(ctx context.Context, adminID, targetUserID uuid.UUID, input models.AssignPositionInput) error {
position, err := s.positions.GetPositionByCode(ctx, input.PositionCode)
if err != nil {
return models.ErrNotFound
}
validFrom := input.ValidFrom
if validFrom.IsZero() {
validFrom = time.Now()
}
return s.positions.AssignPosition(ctx, targetUserID, position.ID, &adminID, validFrom, input.ValidTo)
}
func (s *Service) RevokePosition(ctx context.Context, targetUserID uuid.UUID, positionCode string) error {
position, err := s.positions.GetPositionByCode(ctx, positionCode)
if err != nil {
return models.ErrNotFound
}
if position.Code == "kotosoft_id_staff" {
return models.ErrForbidden
}
return s.positions.RevokePosition(ctx, targetUserID, position.ID)
}
func (s *Service) GetAllPermissionsForLocale(ctx context.Context, locale string) ([]models.Permission, error) {
if locale == "" {
locale = "en"
}
return s.positions.GetAllPermissions(ctx, locale)
}
func (s *Service) CreatePermission(ctx context.Context, code, locale string, description *string) error {
if locale == "" {
locale = "en"
}
return s.positions.CreatePermission(ctx, code, locale, description)
}
func (s *Service) UpdatePermission(ctx context.Context, code, locale string, description *string) error {
if locale == "" {
locale = "en"
}
return s.positions.UpdatePermission(ctx, code, locale, description)
}
func (s *Service) DeletePermission(ctx context.Context, code string) error {
return s.positions.DeletePermission(ctx, code)
}
func (s *Service) UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, error) {
allowed, _, err := s.positions.UserHasPermission(ctx, userID, permissionCode)
return allowed, err
}
type IntrospectResponse struct {
Active bool `json:"active"`
Sub string `json:"sub"`
IsAdmin bool `json:"is_admin"`
Positions []models.PositionLocalized `json:"positions"`
Permissions []models.Permission `json:"permissions"`
}
func (s *Service) IntrospectToken(ctx context.Context, token string) (*IntrospectResponse, error) {
info, err := s.ValidateAccessToken(ctx, token)
if err != nil {
return &IntrospectResponse{Active: false}, nil
}
user, err := s.users.GetUserByID(ctx, info.UserID)
if err != nil {
return &IntrospectResponse{Active: false}, nil
}
positions, err := s.positions.GetUserPositions(ctx, user.ID, "en")
if err != nil {
return &IntrospectResponse{Active: false}, nil
}
if positions == nil {
positions = []models.PositionLocalized{}
}
allPerms, err := s.positions.GetUserPermissions(ctx, user.ID, "en")
if err != nil {
return &IntrospectResponse{Active: false}, nil
}
if allPerms == nil {
allPerms = []models.Permission{}
}
return &IntrospectResponse{
Active: true,
Sub: user.ID.String(),
IsAdmin: user.IsAdmin,
Positions: positions,
Permissions: allPerms,
}, nil
}
@@ -32,6 +32,11 @@ type UserRepo interface {
type OAuthRepo interface { type OAuthRepo interface {
GetOAuthClientByClientID(ctx context.Context, clientID string) (*models.OAuthClient, error) GetOAuthClientByClientID(ctx context.Context, clientID string) (*models.OAuthClient, error)
GetOAuthClientByID(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error) GetOAuthClientByID(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error)
CreateOAuthClient(ctx context.Context, client models.OAuthClient) (*models.OAuthClient, error)
ListOAuthClients(ctx context.Context) ([]models.OAuthClient, error)
GetOAuthClientByIDAdmin(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error)
UpdateOAuthClient(ctx context.Context, client models.OAuthClient) (*models.OAuthClient, error)
DeactivateOAuthClient(ctx context.Context, id uuid.UUID) error
CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error) CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error)
GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error) GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error)
ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error
@@ -47,31 +52,6 @@ type OAuthRepo interface {
UpsertClient(ctx context.Context, client models.OAuthClient) error UpsertClient(ctx context.Context, client models.OAuthClient) error
} }
type PositionRepo interface {
GetAllPermissions(ctx context.Context, locale string) ([]models.Permission, error)
GetPermissionByCode(ctx context.Context, code string) (*models.Permission, error)
GetPositionPermissions(ctx context.Context, positionID uuid.UUID, locale string) ([]models.Permission, error)
AddPermissionToPosition(ctx context.Context, positionID, permissionID uuid.UUID) error
RemovePermissionFromPosition(ctx context.Context, positionID, permissionID uuid.UUID) error
GetPositionByCode(ctx context.Context, code string) (*models.Position, error)
GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error)
GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error)
GetUsersWithPositions(ctx context.Context, locale string) ([]models.UserWithPositions, error)
UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error
AssignPosition(ctx context.Context, userID, positionID uuid.UUID, assignedBy *uuid.UUID, validFrom time.Time, validTo *time.Time) error
RevokePosition(ctx context.Context, userID, positionID uuid.UUID) error
UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, string, error)
GetUserPermissions(ctx context.Context, userID uuid.UUID, locale string) ([]models.Permission, error)
CreatePermission(ctx context.Context, code, locale string, description *string) error
UpdatePermission(ctx context.Context, code, locale string, description *string) error
DeletePositionByCode(ctx context.Context, code string) error
DeletePermission(ctx context.Context, code string) error
}
type TokenConfig struct { type TokenConfig struct {
AccessTTL time.Duration AccessTTL time.Duration
RefreshTTL time.Duration RefreshTTL time.Duration
@@ -83,26 +63,23 @@ type ClientAuth struct {
} }
type Service struct { type Service struct {
users UserRepo users UserRepo
oauth OAuthRepo oauth OAuthRepo
positions PositionRepo redis *redis.Client
redis *redis.Client tokens TokenConfig
tokens TokenConfig
} }
func New( func New(
users UserRepo, users UserRepo,
oauth OAuthRepo, oauth OAuthRepo,
positions PositionRepo,
rdb *redis.Client, rdb *redis.Client,
tokenCfg TokenConfig, tokenCfg TokenConfig,
) *Service { ) *Service {
return &Service{ return &Service{
users: users, users: users,
oauth: oauth, oauth: oauth,
positions: positions, redis: rdb,
redis: rdb, tokens: tokenCfg,
tokens: tokenCfg,
} }
} }
+14 -184
View File
@@ -1,5 +1,19 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto; CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Cleanup: tables from an earlier "multi-tenant RBAC" design (regions,
-- citizenship, positions, permissions) that was never wired up to any
-- backend code. Safe to drop — nothing in this codebase reads or writes them.
DROP TABLE IF EXISTS public.user_positions CASCADE;
DROP TABLE IF EXISTS public.position_permissions CASCADE;
DROP TABLE IF EXISTS public.permission_translations CASCADE;
DROP TABLE IF EXISTS public.permissions CASCADE;
DROP TABLE IF EXISTS public.position_translations CASCADE;
DROP TABLE IF EXISTS public.positions CASCADE;
DROP TABLE IF EXISTS public.citizens CASCADE;
DROP TABLE IF EXISTS public.citizenship_applications CASCADE;
DROP TABLE IF EXISTS public.region_translations CASCADE;
DROP TABLE IF EXISTS public.regions CASCADE;
CREATE TABLE IF NOT EXISTS public.users ( CREATE TABLE IF NOT EXISTS public.users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(), id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
created_at timestamptz NOT NULL DEFAULT now(), created_at timestamptz NOT NULL DEFAULT now(),
@@ -94,112 +108,6 @@ CREATE INDEX IF NOT EXISTS idx_user_consents_revoked
ON public.user_consents (revoked_at) ON public.user_consents (revoked_at)
WHERE revoked_at IS NOT NULL; WHERE revoked_at IS NOT NULL;
CREATE TABLE IF NOT EXISTS public.regions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code char(2) NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS public.region_translations (
region_id uuid NOT NULL REFERENCES public.regions(id) ON DELETE CASCADE,
locale text NOT NULL,
name text NOT NULL,
PRIMARY KEY (region_id, locale)
);
CREATE INDEX IF NOT EXISTS idx_region_translations_region_id
ON public.region_translations (region_id);
CREATE TABLE IF NOT EXISTS public.citizenship_applications (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL UNIQUE REFERENCES public.users(id) ON DELETE CASCADE,
status text NOT NULL DEFAULT 'pending',
region_id uuid REFERENCES public.regions(id),
reviewed_by uuid REFERENCES public.users(id),
reviewed_at timestamptz,
reject_reason text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS public.citizens (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL UNIQUE REFERENCES public.users(id),
application_id uuid NOT NULL REFERENCES public.citizenship_applications(id),
number text NOT NULL UNIQUE,
issued_at timestamptz NOT NULL DEFAULT now(),
region_id uuid REFERENCES public.regions(id)
);
CREATE TABLE IF NOT EXISTS public.positions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS public.position_translations (
position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE,
locale text NOT NULL DEFAULT 'en',
name text NOT NULL,
description text,
PRIMARY KEY (position_id, locale)
);
CREATE INDEX IF NOT EXISTS idx_position_translations_position_id
ON public.position_translations (position_id);
CREATE INDEX IF NOT EXISTS idx_position_translations_locale
ON public.position_translations (locale);
CREATE TABLE IF NOT EXISTS public.permissions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code text NOT NULL UNIQUE,
description text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS public.permission_translations (
permission_id uuid NOT NULL REFERENCES public.permissions(id) ON DELETE CASCADE,
locale text NOT NULL DEFAULT 'en',
name text NOT NULL,
description text,
PRIMARY KEY (permission_id, locale)
);
CREATE INDEX IF NOT EXISTS idx_permission_translations_permission_id
ON public.permission_translations (permission_id);
CREATE INDEX IF NOT EXISTS idx_permission_translations_locale
ON public.permission_translations (locale);
CREATE TABLE IF NOT EXISTS public.position_permissions (
position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE,
permission_id uuid NOT NULL REFERENCES public.permissions(id) ON DELETE CASCADE,
PRIMARY KEY (position_id, permission_id)
);
CREATE INDEX IF NOT EXISTS idx_position_permissions_position_id
ON public.position_permissions (position_id);
CREATE INDEX IF NOT EXISTS idx_position_permissions_permission_id
ON public.position_permissions (permission_id);
CREATE TABLE IF NOT EXISTS public.user_positions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE,
valid_from timestamptz NOT NULL DEFAULT now(),
valid_to timestamptz,
assigned_by uuid REFERENCES public.users(id) ON DELETE SET NULL
);
CREATE INDEX IF NOT EXISTS idx_user_positions_user_id
ON public.user_positions (user_id);
CREATE INDEX IF NOT EXISTS idx_user_positions_position_id
ON public.user_positions (position_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_positions_unique_active
ON public.user_positions (user_id, position_id)
WHERE valid_to IS NULL;
CREATE INDEX IF NOT EXISTS idx_permissions_code
ON public.permissions (code);
CREATE INDEX IF NOT EXISTS idx_users_is_admin CREATE INDEX IF NOT EXISTS idx_users_is_admin
ON public.users (is_admin) ON public.users (is_admin)
WHERE is_admin = TRUE; WHERE is_admin = TRUE;
@@ -221,81 +129,3 @@ DROP TRIGGER IF EXISTS oauth_clients_updated_at ON public.oauth_clients;
CREATE TRIGGER oauth_clients_updated_at CREATE TRIGGER oauth_clients_updated_at
BEFORE UPDATE ON public.oauth_clients BEFORE UPDATE ON public.oauth_clients
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
DROP TRIGGER IF EXISTS positions_updated_at ON public.positions;
CREATE TRIGGER positions_updated_at
BEFORE UPDATE ON public.positions
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
INSERT INTO public.permissions (code, description) VALUES
('positions.manage', 'Create and edit positions'),
('positions.assign', 'Assign positions to users'),
('positions.revoke', 'Revoke positions from users')
ON CONFLICT (code) DO NOTHING;
INSERT INTO public.permission_translations (permission_id, locale, name, description)
SELECT id, 'en', code, description FROM public.permissions
ON CONFLICT (permission_id, locale) DO NOTHING;
INSERT INTO public.permission_translations (permission_id, locale, name, description)
SELECT id,
'ru',
CASE code
WHEN 'positions.manage' THEN 'Управление должностями'
WHEN 'positions.assign' THEN 'Назначение должностей'
WHEN 'positions.revoke' THEN 'Отзыв должностей'
ELSE code
END,
CASE code
WHEN 'positions.manage' THEN 'Создание и редактирование должностей'
WHEN 'positions.assign' THEN 'Назначение должностей пользователям'
WHEN 'positions.revoke' THEN 'Отзыв должностей у пользователей'
ELSE description
END
FROM public.permissions
ON CONFLICT (permission_id, locale) DO NOTHING;
INSERT INTO public.permission_translations (permission_id, locale, name, description)
SELECT id,
'it',
CASE code
WHEN 'positions.manage' THEN 'Gestione posizioni'
WHEN 'positions.assign' THEN 'Assegnazione posizioni'
WHEN 'positions.revoke' THEN 'Revoca posizioni'
ELSE code
END,
CASE code
WHEN 'positions.manage' THEN 'Creazione e modifica delle posizioni'
WHEN 'positions.assign' THEN 'Assegnazione delle posizioni agli utenti'
WHEN 'positions.revoke' THEN 'Revoca delle posizioni dagli utenti'
ELSE description
END
FROM public.permissions
ON CONFLICT (permission_id, locale) DO NOTHING;
INSERT INTO public.positions (code)
VALUES ('kotosoft_id_staff')
ON CONFLICT (code) DO NOTHING;
INSERT INTO public.position_translations (position_id, locale, name, description)
SELECT id, 'en', 'Kotosoft ID Staff', 'Default staff position for Kotosoft ID operators'
FROM public.positions WHERE code = 'kotosoft_id_staff'
ON CONFLICT (position_id, locale) DO NOTHING;
INSERT INTO public.position_translations (position_id, locale, name, description)
SELECT id, 'ru', 'Сотрудник Kotosoft ID', 'Базовая должность сотрудника Kotosoft ID'
FROM public.positions WHERE code = 'kotosoft_id_staff'
ON CONFLICT (position_id, locale) DO NOTHING;
INSERT INTO public.position_translations (position_id, locale, name, description)
SELECT id, 'it', 'Operatore Kotosoft ID', 'Posizione predefinita per operatori Kotosoft ID'
FROM public.positions WHERE code = 'kotosoft_id_staff'
ON CONFLICT (position_id, locale) DO NOTHING;
INSERT INTO public.position_permissions (position_id, permission_id)
SELECT p.id, perm.id
FROM public.positions p
JOIN public.permissions perm
ON perm.code IN ('positions.manage', 'positions.assign', 'positions.revoke')
WHERE p.code = 'kotosoft_id_staff'
ON CONFLICT (position_id, permission_id) DO NOTHING;
+159
View File
@@ -0,0 +1,159 @@
"use server"
import type { CreatedOAuthClient, OAuthClient } from "@/types";
import { getTranslations } from "next-intl/server";
import { cookies } from "next/headers";
import { tryRefresh, clearTokens } from "@/actions/auth";
interface CreateClientPayload {
name: string;
redirect_uris: string[];
grant_types: string[];
scopes: string[];
}
interface UpdateClientPayload {
name: string;
redirect_uris: string[];
scopes: string[];
}
export async function fetchOAuthClients(): Promise<OAuthClient[] | []> {
const store = await cookies();
const accessToken = store.get("access_token")?.value;
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients`, {
headers: { Authorization: `Bearer ${accessToken}` },
cache: "no-store",
});
if (response.status === 401) {
const refreshed = await tryRefresh();
if (!refreshed) {
await clearTokens();
return [];
}
return fetchOAuthClients();
}
if (!response.ok) return [];
return (await response.json()) as OAuthClient[];
} catch {
return [];
}
}
export async function createClient(
payload: CreateClientPayload
): Promise<{ success: boolean; client?: CreatedOAuthClient; message?: string }> {
const t = await getTranslations("errors");
const store = await cookies();
const accessToken = store.get("access_token")?.value;
if (!payload.name || payload.redirect_uris.length === 0) {
return { success: false, message: t("allFieldsRequired") };
}
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients`, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
});
if (response.status === 401) {
const refreshed = await tryRefresh();
if (!refreshed) {
await clearTokens();
return { success: false, message: t("serverError") };
}
return createClient(payload);
}
if (response.status === 400) return { success: false, message: t("invalidInputError") };
if (!response.ok) return { success: false, message: t("serverError") };
const client = (await response.json()) as CreatedOAuthClient;
return { success: true, client };
} catch {
return { success: false, message: t("serverError") };
}
}
export async function updateClient(
id: string,
payload: UpdateClientPayload
): Promise<{ success: boolean; client?: OAuthClient; message?: string }> {
const t = await getTranslations("errors");
const store = await cookies();
const accessToken = store.get("access_token")?.value;
if (!id || !payload.name || payload.redirect_uris.length === 0) {
return { success: false, message: t("allFieldsRequired") };
}
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients/${id}`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
});
if (response.status === 401) {
const refreshed = await tryRefresh();
if (!refreshed) {
await clearTokens();
return { success: false, message: t("serverError") };
}
return updateClient(id, payload);
}
if (response.status === 400) return { success: false, message: t("invalidInputError") };
if (response.status === 404) return { success: false, message: t("notFoundError") };
if (!response.ok) return { success: false, message: t("serverError") };
const client = (await response.json()) as OAuthClient;
return { success: true, client };
} catch {
return { success: false, message: t("serverError") };
}
}
export async function deleteClient(id: string): Promise<{ success: boolean; message?: string }> {
const t = await getTranslations("errors");
const store = await cookies();
const accessToken = store.get("access_token")?.value;
if (!id) return { success: false, message: t("serverError") };
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients/${id}`, {
method: "DELETE",
headers: { Authorization: `Bearer ${accessToken}` },
cache: "no-store",
});
if (response.status === 401) {
const refreshed = await tryRefresh();
if (!refreshed) {
await clearTokens();
return { success: false, message: t("serverError") };
}
return deleteClient(id);
}
if (!response.ok) return { success: false, message: t("serverError") };
return { success: true };
} catch {
return { success: false, message: t("serverError") };
}
}
+8 -8
View File
@@ -3,9 +3,9 @@
import { Consent } from "@/types" import { Consent } from "@/types"
import { cookies } from "next/headers" import { cookies } from "next/headers"
export async function fetchConsents() { export async function fetchConsents(): Promise<Consent[] | []> {
const store = await cookies() const store = await cookies();
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/consents`, `${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/consents`,
@@ -14,16 +14,16 @@ export async function fetchConsents() {
Authorization: `Bearer ${accessToken}`, Authorization: `Bearer ${accessToken}`,
}, },
} }
) );
if (!response.ok) return [] if (!response.ok) return [];
const consents = await response.json() as Consent[] const consents = await response.json() as Consent[];
consents?.forEach((consent: Consent) => { consents?.forEach((consent: Consent) => {
consent.isRevokable = consent.client_id !== process.env.CLIENT_ID consent.isRevokable = consent.client_id !== process.env.CLIENT_ID
}) });
return consents return consents;
} }
export async function revokeConsent(clientId: string) { export async function revokeConsent(clientId: string) {
-266
View File
@@ -1,266 +0,0 @@
"use server"
import type { AdminUser, Permission, Position } from "@/types"
import { cookies } from "next/headers"
async function getAccessToken(): Promise<string | null> {
const store = await cookies()
return store.get("access_token")?.value ?? null
}
async function getAuthHeaders(locale?: string): Promise<HeadersInit> {
const token = await getAccessToken()
return token
? {
Authorization: `Bearer ${token}`,
"Accept-Language": locale ?? "en",
}
: {}
}
async function handleJsonResponse<T>(response: Response): Promise<T | null> {
if (!response.ok) return null
return (await response.json()) as T
}
async function handleSuccessResponse(response: Response): Promise<{ success: boolean }> {
return { success: response.ok }
}
export async function fetchMyPositions(locale?: string): Promise<Position[]> {
const token = await getAccessToken()
if (!token) return []
const res = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/positions`,
{ headers: await getAuthHeaders(locale), cache: "no-store" }
)
return (await handleJsonResponse<Position[]>(res)) ?? []
}
export async function fetchAllPositions(locale?: string): Promise<Position[] | null> {
const token = await getAccessToken()
if (!token) return null
const response = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`,
{ headers: await getAuthHeaders(locale), cache: "no-store" }
)
if (response.status === 403) return null
return await handleJsonResponse<Position[]>(response)
}
export async function savePosition(
code: string,
name: string,
locale: string,
description?: string
): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, {
method: "POST",
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
})
return handleSuccessResponse(res)
}
export async function fetchAllPermissions(locale?: string): Promise<Permission[]> {
const token = await getAccessToken()
if (!token) return []
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, {
headers: await getAuthHeaders(locale),
cache: "no-store",
})
return (await handleJsonResponse<Permission[]>(res)) ?? []
}
export async function fetchAdminUsers(locale?: string): Promise<AdminUser[] | null> {
const token = await getAccessToken()
if (!token) return null
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users`, {
headers: await getAuthHeaders(locale),
cache: "no-store",
})
if (res.status === 403) return []
return await handleJsonResponse<AdminUser[]>(res)
}
export async function addPermission(code: string, description?: string, locale?: string): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, {
method: "POST",
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
body: JSON.stringify({ code, ...(description ? { description } : {}) }),
})
return handleSuccessResponse(res)
}
export async function editPermission(code: string, description?: string, locale?: string): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, {
method: "PUT",
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
body: JSON.stringify({ ...(description ? { description } : {}) }),
})
return handleSuccessResponse(res)
}
export async function removePermission(code: string): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, {
method: "DELETE",
headers: await getAuthHeaders(),
})
return handleSuccessResponse(res)
}
function diffPermissions(oldP: string[], newP: string[]) {
const oldSet = new Set(oldP)
const newSet = new Set(newP)
const toAdd = newP.filter(p => !oldSet.has(p))
const toRemove = oldP.filter(p => !newSet.has(p))
return { toAdd, toRemove }
}
export async function syncPositionPermissions(
positionCode: string,
oldPermissions: string[],
newPermissions: string[]
) {
const { toAdd, toRemove } = diffPermissions(oldPermissions, newPermissions)
await Promise.all([
...toAdd.map(p => attachPermissionToPosition(positionCode, p)),
...toRemove.map(p => detachPermissionFromPosition(positionCode, p)),
])
}
export async function attachPermissionToPosition(
positionCode: string,
permissionCode: string
): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions`,
{
method: "POST",
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
body: JSON.stringify({ permission_code: permissionCode }),
}
)
return handleSuccessResponse(res)
}
export async function detachPermissionFromPosition(
positionCode: string,
permissionCode: string
): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions/${permissionCode}`,
{ method: "DELETE", headers: await getAuthHeaders() }
)
return handleSuccessResponse(res)
}
export async function assignPositionToUser(
userId: string,
positionCode: string,
validFrom?: string,
validTo?: string
): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions`,
{
method: "POST",
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
body: JSON.stringify({
position_code: positionCode,
...(validFrom ? { valid_from: validFrom } : {}),
...(validTo ? { valid_to: validTo } : {}),
}),
}
)
return handleSuccessResponse(res)
}
export async function revokePositionFromUser(userId: string, positionCode: string): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions/${positionCode}`,
{ method: "DELETE", headers: await getAuthHeaders() }
)
return handleSuccessResponse(res)
}
export async function addPosition(code: string, name: string, description?: string, locale?: string): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, {
method: "POST",
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
})
return handleSuccessResponse(res)
}
export async function editPosition(code: string, name: string, description?: string, locale?: string): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${code}`, {
method: "PUT",
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
body: JSON.stringify({ name, ...(description ? { description } : {}) }),
})
return handleSuccessResponse(res)
}
export async function deletePosition(code: string): Promise<{ success: boolean }> {
const token = await getAccessToken()
if (!token) return { success: false }
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${code}`, {
method: "DELETE",
headers: await getAuthHeaders(),
})
return handleSuccessResponse(res)
}
+5 -9
View File
@@ -36,16 +36,12 @@ export default function ConsentPage() {
const handleDecision = async (allow: boolean) => { const handleDecision = async (allow: boolean) => {
setIsSubmitting(true); setIsSubmitting(true);
if (allow) { const result = await Approve(sessionToken, allow);
const result = await Approve(sessionToken, allow); if (result) {
if (result) { window.location.href = result;
window.location.href = result;
} else {
setError(t("invalidSession"));
setIsSubmitting(false);
}
} else { } else {
window.location.href = session?.redirect_uri || "/"; setError(t("invalidSession"));
setIsSubmitting(false);
} }
}; };
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

+5 -1
View File
@@ -35,7 +35,11 @@ export default function LoginPage() {
useEffect(() => { useEffect(() => {
if (redirectTo) { if (redirectTo) {
router.push(redirectTo); if (redirectTo.startsWith("http")) {
window.location.href = redirectTo;
} else {
router.push(redirectTo);
}
} }
}, [redirectTo, router]); }, [redirectTo, router]);
+14 -85
View File
@@ -2,108 +2,37 @@
import Header from "@/components/header"; import Header from "@/components/header";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { useLocale, useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import type { AdminUser, Consent, Permission, Position, User } from "@/types"; import type { Consent, OAuthClient, User } from "@/types";
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, ShieldIcon, UserIcon } from "lucide-react"; import { AppWindowMacIcon, KeyIcon, LogOutIcon, UserIcon } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useEffect, useMemo, useRef, useState } from "react"; import { useMemo, useState } from "react";
import { Logout } from "@/actions/auth"; import { Logout } from "@/actions/auth";
import { fetchAdminUsers, fetchAllPermissions, fetchAllPositions } from "@/actions/positions";
import Profile from "./items/profile"; import Profile from "./items/profile";
import Applications from "./items/applications"; import Consents from "./items/consents";
import Positions from "./items/positions"; import Applications from "./items/applications/applications";
import Admin from "./items/admin";
interface Props { interface Props {
userData: User | null; userData: User | null;
consentsData: Consent[] | null; consentsData: Consent[] | null;
permissionsData: Permission[] | null; clientsData: OAuthClient[] | [];
positionsData: Position[] | null;
adminUsersData: AdminUser[] | null;
canManagePositions: boolean;
canAssignPositions: boolean;
canRevokePositions: boolean;
canAccessAdmin: boolean;
} }
export default function MeClient({ export default function MeClient({ userData, consentsData, clientsData }: Props) {
userData,
consentsData,
permissionsData,
positionsData,
adminUsersData,
canManagePositions,
canAssignPositions,
canRevokePositions,
canAccessAdmin,
}: Props) {
const t = useTranslations("MePage"); const t = useTranslations("MePage");
const locale = useLocale()
const hydratedRef = useRef(false)
const [user, setUser] = useState(userData); const [user, setUser] = useState(userData);
const [consents, setConsents] = useState(consentsData); const [consents, setConsents] = useState(consentsData);
const [permissions, setPermissions] = useState(permissionsData);
const [positions, setPositions] = useState(positionsData);
const [adminUsers, setAdminUsers] = useState(adminUsersData);
const [selectedItem, setSelectedItem] = useState(0); const [selectedItem, setSelectedItem] = useState(0);
const baseItems = useMemo(() => [ const items = useMemo(() => [
{ name: t("items.profile.title"), icon: <UserIcon />, component: <Profile user={user} setUser={setUser} /> }, { name: t("items.profile.title"), icon: <UserIcon />, component: <Profile user={user} setUser={setUser} /> },
{ name: t("items.applications.title"), icon: <AppWindowMacIcon />, component: <Applications consents={consents} setConsents={setConsents} /> }, { name: t("items.consents.title"), icon: <KeyIcon />, component: <Consents consents={consents} setConsents={setConsents} /> },
{ name: t("items.positions.title"), icon: <BriefcaseBusinessIcon />, component: <Positions /> }, ...(user?.is_admin ? [
], [t, user, consents]) { name: t("items.applications.title"), icon: <AppWindowMacIcon />, component: <Applications clientsData={clientsData} /> }
] : [])
const adminItem = useMemo(() => canAccessAdmin ], [t, user, consents, clientsData]);
? [{
name: t("items.admin.title"),
icon: <ShieldIcon />,
component: (
<Admin
permissions={permissions}
setPermissions={setPermissions}
positions={positions}
setPositions={setPositions}
users={adminUsers}
setUsers={setAdminUsers}
canManagePositions={canManagePositions}
canAssignPositions={canAssignPositions}
canRevokePositions={canRevokePositions}
/>
),
}]
: [], [
canAccessAdmin,
t,
permissions,
positions,
adminUsers,
canManagePositions,
canAssignPositions,
canRevokePositions,
]);
const items = useMemo(() => [...baseItems, ...adminItem], [baseItems, adminItem])
useEffect(() => {
if (!hydratedRef.current) {
hydratedRef.current = true
return
}
if (!canAccessAdmin) return
if (canManagePositions) {
fetchAllPermissions(locale).then((data) => setPermissions(data))
}
if (canManagePositions || canAssignPositions || canRevokePositions) {
fetchAllPositions(locale).then((data) => setPositions(data))
}
if (canAssignPositions || canRevokePositions) {
fetchAdminUsers(locale).then((data) => setAdminUsers(data ?? []))
}
}, [locale, canAccessAdmin, canManagePositions, canAssignPositions, canRevokePositions])
return ( return (
<> <>
@@ -1,57 +0,0 @@
"use client"
import { useTranslations } from "next-intl"
import type { AdminUser, Permission, Position } from "@/types"
import Permissions from "./admin/permissions"
import Positions from "./admin/positions";
import UserPositions from "./admin/userPositions";
interface Props {
permissions: Permission[] | null;
setPermissions: React.Dispatch<React.SetStateAction<Permission[] | null>>;
positions: Position[] | null;
setPositions: React.Dispatch<React.SetStateAction<Position[] | null>>;
users: AdminUser[] | null;
setUsers: React.Dispatch<React.SetStateAction<AdminUser[] | null>>;
canManagePositions: boolean;
canAssignPositions: boolean;
canRevokePositions: boolean;
}
export default function Admin({
permissions,
setPermissions,
positions,
setPositions,
users,
setUsers,
canManagePositions,
canAssignPositions,
canRevokePositions,
}: Props) {
const t = useTranslations("MePage.items.admin")
return (
<div className="w-full lg:max-w-xl flex flex-col gap-6">
<h1 className="text-xl">{t("title")}</h1>
<div className="space-y-8">
{canManagePositions && (
<>
<Permissions permissions={permissions} setPermissions={setPermissions} />
<Positions positions={positions} setPositions={setPositions} permissions={permissions} />
</>
)}
{(canAssignPositions || canRevokePositions) && (
<UserPositions
users={users}
setUsers={setUsers}
positions={positions}
canAssignPositions={canAssignPositions}
canRevokePositions={canRevokePositions}
/>
)}
</div>
</div>
)
}
@@ -1,108 +0,0 @@
"use client"
import { useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Spinner } from "@/components/ui/spinner";
import { addPermission, editPermission } from "@/actions/positions";
import { toast } from "sonner";
import { Check, X } from "lucide-react";
import type { Permission } from "@/types";
interface CreateProps {
mode: "create";
trigger: React.ReactNode;
onSuccess: (permission: Permission) => void;
}
interface EditProps {
mode: "edit";
permission: Permission;
trigger: React.ReactNode;
onSuccess: (permission: Permission) => void;
}
type Props = CreateProps | EditProps;
interface FormData {
code: string;
description: string;
}
export function PermissionDialog(props: Props) {
const t = useTranslations("MePage.items.admin.permissions")
const locale = useLocale()
const isEdit = props.mode === "edit"
const [open, setOpen] = useState(false)
const { register, handleSubmit, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
defaultValues: isEdit ? { code: props.permission.code, description: props.permission.description ?? "" } : { code: "", description: "" },
})
function handleOpenChange(o: boolean) {
setOpen(o)
if (!o) reset(isEdit ? { code: props.permission.code, description: props.permission.description ?? "" } : { code: "", description: "" })
}
const onSubmit: SubmitHandler<FormData> = async (data) => {
const result = isEdit
? await editPermission((props as EditProps).permission.code, data.description || undefined, locale)
: await addPermission(data.code, data.description || undefined, locale)
if (!result.success) {
toast(isEdit ? t("edit.error") : t("create.error"), { icon: <X size={16} /> })
return
}
const updated: Permission = isEdit
? { ...(props as EditProps).permission, description: data.description }
: { id: crypto.randomUUID(), code: data.code, name: data.code, description: data.description, created_at: new Date().toISOString() }
toast(isEdit ? t("edit.success") : t("create.success"), { icon: <Check size={16} /> })
props.onSuccess(updated)
reset()
setOpen(false)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>{props.trigger}</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{isEdit ? t("edit.title") : t("create.title")}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<Field data-invalid={!!errors.code}>
<FieldLabel htmlFor="code">{isEdit ? t("edit.code") : t("create.code")}</FieldLabel>
<Input
id="code"
disabled={isEdit || isSubmitting}
aria-invalid={!!errors.code}
{...register("code", { validate: (v) => isEdit || v.trim().length > 0 || t("create.codeRequired") })}
/>
{errors.code && <FieldError>{errors.code.message}</FieldError>}
</Field>
<Field>
<FieldLabel htmlFor="description">{isEdit ? t("edit.description") : t("create.description")}</FieldLabel>
<Input id="description" disabled={isSubmitting} {...register("description")} />
</Field>
</FieldGroup>
<DialogFooter className="mt-4">
<DialogClose asChild>
<Button variant="outline" type="button">{isEdit ? t("edit.cancel") : t("create.cancel")}</Button>
</DialogClose>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner />}
{isEdit ? t("edit.save") : t("create.save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
@@ -1,201 +0,0 @@
"use client"
import { useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Spinner } from "@/components/ui/spinner";
import { addPosition, editPosition, syncPositionPermissions } from "@/actions/positions";
import { toast } from "sonner";
import { Check, X } from "lucide-react";
import type { Permission, Position } from "@/types";
interface CreateProps {
mode: "create";
trigger: React.ReactNode;
onSuccess: (position: Position) => void;
allPermissions: Permission[] | null;
}
interface EditProps {
mode: "edit";
position: Position;
trigger: React.ReactNode;
onSuccess: (position: Position) => void;
allPermissions: Permission[] | null;
}
type Props = CreateProps | EditProps;
interface FormData {
code: string;
name: string;
description: string;
permissions: string[];
}
function addPermissionToForm(current: string[], value: string): string[] {
if (current.includes(value)) return current
return [...current, value]
}
function removePermissionFromForm(current: string[], value: string): string[] {
return current.filter(p => p !== value)
}
function togglePermissionInForm(current: string[], value: string): string[] {
return current.includes(value) ?
removePermissionFromForm(current, value) :
addPermissionToForm(current, value)
}
export function PositionDialog(props: Props) {
const t = useTranslations("MePage.items.admin.positions")
const locale = useLocale()
const isEdit = props.mode === "edit"
const [open, setOpen] = useState(false)
const { register, handleSubmit, reset, formState: { errors, isSubmitting }, watch, setValue } = useForm<FormData>({
defaultValues: isEdit
? { code: props.position.code, name: props.position.name, description: props.position.description ?? "", permissions: props.position.permissions.map(p => p.code) ?? [] }
: { code: "", name: "", description: "", permissions: [] },
})
function handleOpenChange(o: boolean) {
setOpen(o)
if (!o) {
reset(isEdit
? { code: props.position.code, name: props.position.name, description: props.position.description ?? "", permissions: props.position.permissions.map(p => p.code) ?? [] }
: { code: "", name: "", description: "", permissions: [] }
)
}
}
const onSubmit: SubmitHandler<FormData> = async (data) => {
const positionCode = isEdit
? (props as EditProps).position.code
: data.code
const oldPermissions = isEdit
? (props as EditProps).position.permissions.map(p => p.code)
: []
const result = isEdit
? await editPosition(positionCode, data.name, data.description, locale)
: await addPosition(data.code, data.name, data.description, locale)
if (!result.success) {
toast(isEdit ? t("edit.error") : t("create.error"), {
icon: <X size={16} />,
})
return
}
await syncPositionPermissions(
positionCode,
oldPermissions,
data.permissions
)
const nextPermissions = data.permissions.map((permissionCode) => {
const permission = props.allPermissions?.find((p) => p.code === permissionCode)
return permission ?? { id: permissionCode, code: permissionCode, name: permissionCode, description: permissionCode, created_at: new Date().toISOString() }
})
const updated: Position = {
...(isEdit ? (props as EditProps).position : { code: data.code }),
name: data.name,
description: data.description,
permissions: nextPermissions,
}
toast(isEdit ? t("edit.success") : t("create.success"), {
icon: <Check size={16} />,
})
props.onSuccess(updated)
reset()
setOpen(false)
}
const selectedPermissions = watch("permissions");
const togglePermission = (value: string) => {
const updated = togglePermissionInForm(selectedPermissions, value)
setValue("permissions", updated, { shouldDirty: true, shouldValidate: true })
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>{props.trigger}</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{isEdit ? t("edit.title") : t("create.title")}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<Field data-invalid={!!errors.code}>
<FieldLabel htmlFor="code">{isEdit ? t("edit.code") : t("create.code")}</FieldLabel>
<Input
id="code"
disabled={isEdit || isSubmitting}
aria-invalid={!!errors.code}
{...register("code", { validate: (v) => isEdit || v.trim().length > 0 || t("create.codeRequired") })}
/>
{errors.code && <FieldError>{errors.code.message}</FieldError>}
</Field>
<Field data-invalid={!!errors.name}>
<FieldLabel htmlFor="name">{isEdit ? t("edit.name") : t("create.name")}</FieldLabel>
<Input
id="name"
disabled={isSubmitting}
aria-invalid={!!errors.name}
{...register("name", { validate: (v) => v.trim().length > 0 || t("create.nameRequired") })}
/>
{errors.name && <FieldError>{errors.name.message}</FieldError>}
</Field>
<Field>
<FieldLabel htmlFor="description">{isEdit ? t("edit.description") : t("create.description")}</FieldLabel>
<Input
id="description"
disabled={isSubmitting}
{...register("description")}
/>
</Field>
<Field>
<FieldLabel htmlFor="permissions">{t("permissions.label")}</FieldLabel>
<div className="flex flex-wrap gap-2">
{props.allPermissions?.length == 0 && <p className="text-sm text-muted-foreground">{t("permissions.empty")}</p>}
{props.allPermissions?.map((p) => {
const active = selectedPermissions.includes(p.code)
return (
<Button
key={p.id}
variant={active ? "default" : "ghost"}
onClick={(e) => {e.preventDefault(); togglePermission(p.code)}}
>
{p.description || p.name || p.code}
</Button>
)
})}
</div>
</Field>
</FieldGroup>
<DialogFooter className="mt-6">
<DialogClose asChild>
<Button variant="outline">{isEdit ? t("edit.cancel") : t("create.cancel")}</Button>
</DialogClose>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner className="mr-2 size-4" />}
{isEdit ? t("edit.save") : t("create.save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
@@ -1,95 +0,0 @@
"use client"
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { MoreHorizontalIcon } from "lucide-react";
import { Check, X } from "lucide-react";
import { toast } from "sonner";
import { PermissionDialog } from "./dialogs/permissionDialog";
import { removePermission } from "@/actions/positions";
import type { Permission } from "@/types";
interface Props {
permissions: Permission[] | null;
setPermissions: React.Dispatch<React.SetStateAction<Permission[] | null>>;
}
export default function Permissions({ permissions, setPermissions }: Props) {
const t = useTranslations("MePage.items.admin.permissions")
function handleCreated(permission: Permission) {
setPermissions((prev) => [...(prev || []), permission])
}
function handleUpdated(code: string, permission: Permission) {
setPermissions((prev) => (prev || []).map((p) => (p.code === code ? permission : p)))
}
async function handleDelete(code: string) {
const result = await removePermission(code)
if (result.success) {
setPermissions((prev) => (prev || []).filter((p) => p.code !== code))
toast(t("delete.success"), { icon: <Check size={16} /> })
} else {
toast(t("delete.error"), { icon: <X size={16} /> })
}
}
return (
<div className="space-y-4">
<div className="space-y-1">
<h2 className="text-lg">{t("title")}</h2>
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
</div>
<Table>
<TableHeader className="rounded-lg">
<TableRow>
<TableHead>{t("columns.code")}</TableHead>
<TableHead>{t("columns.description")}</TableHead>
<TableHead className="text-right">{t("columns.actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{permissions?.length === 0 && (
<TableRow>
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
</TableRow>
)}
{permissions?.map((permission) => (
<TableRow key={permission.code}>
<TableCell className="font-mono">{permission.code}</TableCell>
<TableCell className="text-muted-foreground">{permission.description || permission.name || permission.code}</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8">
<MoreHorizontalIcon />
<span className="sr-only">{t("columns.actions")}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<PermissionDialog
mode="edit"
permission={permission}
onSuccess={(updated) => handleUpdated(permission.code, updated)}
trigger={<Button variant="ghost" size="sm" className="w-full px-2 justify-start">{t("actions.edit")}</Button>}
/>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(permission.code)}>{t("actions.delete")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<PermissionDialog
mode="create"
onSuccess={handleCreated}
trigger={<Button variant="outline" size="sm" className="w-full">{t("actions.create")}</Button>}
/>
</div>
)
}
@@ -1,100 +0,0 @@
"use client"
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { MoreHorizontalIcon } from "lucide-react";
import { Check, X } from "lucide-react";
import { toast } from "sonner";
import { PositionDialog } from "./dialogs/positionDialog";
import { deletePosition } from "@/actions/positions";
import type { Permission, Position } from "@/types";
interface Props {
positions: Position[] | null;
permissions: Permission[] | null;
setPositions: React.Dispatch<React.SetStateAction<Position[] | null>>;
}
export default function Positions({ positions, permissions, setPositions }: Props) {
const t = useTranslations("MePage.items.admin.positions")
function handleCreated(position: Position) {
setPositions((prev) => [...(prev || []), position])
}
function handleUpdated(code: string, position: Position) {
setPositions((prev) => (prev || []).map((p) => (p.code === code ? position : p)))
}
async function handleDelete(code: string) {
const result = await deletePosition(code)
if (result.success) {
setPositions((prev) => (prev || []).filter((p) => p.code !== code))
toast(t("delete.success"), { icon: <Check size={16} /> })
} else {
toast(t("delete.error"), { icon: <X size={16} /> })
}
}
return (
<div className="space-y-4">
<div className="space-y-1">
<h2 className="text-lg">{t("title")}</h2>
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
</div>
<Table>
<TableHeader className="rounded-lg">
<TableRow>
<TableHead>{t("columns.code")}</TableHead>
<TableHead>{t("columns.name")}</TableHead>
<TableHead>{t("columns.description")}</TableHead>
<TableHead className="text-right">{t("columns.actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{positions?.length === 0 && (
<TableRow>
<TableCell colSpan={4} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
</TableRow>
)}
{positions?.map((position) => (
<TableRow key={position.code}>
<TableCell className="font-mono">{position.code}</TableCell>
<TableCell>{position.name}</TableCell>
<TableCell className="text-muted-foreground">{position.description || t("noDescription")}</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8">
<MoreHorizontalIcon />
<span className="sr-only">{t("columns.actions")}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<PositionDialog
mode="edit"
position={position}
onSuccess={(updated) => handleUpdated(position.code, updated)}
trigger={<Button variant="ghost" size="sm" className="w-full px-2 justify-start">{t("actions.edit")}</Button>}
allPermissions={permissions}
/>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(position.code)}>{t("actions.delete")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<PositionDialog
mode="create"
onSuccess={handleCreated}
trigger={<Button variant="outline" size="sm" className="w-full">{t("actions.create")}</Button>}
allPermissions={permissions}
/>
</div>
)
}
@@ -1,143 +0,0 @@
"use client"
import { assignPositionToUser, revokePositionFromUser } from "@/actions/positions";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { AdminUser, Position } from "@/types";
import { Check, MoreHorizontalIcon, X } from "lucide-react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
interface Props {
users: AdminUser[] | null;
setUsers: React.Dispatch<React.SetStateAction<AdminUser[] | null>>;
positions: Position[] | null;
canAssignPositions: boolean;
canRevokePositions: boolean;
}
export default function UserPositions({
users,
setUsers,
positions,
canAssignPositions,
canRevokePositions,
}: Props) {
const t = useTranslations("MePage.items.admin.userPositions")
async function handleAssign(userId: string, positionCode: string) {
const result = await assignPositionToUser(userId, positionCode)
if (!result.success) {
toast(t("assign.error"), { icon: <X size={16} /> })
return
}
const added = positions?.find((p) => p.code === positionCode)
if (added) {
setUsers((prev) => (prev || []).map((u) => {
if (u.id !== userId) return u
if (u.positions.some((p) => p.code === positionCode)) return u
return { ...u, positions: [...u.positions, added] }
}))
}
toast(t("assign.success"), { icon: <Check size={16} /> })
}
async function handleRevoke(userId: string, positionCode: string) {
const result = await revokePositionFromUser(userId, positionCode)
if (!result.success) {
toast(t("revoke.error"), { icon: <X size={16} /> })
return
}
setUsers((prev) => (prev || []).map((u) => (
u.id === userId
? { ...u, positions: u.positions.filter((p) => p.code !== positionCode) }
: u
)))
toast(t("revoke.success"), { icon: <Check size={16} /> })
}
return (
<div className="space-y-4">
<div className="space-y-1">
<h2 className="text-lg">{t("title")}</h2>
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
</div>
<Table>
<TableHeader className="rounded-lg">
<TableRow>
<TableHead>{t("columns.user")}</TableHead>
<TableHead>{t("columns.positions")}</TableHead>
<TableHead className="text-right">{t("columns.actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users === null && (
<TableRow>
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("loadError")}</TableCell>
</TableRow>
)}
{users?.length === 0 && (
<TableRow>
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
</TableRow>
)}
{users?.map((user) => (
<TableRow key={user.id}>
<TableCell>
<div className="flex flex-col">
<span>{user.first_name} {user.second_name}</span>
<span className="text-xs text-muted-foreground">{user.email}</span>
</div>
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1">
{user.positions.length === 0 && <span className="text-sm text-muted-foreground">{t("noPositions")}</span>}
{user.positions.map((position) => (
<Badge key={position.code} variant="secondary">{position.name || position.code}</Badge>
))}
</div>
</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8">
<MoreHorizontalIcon />
<span className="sr-only">{t("columns.actions")}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{canAssignPositions && (positions || []).map((position) => (
<DropdownMenuItem
key={`assign-${user.id}-${position.code}`}
disabled={user.positions.some((p) => p.code === position.code)}
onClick={() => handleAssign(user.id, position.code)}
>
{t("actions.assign")} {position.name}
</DropdownMenuItem>
))}
{canAssignPositions && (user.positions.filter(p => p.code !== "kotosoft_id_staff")).length > 0 && canRevokePositions && <DropdownMenuSeparator />}
{canRevokePositions && user.positions.filter(p => p.code !== "kotosoft_id_staff").map((position) => (
<DropdownMenuItem
key={`revoke-${user.id}-${position.code}`}
variant="destructive"
onClick={() => handleRevoke(user.id, position.code)}
>
{t("actions.revoke")} {position.name}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)
}
@@ -0,0 +1,34 @@
"use client"
import { useTranslations } from "next-intl";
import type { OAuthClient } from "@/types";
import { useState } from "react";
import { DataTable } from "./table";
import { useColumns } from "./columns";
import { CreateClientDialog } from "./createClientDialog";
import { UpdateClientDialog } from "./updateClientDialog";
interface Props {
clientsData: OAuthClient[];
}
export default function Applications({ clientsData }: Props) {
const t = useTranslations("MePage.items.applications");
const [editingClient, setEditingClient] = useState<OAuthClient | null>(null);
const [clients, setClients] = useState<OAuthClient[] | []>(clientsData);
const columns = useColumns({ setClients, setEditingClient });
return (
<div className="w-full lg:max-w-2xl flex flex-col gap-8">
<div className="lg:max-w-sm space-y-2">
<h1 className="text-xl">{t("title")}</h1>
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
</div>
<CreateClientDialog setClients={setClients} />
<UpdateClientDialog client={editingClient} onClose={() => setEditingClient(null)} setClients={setClients} />
<div className="space-y-4">
{clients.length > 0 ? <DataTable columns={columns} data={clients || []} /> : <h2 className="text-muted-foreground text-lg">{t("noApplications")}</h2>}
</div>
</div>
);
}
@@ -0,0 +1,94 @@
"use client"
import { createColumnHelper } from "@tanstack/react-table";
import { Dispatch, SetStateAction, useMemo } from "react";
import { type DataTableFeatures } from "./features";
import { OAuthClient } from "@/types";
import { Badge } from "@/components/ui/badge";
import { useTranslations } from "next-intl";
import { BanIcon, MoreHorizontal, PencilIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { deleteClient } from "@/actions/clients";
const columnHelper = createColumnHelper<DataTableFeatures, OAuthClient>();
async function handleDisable({ id, setClients }: { id: string; setClients: Dispatch<SetStateAction<OAuthClient[] | []>> }) {
try {
await deleteClient(id);
setClients((prev) => prev ? prev.map((c) => c.id === id ? { ...c, is_active: false } : c) : prev);
} catch {}
}
export function useColumns({ setClients, setEditingClient }: { setClients: Dispatch<SetStateAction<OAuthClient[] | []>>; setEditingClient: Dispatch<SetStateAction<OAuthClient | null>>; }) {
const t = useTranslations("MePage.items.applications.table");
return useMemo(
() =>
columnHelper.columns([
columnHelper.accessor("name", {
header: t("client"),
cell: ({ row }) => (
<div className="flex flex-col gap-0.5">
<h4>{row.getValue("name")}</h4>
<h5 className="text-xs text-muted-foreground">
{row.original.client_id}
</h5>
</div>
),
}),
columnHelper.accessor("redirect_uris", {
header: t("redirectURIs"),
cell: ({ row }) => (
<div className="flex flex-row gap-1 flex-wrap">
{(row.getValue("redirect_uris") as string[]).map((url) => (
<Badge key={url} variant="secondary">
{url}
</Badge>
))}
</div>
),
}),
columnHelper.accessor("scopes", {
header: t("scopes"),
cell: ({ row }) => (
<div className="flex flex-row gap-1 flex-wrap">
{(row.getValue("scopes") as string[]).map((scope) => (
<Badge key={scope} variant="secondary">
{scope}
</Badge>
))}
</div>
),
}),
columnHelper.accessor("is_active", {
header: t("status"),
cell: ({ row }) => {
return row.getValue("is_active") === true ? t("active") : t("disabled")
},
}),
columnHelper.display({
id: "actions",
cell: ({ row }) => {
const client = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setEditingClient(client)}><PencilIcon />{t("edit")}</DropdownMenuItem>
{client.is_active && <DropdownMenuItem onClick={() => handleDisable({ id: client.id, setClients })}><BanIcon />{t("disable")}</DropdownMenuItem>}
</DropdownMenuContent>
</DropdownMenu>
)
},
}),
]),
[t, setClients, setEditingClient]
)
}
@@ -0,0 +1,256 @@
"use client"
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldError, FieldGroup, FieldLabel, FieldDescription } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useTranslations } from "next-intl";
import { Dispatch, SetStateAction, useState } from "react";
import { useFieldArray, useForm, Controller, SubmitHandler } from "react-hook-form";
import { Plus, Trash2, Copy, Check } from "lucide-react";
import { createClient } from "@/actions/clients";
import type { CreatedOAuthClient, OAuthClient } from "@/types";
interface FormData {
name: string;
redirect_uris: { value: string }[];
scopes: string[];
}
interface Props {
setClients: Dispatch<SetStateAction<OAuthClient[] | []>>;
}
const GRANT_TYPES = ["authorization_code", "refresh_token"] as const;
const SCOPES = ["profile:read", "profile:edit"] as const;
export function CreateClientDialog({ setClients }: Props) {
const t = useTranslations("MePage.items.applications.dialog");
const [isOpen, setIsOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const [createdClient, setCreatedClient] = useState<CreatedOAuthClient | null>(null);
const [copied, setCopied] = useState<"id" | "secret" | null>(null);
const { register, handleSubmit, control, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
defaultValues: {
name: "",
redirect_uris: [{ value: "" }],
scopes: [],
},
});
const { fields, append, remove } = useFieldArray({
control,
name: "redirect_uris",
});
const onSubmit: SubmitHandler<FormData> = async (data) => {
setError(null);
const result = await createClient({
name: data.name,
redirect_uris: data.redirect_uris.map((r) => r.value).filter(Boolean),
grant_types: [...GRANT_TYPES],
scopes: data.scopes,
});
if (!result.success || !result.client) {
setError(result.message ?? null);
return;
}
setClients((prev) => (prev ? [...prev, result.client!] : [result.client!]));
setCreatedClient(result.client);
};
const handleCopy = async (value: string, key: "id" | "secret") => {
await navigator.clipboard.writeText(value);
setCopied(key);
setTimeout(() => setCopied(null), 2000);
};
const handleClose = (open: boolean) => {
setIsOpen(open);
if (!open) {
reset();
setCreatedClient(null);
setError(null);
}
};
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
<DialogTrigger asChild>
<Button className="w-max">{t("trigger")}</Button>
</DialogTrigger>
<DialogContent onInteractOutside={(e) => createdClient && e.preventDefault()}>
{!createdClient ? (
<>
<DialogHeader>
<DialogTitle>{t("title")}</DialogTitle>
<DialogDescription>{t("subtitle")}</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<Field data-invalid={!!errors.name}>
<FieldLabel htmlFor="name">{t("name.title")}</FieldLabel>
<Input
id="name"
disabled={isSubmitting}
aria-invalid={!!errors.name}
{...register("name", {
required: t("required"),
minLength: { value: 2, message: t("name.minLength") },
maxLength: { value: 128, message: t("name.maxLength") },
})}
/>
{errors.name && <FieldError>{errors.name.message}</FieldError>}
</Field>
<Field>
<FieldLabel>{t("redirectUris.title")}</FieldLabel>
<div className="flex flex-col gap-2">
{fields.map((field, index) => (
<div key={field.id} className="flex gap-2">
<Input
disabled={isSubmitting}
placeholder={t("redirectUris.placeholder")}
{...register(`redirect_uris.${index}.value` as const, {
required: index === 0 ? t("required") : false,
pattern: {
value: /^https?:\/\/.+/,
message: t("redirectUris.invalid"),
},
})}
/>
<Button
type="button"
variant="outline"
size="icon"
disabled={isSubmitting || fields.length === 1}
onClick={() => remove(index)}
>
<Trash2 />
</Button>
</div>
))}
{errors.redirect_uris?.[0]?.value && (
<FieldError>{errors.redirect_uris[0]?.value?.message}</FieldError>
)}
<Button
type="button"
variant="outline"
size="sm"
disabled={isSubmitting}
onClick={() => append({ value: "" })}
>
<Plus />
{t("redirectUris.add")}
</Button>
</div>
</Field>
<Field data-invalid={!!errors.scopes}>
<FieldLabel>{t("scopes.title")}</FieldLabel>
<Controller
name="scopes"
control={control}
rules={{ required: t("required") }}
render={({ field }) => (
<div className="flex flex-col gap-2">
{SCOPES.map((scope) => (
<label key={scope} className="flex items-center gap-2 text-sm">
<Checkbox
disabled={isSubmitting}
checked={field.value.includes(scope)}
onCheckedChange={(checked) => {
field.onChange(
checked
? [...field.value, scope]
: field.value.filter((s) => s !== scope)
);
}}
/>
{t(`scopes.${scope}`)}
</label>
))}
</div>
)}
/>
{errors.scopes && <FieldError>{errors.scopes.message}</FieldError>}
</Field>
{error && <FieldError className="text-center">{error}</FieldError>}
</FieldGroup>
<DialogFooter className="mt-6">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner />}
{t("submit")}
</Button>
</DialogFooter>
</form>
</>
) : (
<>
<DialogHeader>
<DialogTitle>{t("secretReveal.title")}</DialogTitle>
<DialogDescription>{t("secretReveal.subtitle")}</DialogDescription>
</DialogHeader>
<FieldGroup>
<Field>
<FieldLabel>{t("secretReveal.clientId")}</FieldLabel>
<div className="flex gap-2">
<Input readOnly value={createdClient.client_id} className="font-mono text-sm" />
<Button
type="button"
variant="outline"
size="icon"
onClick={() => handleCopy(createdClient.client_id, "id")}
>
{copied === "id" ? <Check /> : <Copy />}
</Button>
</div>
</Field>
<Field>
<FieldLabel>{t("secretReveal.clientSecret")}</FieldLabel>
<div className="flex gap-2">
<Input readOnly value={createdClient.client_secret} className="font-mono text-sm" />
<Button
type="button"
variant="outline"
size="icon"
onClick={() => handleCopy(createdClient.client_secret, "secret")}
>
{copied === "secret" ? <Check /> : <Copy />}
</Button>
</div>
<FieldDescription className="text-destructive">
{t("secretReveal.warning")}
</FieldDescription>
</Field>
</FieldGroup>
<DialogFooter className="mt-6">
<Button onClick={() => handleClose(false)}>
{t("secretReveal.confirm")}
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,29 @@
import {
columnFilteringFeature,
columnVisibilityFeature,
createFilteredRowModel,
createPaginatedRowModel,
createSortedRowModel,
filterFn_includesString,
rowPaginationFeature,
rowSelectionFeature,
rowSortingFeature,
sortFn_alphanumeric,
sortFn_text,
tableFeatures,
} from "@tanstack/react-table";
export const features = tableFeatures({
columnFilteringFeature,
columnVisibilityFeature,
rowPaginationFeature,
rowSelectionFeature,
rowSortingFeature,
filteredRowModel: createFilteredRowModel(),
paginatedRowModel: createPaginatedRowModel(),
sortedRowModel: createSortedRowModel(),
filterFns: { includesString: filterFn_includesString },
sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text },
});
export type DataTableFeatures = typeof features;
@@ -0,0 +1,49 @@
"use client"
import { useTable, type ColumnDef, type RowData } from "@tanstack/react-table";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { features, type DataTableFeatures } from "./features";
interface DataTableProps<TData extends RowData> {
columns: ColumnDef<DataTableFeatures, TData>[];
data: TData[];
}
export function DataTable<TData extends RowData>({ columns, data }: DataTableProps<TData>) {
const table = useTable({ features, data, columns });
return (
<div className="overflow-hidden rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder ? null : (
<table.FlexRender header={header} />
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length > 0 && (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
<table.FlexRender cell={cell} />
</TableCell>
))}
</TableRow>
))
)}
</TableBody>
</Table>
</div>
)
}
@@ -0,0 +1,186 @@
"use client"
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useTranslations } from "next-intl";
import { useFieldArray, useForm, Controller, SubmitHandler } from "react-hook-form";
import { Plus, Trash2 } from "lucide-react";
import { updateClient } from "@/actions/clients";
import type { OAuthClient } from "@/types";
interface FormData {
name: string;
redirect_uris: { value: string }[];
scopes: string[];
}
interface Props {
client: OAuthClient | null;
onClose: () => void;
setClients: Dispatch<SetStateAction<OAuthClient[] | []>>;
}
const SCOPES = ["profile:read", "profile:edit"] as const;
export function UpdateClientDialog({ client, onClose, setClients }: Props) {
const t = useTranslations("MePage.items.applications.dialog");
const [error, setError] = useState<string | null>(null);
const { register, handleSubmit, control, reset, formState: { errors, isSubmitting }} = useForm<FormData>({
defaultValues: { name: "", redirect_uris: [{ value: "" }], scopes: [] },
});
const { fields, append, remove } = useFieldArray({
control,
name: "redirect_uris",
});
useEffect(() => {
if (client) {
reset({
name: client.name,
redirect_uris: client.redirect_uris.map((value) => ({ value })),
scopes: client.scopes,
});
}
}, [client, reset]);
const onSubmit: SubmitHandler<FormData> = async (data) => {
if (!client) return;
setError(null);
const result = await updateClient(client.id, {
name: data.name,
redirect_uris: data.redirect_uris.map((r) => r.value).filter(Boolean),
scopes: data.scopes,
});
if (!result.success || !result.client) {
setError(result.message ?? null);
return;
}
setClients((prev) =>
prev ? prev.map((c) => (c.id === result.client!.id ? result.client! : c)) : prev
);
onClose();
};
return (
<Dialog open={!!client} onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("editTitle")}</DialogTitle>
<DialogDescription>{t("editSubtitle")}</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<Field data-invalid={!!errors.name}>
<FieldLabel htmlFor="name">{t("name.title")}</FieldLabel>
<Input
id="name"
disabled={isSubmitting}
aria-invalid={!!errors.name}
{...register("name", {
required: t("required"),
minLength: { value: 2, message: t("name.minLength") },
maxLength: { value: 128, message: t("name.maxLength") },
})}
/>
{errors.name && <FieldError>{errors.name.message}</FieldError>}
</Field>
<Field>
<FieldLabel>{t("redirectUris.title")}</FieldLabel>
<div className="flex flex-col gap-2">
{fields.map((field, index) => (
<div key={field.id} className="flex gap-2">
<Input
disabled={isSubmitting}
placeholder={t("redirectUris.placeholder")}
{...register(`redirect_uris.${index}.value` as const, {
required: index === 0 ? t("required") : false,
pattern: { value: /^https?:\/\/.+/, message: t("redirectUris.invalid") },
})}
/>
<Button
type="button"
variant="outline"
size="icon"
disabled={isSubmitting || fields.length === 1}
onClick={() => remove(index)}
>
<Trash2 />
</Button>
</div>
))}
{errors.redirect_uris?.[0]?.value && (
<FieldError>{errors.redirect_uris[0]?.value?.message}</FieldError>
)}
<Button
type="button"
variant="outline"
size="sm"
disabled={isSubmitting}
onClick={() => append({ value: "" })}
>
<Plus />
{t("redirectUris.add")}
</Button>
</div>
</Field>
<Field data-invalid={!!errors.scopes}>
<FieldLabel>{t("scopes.title")}</FieldLabel>
<Controller
name="scopes"
control={control}
rules={{ required: t("required") }}
render={({ field }) => (
<div className="flex flex-col gap-2">
{SCOPES.map((scope) => (
<label key={scope} className="flex items-center gap-2 text-sm">
<Checkbox
disabled={isSubmitting}
checked={field.value.includes(scope)}
onCheckedChange={(checked) => {
field.onChange(
checked ? [...field.value, scope] : field.value.filter((s) => s !== scope)
);
}}
/>
{t(`scopes.${scope}`)}
</label>
))}
</div>
)}
/>
{errors.scopes && <FieldError>{errors.scopes.message}</FieldError>}
</Field>
{error && <FieldError className="text-center">{error}</FieldError>}
</FieldGroup>
<DialogFooter className="mt-6">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner />}
{t("editSubmit")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -18,8 +18,8 @@ interface Props {
setConsents: (consents: Consent[]) => void; setConsents: (consents: Consent[]) => void;
} }
export default function Applications({ consents, setConsents }: Props) { export default function Consents({ consents, setConsents }: Props) {
const t = useTranslations("MePage.items.applications"); const t = useTranslations("MePage.items.consents");
const [list, setList] = useState(consents); const [list, setList] = useState(consents);
const [revokingId, setRevokingId] = useState<string | null>(null); const [revokingId, setRevokingId] = useState<string | null>(null);
@@ -1,72 +0,0 @@
"use client"
import { useEffect, useState } from "react"
import { useLocale, useTranslations } from "next-intl"
import type { Position } from "@/types"
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"
import { Badge } from "@/components/ui/badge"
import { Spinner } from "@/components/ui/spinner"
import { fetchMyPositions } from "@/actions/positions"
const positionsCache: Record<string, Position[]> = {}
export default function Positions() {
const t = useTranslations("MePage.items.positions")
const locale = useLocale()
const [positions, setPositions] = useState<Position[] | null>(
() => positionsCache[locale] ?? null
)
const [loading, setLoading] = useState(!positionsCache[locale])
useEffect(() => {
if (positionsCache[locale]) return
fetchMyPositions(locale)
.then((data) => {
positionsCache[locale] = data
setPositions(data)
})
.finally(() => setLoading(false))
}, [locale])
return (
<div className="w-full lg:max-w-sm flex flex-col gap-4">
<h1 className="text-xl">{t("title")}</h1>
{loading && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Spinner />
<span>{t("loading")}</span>
</div>
)}
{!loading && (
<div className="space-y-4">
{positions && positions.length > 0 ? (
positions.map((position) => (
<Item key={position.code}>
<ItemContent>
<ItemTitle>{position.name}</ItemTitle>
{position.description && (
<ItemDescription>{position.description}</ItemDescription>
)}
{position.permissions.length > 0 && (
<div className="flex flex-wrap gap-1 mt-2">
{position.permissions.map((perm) => (
<Badge key={perm.code} variant="secondary" className="text-xs">
{perm.description}
</Badge>
))}
</div>
)}
</ItemContent>
</Item>
))
) : (
<p className="text-sm text-muted-foreground">{t("empty")}</p>
)}
</div>
)}
</div>
)
}
+5 -23
View File
@@ -1,45 +1,27 @@
import { fetchUser } from "@/actions/auth"; import { fetchUser } from "@/actions/auth";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import MeComponent from "./component"; import MeComponent from "./component";
import { fetchConsents } from "@/actions/consents"; import { fetchConsents } from "@/actions/consents";
import { fetchAllPositions, fetchAllPermissions, fetchAdminUsers, fetchMyPositions } from "@/actions/positions"; import { fetchOAuthClients } from "@/actions/clients";
import { getLocale } from "next-intl/server";
export default async function Me() { export default async function Me() {
const locale = await getLocale();
const user = await fetchUser(); const user = await fetchUser();
if (!user) { if (!user) {
redirect("/api/auth/initiate"); redirect("/api/auth/initiate");
} }
const [consents, myPositions] = await Promise.all([ const [consents, clients] = await Promise.all([
fetchConsents(), fetchConsents(),
fetchMyPositions(locale), fetchOAuthClients(),
]);
const granted = new Set(myPositions.flatMap((position) => position.permissions.map((p) => p.code)));
const canManage = granted.has("positions.manage");
const canAssign = granted.has("positions.assign");
const canRevoke = granted.has("positions.revoke");
const canAccessAdmin = canManage || canAssign || canRevoke;
const [permissions, positions, adminUsers] = await Promise.all([
canAccessAdmin && canManage ? fetchAllPermissions(locale) : Promise.resolve<null>(null),
canAccessAdmin && (canManage || canAssign || canRevoke) ? fetchAllPositions(locale) : Promise.resolve<null>(null),
canAccessAdmin && (canAssign || canRevoke) ? fetchAdminUsers(locale).then((data) => data ?? []) : Promise.resolve<null>(null),
]); ]);
return ( return (
<MeComponent <MeComponent
userData={user} userData={user}
consentsData={consents} consentsData={consents}
permissionsData={permissions} clientsData={clients}
positionsData={positions}
adminUsersData={adminUsers}
canManagePositions={canManage}
canAssignPositions={canAssign}
canRevokePositions={canRevoke}
canAccessAdmin={canAccessAdmin}
/> />
); );
} }
+24 -10
View File
@@ -5,30 +5,32 @@
"": { "": {
"name": "kotosoft-id-frontend", "name": "kotosoft-id-frontend",
"dependencies": { "dependencies": {
"@tanstack/react-table": "^9.2.4",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"date-fns": "^4.1.0", "cn": "^0.3.0",
"date-fns": "^4.4.0",
"lucide-react": "^0.575.0", "lucide-react": "^0.575.0",
"next": "^16.2.3", "next": "^16.2.9",
"next-intl": "^4.9.1", "next-intl": "^4.13.0",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"radix-ui": "^1.4.3", "radix-ui": "^1.5.0",
"react": "19.2.3", "react": "19.2.3",
"react-day-picker": "^9.14.0", "react-day-picker": "^9.14.0",
"react-dom": "19.2.3", "react-dom": "19.2.3",
"react-hook-form": "^7.72.1", "react-hook-form": "^7.78.0",
"sonner": "^2.0.7", "sonner": "^2.0.7",
"tailwind-merge": "^3.5.0", "tailwind-merge": "^3.6.0",
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.2.2", "@tailwindcss/postcss": "^4.3.0",
"@types/node": "^20.19.39", "@types/node": "^20.19.42",
"@types/react": "^19.2.14", "@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"eslint": "^9.39.4", "eslint": "^9.39.4",
"eslint-config-next": "16.1.6", "eslint-config-next": "16.1.6",
"shadcn": "^3.8.5", "shadcn": "^3.8.5",
"tailwindcss": "^4.2.2", "tailwindcss": "^4.3.0",
"tw-animate-css": "^1.4.0", "tw-animate-css": "^1.4.0",
"typescript": "^5.9.3", "typescript": "^5.9.3",
}, },
@@ -489,6 +491,14 @@
"@tailwindcss/postcss": ["@tailwindcss/[email protected]", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.0", "@tailwindcss/oxide": "4.3.0", "postcss": "^8.5.10", "tailwindcss": "4.3.0" } }, "sha512-Jm05Tjx+9yCLGv5qw1c+84Psds8MnyrEQYCB+FFk2lgGiUjlRqdxke4mVTuYrj2xnVZqKim2Apr5ySuQRYAw/w=="], "@tailwindcss/postcss": ["@tailwindcss/[email protected]", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.0", "@tailwindcss/oxide": "4.3.0", "postcss": "^8.5.10", "tailwindcss": "4.3.0" } }, "sha512-Jm05Tjx+9yCLGv5qw1c+84Psds8MnyrEQYCB+FFk2lgGiUjlRqdxke4mVTuYrj2xnVZqKim2Apr5ySuQRYAw/w=="],
"@tanstack/react-store": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "0.11.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-HaIGKI3YLmjBYIvy5DFDY23oNaYZIsTZfngey07Uh5iLVJgM3bIGCnZeOFOqzjFld9JHWcaHJnasD/bKoGKwJQ=="],
"@tanstack/react-table": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/react-store": "^0.11.1", "@tanstack/table-core": "9.2.4" }, "peerDependencies": { "react": ">=18" } }, "sha512-Rzp1Q4e0/nIgEjmISYR5HeEgLTNtrG+C7NFZf/AbCxPO5hg+zC3yNGwcoECigUk8SFzzvhXbd2rFdtP2ZiGrfA=="],
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-mzTOBhypOuDJAy/D8n2MfUZ1HFkXnmSETviRyhqEC8LUE7/IZQExOTxMANj3KjTofYTkFNpBY67qaVrT41YccA=="],
"@tanstack/table-core": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "^0.11.1" } }, "sha512-GwdDyGGr6UXAtubF14yAwcXvdaogqfsQgIk89Suebjxob/Rjq2xvfmXsjDF1rQmKmhHsJm9TOY7myxv3i6geJw=="],
"@ts-morph/common": ["@ts-morph/[email protected]", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="], "@ts-morph/common": ["@ts-morph/[email protected]", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="],
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="], "@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
@@ -661,6 +671,8 @@
"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], "clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
"cn": ["[email protected]", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-qRoU0ARrZD3Bbj1wKFftEKxPjSnzTEdFkf22NVhW+zU9D/wajhoP+qUZ5DChhhSOBCH1onV12hrmGqfu1+5Z2Q=="],
"code-block-writer": ["[email protected]", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="], "code-block-writer": ["[email protected]", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="],
"color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
@@ -1481,6 +1493,8 @@
"use-sidecar": ["[email protected]", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="], "use-sidecar": ["[email protected]", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], "util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"validate-npm-package-name": ["[email protected]", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], "validate-npm-package-name": ["[email protected]", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="],
+1 -1
View File
@@ -3,7 +3,7 @@ import { LanguageToggler } from "./languageToggler";
export default function Header() { export default function Header() {
return ( return (
<header className="fixed top-0 left-0 right-0 flex flex-row items-center justify-between gap-6 px-3 py-2.5"> <header className="fixed top-0 left-0 right-0 flex flex-row items-center justify-between gap-6 px-3 py-2.5 bg-background z-50">
<div /> <div />
<div className="flex flex-row items-center gap-3"> <div className="flex flex-row items-center gap-3">
<LanguageToggler /> <LanguageToggler />
@@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { Checkbox as CheckboxPrimitive } from "radix-ui"
import { CheckIcon } from "lucide-react"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
>
<CheckIcon
/>
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }
+2 -3
View File
@@ -1,8 +1,7 @@
"use client" "use client"
import * as React from "react" import * as React from "react"
import { cn } from "cn"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) { function Table({ className, ...props }: React.ComponentProps<"table">) {
return ( return (
@@ -57,7 +56,7 @@ function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
<tr <tr
data-slot="table-row" data-slot="table-row"
className={cn( className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", "border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className className
)} )}
{...props} {...props}
+44 -113
View File
@@ -74,130 +74,61 @@
"updateError": "An error occurred during the update. Please try again later." "updateError": "An error occurred during the update. Please try again later."
} }
}, },
"applications": { "consents": {
"title": "Applications", "title": "Consents",
"subtitle": "Here you can review and revoke concents for connected applications.", "subtitle": "Here you can review and revoke concents for connected applications.",
"authorized": "Autorized on", "authorized": "Autorized on",
"revoke": "Revoke", "revoke": "Revoke",
"successfullyRevoked": "Access successfully revoked!", "successfullyRevoked": "Access successfully revoked!",
"revocationError": "Failed to revoke access" "revocationError": "Failed to revoke access"
}, },
"positions": { "applications": {
"title": "Positions", "title": "Applications",
"loading": "Loading positions...", "subtitle": "Here you can connect your own applications to Kotosoft ID to provide your users an easy way to authorize.",
"empty": "No positions assigned" "table": {
}, "client": "Client",
"admin": { "redirectURIs": "Redirect URIs",
"title": "Administration", "scopes": "Scopes",
"permissions": { "status": "Status",
"title": "Permissions", "active": "Active",
"subtitle": "Permissions can be assigned to positions to control access.", "disabled": "Disabled",
"empty": "There're no permissions yet", "disable": "Disable this appplication",
"noDescription": "No description", "edit": "Edit this application"
"columns": {
"code": "Code",
"description": "Description",
"actions": "Actions"
},
"actions": {
"edit": "Edit",
"delete": "Delete",
"create": "Create permission"
},
"create": {
"title": "Create permission",
"code": "Code",
"description": "Description",
"cancel": "Cancel",
"save": "Save",
"codeRequired": "Code is required",
"success": "Permission successfully created!",
"error": "Failed to create permission"
},
"edit": {
"title": "Edit permission",
"code": "Code",
"description": "Description",
"cancel": "Cancel",
"save": "Update",
"success": "Permission successfully updated!",
"error": "Failed to update permission"
},
"delete": {
"success": "Permission successfully deleted!",
"error": "Failed to delete permission"
}
}, },
"positions": { "noApplications": "You don't have any connected applications yet",
"title": "Positions", "dialog": {
"subtitle": "Manage positions and assign permissions to control access.", "trigger": "Connect application",
"empty": "There're no positions yet", "title": "Connect a new application",
"noDescription": "No description", "subtitle": "Enter the details of your application to connect it.",
"columns": { "required": "This field is required",
"code": "Code", "name": {
"name": "Name", "title": "Application name",
"description": "Description", "minLength": "Name must be at least 2 characters",
"actions": "Actions" "maxLength": "Name must be at most 128 characters"
}, },
"actions": { "editTitle": "Edit application",
"edit": "Edit", "editSubtitle": "Update your application's details.",
"delete": "Delete", "editSubmit": "Save changes",
"create": "Create position" "redirectUris": {
"title": "Redirect URIs",
"placeholder": "https://example.com/callback",
"add": "Add another URI",
"invalid": "Must be a valid URL starting with http:// or https://"
}, },
"create": { "scopes": {
"title": "Create position", "title": "Scopes",
"code": "Code", "profile:read": "Read profile",
"name": "Name", "profile:edit": "Edit profile"
"description": "Description",
"cancel": "Cancel",
"save": "Save",
"codeRequired": "Code is required",
"nameRequired": "Name is required",
"success": "Position successfully created!",
"error": "Failed to create position"
}, },
"edit": { "submit": "Connect application",
"title": "Edit position", "secretReveal": {
"code": "Code", "title": "Save your client secret",
"name": "Name", "subtitle": "This is the only time your client secret will be shown. Copy it now and store it somewhere safe.",
"description": "Description", "clientId": "Client ID",
"cancel": "Cancel", "clientSecret": "Client secret",
"save": "Update", "warning": "You won't be able to see this secret again. If you lose it, you'll need to regenerate it.",
"success": "Position successfully updated!", "confirm": "I've saved it"
"error": "Failed to update position"
},
"delete": {
"success": "Position successfully deleted!",
"error": "Failed to delete position"
},
"permissions": {
"label": "Permissions",
"empty": "There are no permissions yet"
} }
},
"userPositions": {
"title": "User positions",
"subtitle": "Assign and revoke positions for users.",
"empty": "There're no users yet",
"noPositions": "No positions",
"columns": {
"user": "User",
"positions": "Positions",
"actions": "Actions"
},
"actions": {
"assign": "Assign",
"revoke": "Revoke"
},
"assign": {
"success": "Position assigned successfully!",
"error": "Failed to assign position"
},
"revoke": {
"success": "Position revoked successfully!",
"error": "Failed to revoke position"
},
"loadError": "Failed to load users"
} }
}, },
"logout": "Logout" "logout": "Logout"
+44 -113
View File
@@ -74,130 +74,61 @@
"updateError": "Si è verificato un errore durante l'aggiornamento. Riprova più tardi." "updateError": "Si è verificato un errore durante l'aggiornamento. Riprova più tardi."
} }
}, },
"applications": { "consents": {
"title": "Applicazioni", "title": "Consensi",
"subtitle": "Qui puoi vedere e revocare i consensi per le applicazioni connesse.", "subtitle": "Qui puoi vedere e revocare i consensi per le applicazioni connesse.",
"authorized": "Autorizzato il", "authorized": "Autorizzato il",
"revoke": "Revoca", "revoke": "Revoca",
"successfullyRevoked": "Accesso all'applicazione revocato con successo!", "successfullyRevoked": "Accesso all'applicazione revocato con successo!",
"revocationError": "Impossibile revocare l'accesso all'applicazione" "revocationError": "Impossibile revocare l'accesso all'applicazione"
}, },
"positions": { "applications": {
"title": "Posizioni", "title": "Applicazioni",
"loading": "Caricamento posizioni...", "subtitle": "Qui puoi collegare le tue applicazioni a Kotosoft ID per offrire ai tuoi utenti un modo semplice per autenticarsi.",
"empty": "Nessuna posizione assegnata" "table": {
}, "client": "Client",
"admin": { "redirectURIs": "Redirect URIs",
"title": "Amministrazione", "scopes": "Ambiti di accesso",
"permissions": { "status": "Stato",
"title": "Permessi", "active": "Attivo",
"subtitle": "I permessi possono essere assegnati alle posizioni per controllare l'accesso.", "disabled": "Disabilitato",
"empty": "Non ci sono permessi", "disable": "Disabilita applicazione",
"noDescription": "Senza descrizione", "edit": "Modifica applicazione"
"columns": {
"code": "Codice",
"description": "Descrizione",
"actions": "Azioni"
},
"actions": {
"edit": "Modifica",
"delete": "Elimina",
"create": "Crea permesso"
},
"create": {
"title": "Creazione del permesso",
"code": "Codice",
"description": "Descrizione",
"cancel": "Annulla",
"save": "Salva",
"codeRequired": "Il codice è obbligatorio",
"success": "Il permesso è stato creato con successo!",
"error": "Impossibile creare il permesso"
},
"edit": {
"title": "Modifica permesso",
"code": "Codice",
"description": "Descrizione",
"cancel": "Annulla",
"save": "Aggiorna",
"success": "Il permesso è stato aggiornato con successo!",
"error": "Impossibile aggiornare il permesso"
},
"delete": {
"success": "Il permesso è stato eliminato con successo!",
"error": "Impossibile eliminare il permesso"
}
}, },
"positions": { "noApplications": "Non hai ancora applicazioni collegate",
"title": "Posizioni", "dialog": {
"subtitle": "Gestire le posizioni e assegnare i permessi per controllare l'accesso.", "trigger": "Collega applicazione",
"empty": "Non ci sono posizioni", "title": "Collega una nuova applicazione",
"noDescription": "Senza descrizione", "subtitle": "Inserisci i dati della tua applicazione per collegarla.",
"columns": { "required": "Questo campo è obbligatorio",
"code": "Codice", "name": {
"name": "Nome", "title": "Nome dell'applicazione",
"description": "Descrizione", "minLength": "Il nome deve contenere almeno 2 caratteri",
"actions": "Azioni" "maxLength": "Il nome deve contenere al massimo 128 caratteri"
}, },
"actions": { "editTitle": "Modifica applicazione",
"edit": "Modifica", "editSubtitle": "Modifica i dati della tua applicazione.",
"delete": "Elimina", "editSubmit": "Salva modifiche",
"create": "Crea posizione" "redirectUris": {
"title": "URI di reindirizzamento",
"placeholder": "https://example.com/callback",
"add": "Aggiungi un altro URI",
"invalid": "Deve essere un URL valido che inizi con http:// o https://"
}, },
"create": { "scopes": {
"title": "Crea posizione", "title": "Ambiti di accesso",
"code": "Codice", "profile:read": "Lettura del profilo",
"name": "Nome", "profile:edit": "Modifica del profilo"
"description": "Descrizione",
"cancel": "Annulla",
"save": "Salva",
"codeRequired": "Il codice è obbligatorio",
"nameRequired": "Il nome è obbligatorio",
"success": "La posizione è stata creata con successo!",
"error": "Impossibile creare la posizione"
}, },
"edit": { "submit": "Collega applicazione",
"title": "Modifica posizione", "secretReveal": {
"code": "Codice", "title": "Salva il segreto del client",
"name": "Nome", "subtitle": "Questa è l'unica volta in cui il segreto del client verrà mostrato. Copialo ora e conservalo in un luogo sicuro.",
"description": "Descrizione", "clientId": "ID client",
"cancel": "Annulla", "clientSecret": "Segreto del client",
"save": "Aggiorna", "warning": "Non potrai visualizzare nuovamente questo segreto. Se lo perdi, dovrai generarne uno nuovo.",
"success": "La posizione è stata aggiornata con successo!", "confirm": "Ho salvato il segreto"
"error": "Impossibile aggiornare la posizione"
},
"delete": {
"success": "La posizione è stata eliminata con successo!",
"error": "Impossibile eliminare la posizione"
},
"permissions": {
"label": "Permessi",
"empty": "Non ci sono permessi"
} }
},
"userPositions": {
"title": "Posizioni utenti",
"subtitle": "Assegna e revoca posizioni agli utenti.",
"empty": "Non ci sono utenti",
"noPositions": "Nessuna posizione",
"columns": {
"user": "Utente",
"positions": "Posizioni",
"actions": "Azioni"
},
"actions": {
"assign": "Assegna",
"revoke": "Revoca"
},
"assign": {
"success": "Posizione assegnata con successo!",
"error": "Impossibile assegnare la posizione"
},
"revoke": {
"success": "Posizione revocata con successo!",
"error": "Impossibile revocare la posizione"
},
"loadError": "Impossibile caricare gli utenti"
} }
}, },
"logout": "Esci" "logout": "Esci"
+44 -113
View File
@@ -74,130 +74,61 @@
"updateError": "Произошла ошибка при обновлении. Попробуйте ещё раз позже." "updateError": "Произошла ошибка при обновлении. Попробуйте ещё раз позже."
} }
}, },
"applications": { "consents": {
"title": "Приложения", "title": "Разрешения",
"subtitle": "Здесь вы можете просматривать и отзывать доступ приложений.", "subtitle": "Здесь вы можете просматривать и отзывать доступ приложений.",
"authorized": "Разрешено", "authorized": "Разрешено",
"revoke": "Отозвать", "revoke": "Отозвать",
"successfullyRevoked": "Доступ приложения успешно отозван!", "successfullyRevoked": "Доступ приложения успешно отозван!",
"revocationError": "Не удалось отозвать доступ приложения" "revocationError": "Не удалось отозвать доступ приложения"
}, },
"positions": { "applications": {
"title": "Должности", "title": "Приложения",
"loading": "Загрузка должностей...", "subtitle": "Здесь вы можете подключить свои приложения к Kotosoft ID, чтобы предоставить пользователям удобный способ авторизации.",
"empty": "Нет назначенных должностей" "table": {
}, "client": "Клиент",
"admin": { "redirectURIs": "Redirect URIs",
"title": "Администрирование", "scopes": "Области доступа",
"permissions": { "status": "Статус",
"title": "Разрешения", "active": "Активно",
"subtitle": "Разрешения могут быть присвоены должностям для контроля прав доступа.", "disabled": "Отключено",
"empty": "Разрешений пока нет", "disable": "Отключить",
"noDescription": "Без описания", "edit": "Редактировать"
"columns": {
"code": "Код",
"description": "Описание",
"actions": "Действия"
},
"actions": {
"edit": "Изменить",
"delete": "Удалить",
"create": "Создать разрешение"
},
"create": {
"title": "Создать разрешение",
"code": "Код",
"description": "Описание",
"cancel": "Отмена",
"save": "Сохранить",
"codeRequired": "Код разрешения обязателен",
"success": "Разрешение успешно создано!",
"error": "Не удалось создать разрешение"
},
"edit": {
"title": "Редактирование разрешения",
"code": "Код",
"description": "Описание",
"cancel": "Отмена",
"save": "Сохранить",
"success": "Разрешение успешно обновлено!",
"error": "Не удалось обновить разрешение"
},
"delete": {
"success": "Разрешение успешно удалено!",
"error": "Не удалось удалить разрешение"
}
}, },
"positions": { "noApplications": "У вас пока нет подключённых приложений",
"title": "Должности", "dialog": {
"subtitle": "Управление должностями и назначение разрешений для контроля доступа.", "trigger": "Подключить приложение",
"empty": "Должностей пока нет", "title": "Подключить новое приложение",
"noDescription": "Без описания", "subtitle": "Введите данные приложения, чтобы подключить его.",
"columns": { "required": "Это поле обязательно",
"code": "Код", "name": {
"name": "Название", "title": "Название приложения",
"description": "Описание", "minLength": "Название должно содержать не менее 2 символов",
"actions": "Действия" "maxLength": "Название должно содержать не более 128 символов"
}, },
"actions": { "editTitle": "Редактировать приложение",
"edit": "Изменить", "editSubtitle": "Измените данные вашего приложения.",
"delete": "Удалить", "editSubmit": "Сохранить изменения",
"create": "Создать должность" "redirectUris": {
"title": "URI перенаправления",
"placeholder": "https://example.com/callback",
"add": "Добавить ещё URI",
"invalid": "Должен быть корректный URL, начинающийся с http:// или https://"
}, },
"create": { "scopes": {
"title": "Создать должность", "title": "Области доступа",
"code": "Код", "profile:read": "Чтение профиля",
"name": "Название", "profile:edit": "Редактирование профиля"
"description": "Описание",
"cancel": "Отмена",
"save": "Сохранить",
"codeRequired": "Код должности обязателен",
"nameRequired": "Название должности обязательно",
"success": "Должность успешно создана!",
"error": "Не удалось создать должность"
}, },
"edit": { "submit": "Подключить приложение",
"title": "Редактирование должности", "secretReveal": {
"code": "Код", "title": "Сохраните секрет клиента",
"name": "Название", "subtitle": "Секрет клиента будет показан только один раз. Скопируйте его сейчас и сохраните в безопасном месте.",
"description": "Описание", "clientId": "ID клиента",
"cancel": "Отмена", "clientSecret": "Секрет клиента",
"save": "Сохранить", "warning": "Вы больше не сможете посмотреть этот секрет. Если вы его потеряете, вам потребуется создать новое приложение.",
"success": "Должность успешно обновлена!", "confirm": "Я сохранил секрет"
"error": "Не удалось обновить должность"
},
"delete": {
"success": "Должность успешно удалена!",
"error": "Не удалось удалить должность"
},
"permissions": {
"label": "Разрешения",
"empty": "Разрешений пока нет"
} }
},
"userPositions": {
"title": "Должности пользователей",
"subtitle": "Назначайте и отзывайте должности у пользователей.",
"empty": "Пользователей пока нет",
"noPositions": "Нет должностей",
"columns": {
"user": "Пользователь",
"positions": "Должности",
"actions": "Действия"
},
"actions": {
"assign": "Назначить",
"revoke": "Отозвать"
},
"assign": {
"success": "Должность успешно назначена!",
"error": "Не удалось назначить должность"
},
"revoke": {
"success": "Должность успешно отозвана!",
"error": "Не удалось отозвать должность"
},
"loadError": "Не удалось загрузить пользователей"
} }
}, },
"logout": "Выйти" "logout": "Выйти"
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+2
View File
@@ -9,8 +9,10 @@
"lint": "eslint" "lint": "eslint"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-table": "^9.2.4",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cn": "^0.3.0",
"date-fns": "^4.4.0", "date-fns": "^4.4.0",
"lucide-react": "^0.575.0", "lucide-react": "^0.575.0",
"next": "^16.2.9", "next": "^16.2.9",
+10 -62
View File
@@ -33,77 +33,25 @@ export interface Consent {
isRevokable: boolean; isRevokable: boolean;
} }
export interface Permission {
id: string;
code: string;
name: string;
description: string;
created_at: string;
}
export interface Position {
code: string;
name: string;
description?: string | null;
permissions: Permission[];
}
export interface AdminUser {
id: string;
email: string;
first_name: string;
second_name: string;
is_admin: boolean;
positions: Position[];
}
export const localeMap = { export const localeMap = {
ru, ru,
en: enUS, en: enUS,
it, it,
}; };
export interface Region { export interface OAuthClient {
id: string; id: string;
code: string; client_id: string;
name: string; name: string;
} redirect_uris: string[];
grant_types: string[];
type FieldType = "text" | "date" | "select" | "masked" scopes: string[];
trusted: boolean;
export interface FieldOption { is_active: boolean;
value: string;
label: { en: string; ru: string };
}
export interface FieldTemplate {
id: string;
name: { en: string; ru: string };
type: FieldType;
required?: boolean;
mask?: string;
options?: FieldOption[];
generated?: boolean;
}
type CitizenshipApplicationStatus = "pending" | "rejected" | "approved"
export interface CitizenshipApplication {
id: string;
user_id: string;
status: CitizenshipApplicationStatus;
region_id: string;
reviewed_by?: string;
reviewed_at?: string;
reject_reason?: string;
created_at: string; created_at: string;
updated_at: string;
} }
export interface Citizen { export interface CreatedOAuthClient extends OAuthClient {
id: string; client_secret: string;
user_id: string;
application_id: string;
number: string;
issued_at: string;
region_id: string;
} }