v2: fixed oauth errors, oauth clients native control added
This commit is contained in:
@@ -35,8 +35,6 @@ func main() {
|
||||
|
||||
userRepo := repositories.NewUserRepository(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 {
|
||||
log.Fatalf("seed client: %v", err)
|
||||
@@ -45,11 +43,10 @@ func main() {
|
||||
svc := services.New(
|
||||
userRepo,
|
||||
oauthRepo,
|
||||
positionRepo,
|
||||
redis.Client,
|
||||
services.TokenConfig{
|
||||
AccessTTL: cfg.JWT.TTL,
|
||||
RefreshTTL: cfg.JWT.TTL * 7,
|
||||
AccessTTL: cfg.Tokens.AccessTTL,
|
||||
RefreshTTL: cfg.Tokens.RefreshTTL,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -58,11 +55,9 @@ func main() {
|
||||
authHandler := handlers.NewAuthHandler(svc)
|
||||
oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL)
|
||||
consentHandler := handlers.NewConsentHandler(svc)
|
||||
positionsHandler := handlers.NewPositionsHandler(svc)
|
||||
citizenshipSvc := services.NewCitizenshipService(citizenshipRepo)
|
||||
citizenshipHandler := handlers.NewCitizenshipHandler(citizenshipSvc)
|
||||
clientHandler := handlers.NewClientHandler(svc)
|
||||
|
||||
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)
|
||||
if err := router.Run(cfg.Server.Addr); err != nil {
|
||||
|
||||
@@ -8,6 +8,7 @@ require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.8.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/redis/go-redis/v9 v9.18.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/goccy/go-json v0.10.2 // 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/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // 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/quic-go/qpack v0.5.1 // 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/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
|
||||
@@ -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/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||
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-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||
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/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
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/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/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/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
|
||||
@@ -13,7 +13,7 @@ type Conf struct {
|
||||
Postgres Postgres
|
||||
Redis Redis
|
||||
Client Client
|
||||
JWT JWT
|
||||
Tokens Tokens
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type JWT struct {
|
||||
Secret string `env:"JWT_SECRET,required"`
|
||||
TTL time.Duration `env:"JWT_TTL" envDefault:"24h"`
|
||||
// Tokens holds the TTLs for opaque access/refresh tokens.
|
||||
// NOTE: tokens issued by this service are opaque (random), not JWTs —
|
||||
// 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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -16,8 +16,7 @@ func NewRouter(
|
||||
auth *handlers.AuthHandler,
|
||||
oauth *handlers.OAuthHandler,
|
||||
consents *handlers.ConsentHandler,
|
||||
positions *handlers.PositionsHandler,
|
||||
citizenship *handlers.CitizenshipHandler,
|
||||
clients *handlers.ClientHandler,
|
||||
svc *services.Service,
|
||||
repo *repositories.OAuthRepository,
|
||||
limiter *services.RateLimiter,
|
||||
@@ -50,14 +49,15 @@ func NewRouter(
|
||||
middleware.RateLimit(limiter, services.RevokeRateLimit, middleware.RevokeKeyFn),
|
||||
oauth.Revoke,
|
||||
)
|
||||
|
||||
o.POST("/introspect", positions.Introspect)
|
||||
}
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
a := api.Group("/auth")
|
||||
a.POST("/register", auth.Register)
|
||||
a.POST("/register",
|
||||
middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")),
|
||||
auth.Register,
|
||||
)
|
||||
a.POST("/refresh",
|
||||
middleware.RateLimit(limiter, services.RefreshRateLimit, middleware.RefreshKeyFn),
|
||||
auth.Refresh,
|
||||
@@ -69,101 +69,22 @@ func NewRouter(
|
||||
me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile)
|
||||
me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents)
|
||||
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
|
||||
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)
|
||||
|
||||
manage := admin.Group("", permissionMiddleware(svc, "positions.manage"))
|
||||
{
|
||||
manage.GET("/permissions", positions.ListPermissions)
|
||||
manage.POST("/permissions", positions.CreatePermission)
|
||||
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)
|
||||
}
|
||||
c := admin.Group("/clients")
|
||||
c.POST("", clients.Create)
|
||||
c.GET("", clients.List)
|
||||
c.GET("/:id", clients.Get)
|
||||
c.PATCH("/:id", clients.Update)
|
||||
c.DELETE("/:id", clients.Deactivate)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
return func(c *gin.Context) {
|
||||
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"`
|
||||
}
|
||||
|
||||
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 {
|
||||
ID uuid.UUID `json:"id"`
|
||||
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"`
|
||||
}
|
||||
|
||||
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 {
|
||||
Email string `json:"email" binding:"required,min=3"`
|
||||
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
|
||||
}
|
||||
|
||||
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) {
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 {
|
||||
GetOAuthClientByClientID(ctx context.Context, clientID string) (*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)
|
||||
GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error)
|
||||
ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error
|
||||
@@ -47,31 +52,6 @@ type OAuthRepo interface {
|
||||
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 {
|
||||
AccessTTL time.Duration
|
||||
RefreshTTL time.Duration
|
||||
@@ -83,26 +63,23 @@ type ClientAuth struct {
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users UserRepo
|
||||
oauth OAuthRepo
|
||||
positions PositionRepo
|
||||
redis *redis.Client
|
||||
tokens TokenConfig
|
||||
users UserRepo
|
||||
oauth OAuthRepo
|
||||
redis *redis.Client
|
||||
tokens TokenConfig
|
||||
}
|
||||
|
||||
func New(
|
||||
users UserRepo,
|
||||
oauth OAuthRepo,
|
||||
positions PositionRepo,
|
||||
rdb *redis.Client,
|
||||
tokenCfg TokenConfig,
|
||||
) *Service {
|
||||
return &Service{
|
||||
users: users,
|
||||
oauth: oauth,
|
||||
positions: positions,
|
||||
redis: rdb,
|
||||
tokens: tokenCfg,
|
||||
users: users,
|
||||
oauth: oauth,
|
||||
redis: rdb,
|
||||
tokens: tokenCfg,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
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 (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
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)
|
||||
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
|
||||
ON public.users (is_admin)
|
||||
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
|
||||
BEFORE UPDATE ON public.oauth_clients
|
||||
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;
|
||||
Reference in New Issue
Block a user