fix
This commit is contained in:
@@ -4,9 +4,10 @@ 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"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||
)
|
||||
|
||||
type PositionsHandler struct {
|
||||
@@ -24,7 +25,7 @@ func localeFromRequest(c *gin.Context) string {
|
||||
if l := c.GetHeader("Accept-Language"); l != "" {
|
||||
return l
|
||||
}
|
||||
return "ru"
|
||||
return "en"
|
||||
}
|
||||
|
||||
func userIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
||||
@@ -36,6 +37,15 @@ func userIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func isAdminFromContext(c *gin.Context) bool {
|
||||
v, ok := c.Get("is_admin")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
b, ok := v.(bool)
|
||||
return ok && b
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
|
||||
userID, ok := userIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -52,25 +62,8 @@ func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
|
||||
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) ListPositions(c *gin.Context) {
|
||||
userID, ok := userIDFromContext(c)
|
||||
if !ok {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
c.Error(models.ErrInternal)
|
||||
return
|
||||
}
|
||||
if !isAdmin {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
@@ -84,19 +77,14 @@ func (h *PositionsHandler) ListPositions(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, positions)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
||||
userID, ok := userIDFromContext(c)
|
||||
if !ok {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
type upsertPositionRequest struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description *string `json:"description"`
|
||||
}
|
||||
|
||||
isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
c.Error(models.ErrInternal)
|
||||
return
|
||||
}
|
||||
if !isAdmin {
|
||||
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
@@ -115,3 +103,141 @@ func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type permissionCodeRequest struct {
|
||||
PermissionCode string `json:"permission_code" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
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 !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.RemovePermissionFromPosition(c.Request.Context(), c.Param("code"), c.Param("permCode")); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) ListPermissions(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
perms, err := h.svc.GetAllPermissions(c.Request.Context())
|
||||
if err != nil {
|
||||
c.Error(models.ErrInternal)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, perms)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) AssignPosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
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) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
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) 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)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,15 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, positions *handlers.PositionsHandler, svc *services.Service, repo *repositories.OAuthRepository, limiter *services.RateLimiter) *gin.Engine {
|
||||
func NewRouter(
|
||||
auth *handlers.AuthHandler,
|
||||
oauth *handlers.OAuthHandler,
|
||||
consents *handlers.ConsentHandler,
|
||||
positions *handlers.PositionsHandler,
|
||||
svc *services.Service,
|
||||
repo *repositories.OAuthRepository,
|
||||
limiter *services.RateLimiter,
|
||||
) *gin.Engine {
|
||||
r := gin.Default()
|
||||
r.Use(errorMiddleware())
|
||||
|
||||
@@ -20,17 +28,25 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
||||
{
|
||||
o.GET("/authorize", oauth.Authorize)
|
||||
o.GET("/session/:token", oauth.GetSession)
|
||||
o.POST("/session/login", middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn), oauth.SessionLogin)
|
||||
o.POST("/session/login",
|
||||
middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn),
|
||||
oauth.SessionLogin,
|
||||
)
|
||||
o.POST("/session/attach", oauth.SessionAttach)
|
||||
o.POST("/session/approve", oauth.SessionApprove)
|
||||
o.POST("/token", oauth.Token)
|
||||
o.POST("/revoke", oauth.Revoke)
|
||||
|
||||
o.POST("/introspect", positions.Introspect)
|
||||
}
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
a := api.Group("/auth")
|
||||
a.POST("/register", middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")), auth.Register)
|
||||
a.POST("/register",
|
||||
middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")),
|
||||
auth.Register,
|
||||
)
|
||||
a.POST("/refresh", auth.Refresh)
|
||||
|
||||
me := api.Group("/me")
|
||||
@@ -41,9 +57,19 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
||||
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
|
||||
me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions)
|
||||
|
||||
admin := api.Group("/admin")
|
||||
admin.GET("/positions", authMiddleware(svc, repo), positions.ListPositions)
|
||||
admin.POST("/positions", authMiddleware(svc, repo), positions.UpsertPosition)
|
||||
admin := api.Group("/admin", authMiddleware(svc, repo))
|
||||
{
|
||||
admin.GET("/permissions", positions.ListPermissions)
|
||||
|
||||
admin.GET("/positions", positions.ListPositions)
|
||||
admin.POST("/positions", positions.UpsertPosition)
|
||||
|
||||
admin.POST("/positions/:code/permissions", positions.AddPermissionToPosition)
|
||||
admin.DELETE("/positions/:code/permissions/:permCode", positions.RemovePermissionFromPosition)
|
||||
|
||||
admin.POST("/users/:userId/positions", positions.AssignPosition)
|
||||
admin.DELETE("/users/:userId/positions/:code", positions.RevokePosition)
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -77,7 +103,15 @@ func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, r
|
||||
return
|
||||
}
|
||||
|
||||
user, err := svc.GetUserByID(c.Request.Context(), info.UserID)
|
||||
if err != nil {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", info.UserID)
|
||||
c.Set("is_admin", user.IsAdmin)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,30 +6,50 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Permission struct {
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
Code string `db:"code" json:"code"`
|
||||
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"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||
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"`
|
||||
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"`
|
||||
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"`
|
||||
ValidFrom time.Time `db:"valid_from" json:"valid_from"`
|
||||
ValidTo *time.Time `db:"valid_to" json:"valid_to,omitempty"`
|
||||
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"`
|
||||
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"`
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ type User struct {
|
||||
SecondName string `db:"second_name" json:"second_name"`
|
||||
BirthDate *time.Time `db:"birth_date" json:"birth_date,omitempty"`
|
||||
Sex string `db:"sex" json:"sex"`
|
||||
IsAdmin bool `db:"is_admin" json:"is_admin"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -17,15 +17,102 @@ func NewPositionRepository(db *pgxpool.Pool) *PositionRepository {
|
||||
return &PositionRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetAllPermissions(ctx context.Context) ([]models.Permission, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT id, code, COALESCE(description, ''), created_at
|
||||
FROM permissions
|
||||
ORDER BY code
|
||||
`)
|
||||
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.Description, &p.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
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) ([]models.Permission, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT p.id, p.code, COALESCE(p.description, ''), p.created_at
|
||||
FROM position_permissions pp
|
||||
JOIN permissions p ON pp.permission_id = p.id
|
||||
WHERE pp.position_id = $1
|
||||
ORDER BY p.code
|
||||
`, positionID)
|
||||
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.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.code,
|
||||
COALESCE(pt.name, p.code) AS name, pt.description
|
||||
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
|
||||
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
|
||||
@@ -38,9 +125,18 @@ func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.U
|
||||
var result []models.PositionLocalized
|
||||
for rows.Next() {
|
||||
var p models.PositionLocalized
|
||||
if err := rows.Scan(&p.Code, &p.Name, &p.Description); err != nil {
|
||||
var positionID uuid.UUID
|
||||
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
perms, err := r.GetPositionPermissions(ctx, positionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Permissions = perms
|
||||
if p.Permissions == nil {
|
||||
p.Permissions = []models.Permission{}
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return result, rows.Err()
|
||||
@@ -48,27 +144,34 @@ func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.U
|
||||
|
||||
func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT p.code,
|
||||
COALESCE(pt.name, p.code) AS name, pt.description
|
||||
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
|
||||
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 result []models.PositionLocalized
|
||||
for rows.Next() {
|
||||
var p models.PositionLocalized
|
||||
if err := rows.Scan(&p.Code, &p.Name, &p.Description); err != nil {
|
||||
var positionID uuid.UUID
|
||||
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
perms, err := r.GetPositionPermissions(ctx, positionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Permissions = perms
|
||||
if p.Permissions == nil {
|
||||
p.Permissions = []models.Permission{}
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return result, rows.Err()
|
||||
@@ -85,8 +188,7 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code,
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO positions (code)
|
||||
VALUES ($1)
|
||||
ON CONFLICT (code) DO UPDATE
|
||||
SET updated_at = now()
|
||||
ON CONFLICT (code) DO UPDATE SET updated_at = now()
|
||||
RETURNING id
|
||||
`, code).Scan(&positionID)
|
||||
if err != nil {
|
||||
@@ -97,10 +199,8 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code,
|
||||
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
|
||||
SET name = EXCLUDED.name, description = EXCLUDED.description
|
||||
`, positionID, strings.ToLower(locale), name, description)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -108,21 +208,66 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code,
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (r *PositionRepository) UserHasPosition(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
|
||||
var exists bool
|
||||
func (r *PositionRepository) AssignPosition(ctx context.Context, userID, positionID uuid.UUID, assignedBy *uuid.UUID, validFrom interface{}, validTo *interface{}) 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 EXISTS (
|
||||
SELECT 1
|
||||
FROM user_positions up
|
||||
JOIN positions p ON up.position_id = p.id
|
||||
WHERE up.user_id = $1
|
||||
AND p.code = $2
|
||||
AND (up.valid_to IS NULL OR up.valid_to > now())
|
||||
)
|
||||
`, userID, code).Scan(&exists)
|
||||
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) ([]models.Permission, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT DISTINCT perm.id, perm.code, COALESCE(perm.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
|
||||
WHERE up.user_id = $1
|
||||
AND (up.valid_to IS NULL OR up.valid_to > now())
|
||||
ORDER BY perm.code
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
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.Description, &p.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return exists, nil
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
@@ -27,9 +27,9 @@ func (r *UserRepository) CreateUser(ctx context.Context, user models.User) (*mod
|
||||
err := r.db.QueryRow(ctx, `
|
||||
INSERT INTO users (email, password_hash, first_name, second_name, birth_date, sex)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, created_at, updated_at
|
||||
RETURNING id, is_admin, created_at, updated_at
|
||||
`, user.Email, user.PasswordHash, user.FirstName, user.SecondName, user.BirthDate, user.Sex).
|
||||
Scan(&user.ID, &user.CreatedAt, &user.UpdatedAt)
|
||||
Scan(&user.ID, &user.IsAdmin, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
@@ -63,9 +63,15 @@ func (r *UserRepository) DeleteUser(ctx context.Context, id uuid.UUID) error {
|
||||
func (r *UserRepository) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
|
||||
var u models.User
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
|
||||
SELECT id, email, password_hash, first_name, second_name,
|
||||
birth_date, sex, is_admin, created_at, updated_at
|
||||
FROM users WHERE email = $1
|
||||
`, email).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
|
||||
`, email).Scan(
|
||||
&u.ID, &u.Email, &u.PasswordHash,
|
||||
&u.FirstName, &u.SecondName,
|
||||
&u.BirthDate, &u.Sex, &u.IsAdmin,
|
||||
&u.CreatedAt, &u.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -75,9 +81,15 @@ func (r *UserRepository) GetUserByEmail(ctx context.Context, email string) (*mod
|
||||
func (r *UserRepository) GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error) {
|
||||
var u models.User
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
|
||||
SELECT id, email, password_hash, first_name, second_name,
|
||||
birth_date, sex, is_admin, created_at, updated_at
|
||||
FROM users WHERE id = $1
|
||||
`, id).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
|
||||
`, id).Scan(
|
||||
&u.ID, &u.Email, &u.PasswordHash,
|
||||
&u.FirstName, &u.SecondName,
|
||||
&u.BirthDate, &u.Sex, &u.IsAdmin,
|
||||
&u.CreatedAt, &u.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -2,12 +2,43 @@ package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const adminPositionCode = "PRESIDENT"
|
||||
func (s *Service) GetAllPermissions(ctx context.Context) ([]models.Permission, error) {
|
||||
return s.positions.GetAllPermissions(ctx)
|
||||
}
|
||||
|
||||
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 == "" {
|
||||
@@ -30,6 +61,74 @@ func (s *Service) UpsertPositionForLocale(ctx context.Context, code, locale, nam
|
||||
return s.positions.UpsertPositionForLocale(ctx, code, locale, name, description)
|
||||
}
|
||||
|
||||
func (s *Service) UserIsPositionsAdmin(ctx context.Context, userID uuid.UUID) (bool, error) {
|
||||
return s.positions.UserHasPosition(ctx, userID, adminPositionCode)
|
||||
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, (*interface{})(nil))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
return s.positions.RevokePosition(ctx, targetUserID, position.ID)
|
||||
}
|
||||
|
||||
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)
|
||||
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
|
||||
}
|
||||
|
||||
@@ -43,13 +43,26 @@ type OAuthRepo interface {
|
||||
UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error
|
||||
GetUserConsentsByClientID(ctx context.Context, userID uuid.UUID, clientID uuid.UUID) ([]models.UserConsent, error)
|
||||
RevokeConsent(ctx context.Context, userID, clientID uuid.UUID, revokedBy *uuid.UUID) error
|
||||
UpsertClient(ctx context.Context, client models.OAuthClient) error
|
||||
}
|
||||
|
||||
type PositionRepo interface {
|
||||
GetAllPermissions(ctx context.Context) ([]models.Permission, error)
|
||||
GetPermissionByCode(ctx context.Context, code string) (*models.Permission, error)
|
||||
GetPositionPermissions(ctx context.Context, positionID uuid.UUID) ([]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)
|
||||
UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error
|
||||
UserHasPosition(ctx context.Context, userID uuid.UUID, code string) (bool, error)
|
||||
|
||||
AssignPosition(ctx context.Context, userID, positionID uuid.UUID, assignedBy *uuid.UUID, validFrom any, validTo *any) 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) ([]models.Permission, error)
|
||||
}
|
||||
|
||||
type TokenConfig struct {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.users (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
@@ -7,7 +9,8 @@ CREATE TABLE IF NOT EXISTS public.users (
|
||||
first_name text NOT NULL,
|
||||
second_name text NOT NULL,
|
||||
birth_date date,
|
||||
sex text NOT NULL
|
||||
sex text NOT NULL,
|
||||
is_admin boolean DEFAULT false
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.oauth_clients (
|
||||
@@ -38,9 +41,20 @@ CREATE TABLE IF NOT EXISTS public.authorization_codes (
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_code_hash ON public.authorization_codes (code_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_expires_at ON public.authorization_codes (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_consumed_at ON public.authorization_codes (consumed_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_code_hash
|
||||
ON public.authorization_codes (code_hash);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_expires_at
|
||||
ON public.authorization_codes (expires_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_consumed_at
|
||||
ON public.authorization_codes (consumed_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_user_id
|
||||
ON public.authorization_codes(user_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_client_id
|
||||
ON public.authorization_codes(client_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.refresh_tokens (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -52,14 +66,11 @@ CREATE TABLE IF NOT EXISTS public.refresh_tokens (
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_token_hash ON public.refresh_tokens (token_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON public.refresh_tokens (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_token_hash
|
||||
ON public.refresh_tokens (token_hash);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_user_id
|
||||
ON public.authorization_codes(user_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_client_id
|
||||
ON public.authorization_codes(client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at
|
||||
ON public.refresh_tokens (expires_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user_id
|
||||
ON public.refresh_tokens(user_id);
|
||||
@@ -83,9 +94,15 @@ CREATE UNIQUE INDEX IF NOT EXISTS unique_active_consent
|
||||
ON public.user_consents (user_id, client_id)
|
||||
WHERE revoked_at IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_consents_user_id ON public.user_consents(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_consents_client_id ON public.user_consents(client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_consents_revoked ON public.user_consents(revoked_at) WHERE revoked_at IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_user_consents_user_id
|
||||
ON public.user_consents(user_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_consents_client_id
|
||||
ON public.user_consents(client_id);
|
||||
|
||||
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.positions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -94,23 +111,78 @@ CREATE TABLE IF NOT EXISTS public.positions (
|
||||
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,
|
||||
name text NOT NULL,
|
||||
CREATE TABLE IF NOT EXISTS public.permissions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
code text NOT NULL UNIQUE,
|
||||
description text,
|
||||
PRIMARY KEY (position_id, locale)
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
INSERT INTO public.permissions (code, description) VALUES
|
||||
('positions.manage', 'Create and edit positions'),
|
||||
('positions.assign', 'Assign positions to users')
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
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,
|
||||
CONSTRAINT user_positions_unique_active UNIQUE (user_id, position_id)
|
||||
DEFERRABLE INITIALLY IMMEDIATE
|
||||
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 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;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.set_updated_at()
|
||||
RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS users_updated_at ON public.users;
|
||||
CREATE TRIGGER users_updated_at
|
||||
BEFORE UPDATE ON public.users
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
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();
|
||||
@@ -1,40 +1,41 @@
|
||||
"use server"
|
||||
|
||||
import type { Position } from "@/types"
|
||||
import type { Permission, Position } from "@/types"
|
||||
import { cookies } from "next/headers"
|
||||
|
||||
export async function getMyPositions(): Promise<Position[]> {
|
||||
async function getAccessToken(): Promise<string | null> {
|
||||
const store = await cookies()
|
||||
const accessToken = store.get("access_token")?.value
|
||||
if (!accessToken) return []
|
||||
return store.get("access_token")?.value ?? null
|
||||
}
|
||||
|
||||
async function authHeaders(locale?: string): Promise<HeadersInit> {
|
||||
const token = await getAccessToken()
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Accept-Language": locale ?? "en",
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMyPositions(locale?: string): Promise<Position[]> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return []
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/positions`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
cache: "no-store",
|
||||
}
|
||||
{ headers: await authHeaders(locale), cache: "no-store" }
|
||||
)
|
||||
|
||||
if (!response.ok) return []
|
||||
return (await response.json()) as Position[]
|
||||
}
|
||||
|
||||
export async function listAllPositions(): Promise<Position[] | null> {
|
||||
const store = await cookies()
|
||||
const accessToken = store.get("access_token")?.value
|
||||
if (!accessToken) return null
|
||||
export async function listAllPositions(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: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
cache: "no-store",
|
||||
}
|
||||
{ headers: await authHeaders(locale), cache: "no-store" }
|
||||
)
|
||||
|
||||
if (response.status === 403) return null
|
||||
@@ -42,27 +43,176 @@ export async function listAllPositions(): Promise<Position[] | null> {
|
||||
return (await response.json()) as Position[]
|
||||
}
|
||||
|
||||
export async function upsertPosition(code: string, name: string, description?: string | null): Promise<{ success: boolean }> {
|
||||
const store = await cookies()
|
||||
const accessToken = store.get("access_token")?.value
|
||||
if (!accessToken) return { success: false }
|
||||
export async function upsertPosition(
|
||||
code: string,
|
||||
name: string,
|
||||
locale: string,
|
||||
description?: string | null
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
headers: { ...(await authHeaders(locale)), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
return { success: false }
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function createPermission(
|
||||
code: string,
|
||||
description?: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
...(await authHeaders()),
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
code,
|
||||
...(description ? { description } : {}),
|
||||
}),
|
||||
}
|
||||
)
|
||||
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function updatePermission(
|
||||
code: string,
|
||||
description?: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
...(await authHeaders()),
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...(description ? { description } : {}),
|
||||
}),
|
||||
}
|
||||
)
|
||||
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function deletePermission(
|
||||
code: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: await authHeaders(),
|
||||
}
|
||||
)
|
||||
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function listAllPermissions(): Promise<Permission[]> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return []
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`,
|
||||
{ headers: await authHeaders(), cache: "no-store" }
|
||||
)
|
||||
|
||||
if (!response.ok) return []
|
||||
return (await response.json()) as Permission[]
|
||||
}
|
||||
|
||||
export async function addPermissionToPosition(
|
||||
positionCode: string,
|
||||
permissionCode: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { ...(await authHeaders()), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ permission_code: permissionCode }),
|
||||
}
|
||||
)
|
||||
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function removePermissionFromPosition(
|
||||
positionCode: string,
|
||||
permissionCode: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions/${permissionCode}`,
|
||||
{ method: "DELETE", headers: await authHeaders() }
|
||||
)
|
||||
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function assignPosition(
|
||||
userId: string,
|
||||
positionCode: string,
|
||||
validFrom?: string,
|
||||
validTo?: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { ...(await authHeaders()), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
position_code: positionCode,
|
||||
...(validFrom ? { valid_from: validFrom } : {}),
|
||||
...(validTo ? { valid_to: validTo } : {}),
|
||||
}),
|
||||
}
|
||||
)
|
||||
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function revokePosition(
|
||||
userId: string,
|
||||
positionCode: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions/${positionCode}`,
|
||||
{ method: "DELETE", headers: await authHeaders() }
|
||||
)
|
||||
|
||||
return { success: response.ok }
|
||||
}
|
||||
@@ -4,13 +4,14 @@ import Header from "@/components/header";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { Consent, User } from "@/types";
|
||||
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, UserIcon } from "lucide-react";
|
||||
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, ShieldIcon, UserIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { Logout } from "@/actions/auth";
|
||||
import Profile from "./items/profile";
|
||||
import Applications from "./items/applications";
|
||||
import Positions from "./items/positions";
|
||||
import Admin from "./items/admin";
|
||||
|
||||
interface Props {
|
||||
userData: User | null;
|
||||
@@ -24,12 +25,19 @@ export default function MeClient({ userData, consentsData }: Props) {
|
||||
const [consents, setConsents] = useState(consentsData)
|
||||
const [selectedItem, setSelectedItem] = useState(0);
|
||||
|
||||
const items = [
|
||||
{"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.positions.title"), "icon": <BriefcaseBusinessIcon />, "component": <Positions />},
|
||||
|
||||
const baseItems = [
|
||||
{ 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.positions.title"), icon: <BriefcaseBusinessIcon />, component: <Positions /> },
|
||||
]
|
||||
|
||||
const adminItem = user?.is_admin
|
||||
? [{ name: t("items.admin.title"), icon: <ShieldIcon />, component: <Admin /> }]
|
||||
: []
|
||||
|
||||
const items = [...baseItems, ...adminItem]
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header />
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useLocale, useTranslations } from "next-intl"
|
||||
import type { Position } from "@/types"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { getMyPositions } from "@/actions/positions"
|
||||
import Permissions from "./admin/permissions"
|
||||
// import Positions from "./admin/positions"
|
||||
|
||||
export default function Admin() {
|
||||
const t = useTranslations("MePage.items.admin")
|
||||
const locale = useLocale()
|
||||
|
||||
const [positions, setPositions] = useState<Position[] | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
getMyPositions(locale)
|
||||
.then(setPositions)
|
||||
.finally(() => setLoading(false))
|
||||
}, [locale])
|
||||
|
||||
return (
|
||||
<div className="w-full lg:max-w-xl flex flex-col gap-6">
|
||||
<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-8">
|
||||
<Permissions />
|
||||
{/* <Positions /> */}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react";
|
||||
import { useForm, SubmitHandler } from "react-hook-form";
|
||||
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 { createPermission } from "@/actions/positions";
|
||||
import { toast } from "sonner";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
interface FormData {
|
||||
code: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export default function CreatePermissionDialog() {
|
||||
const { register, handleSubmit, formState: { errors, isSubmitting }, reset } = useForm<FormData>()
|
||||
|
||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||
const result = await createPermission(data.code, data.description)
|
||||
|
||||
if (!result.success) {
|
||||
toast("Failed to create permission", { icon: <X size={16} /> })
|
||||
return
|
||||
}
|
||||
|
||||
reset()
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
Add permission
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create permission</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.code}>
|
||||
<FieldLabel htmlFor="code">Code</FieldLabel>
|
||||
<Input
|
||||
id="code"
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={!!errors.code}
|
||||
{...register("code", {
|
||||
required: "Code is required"
|
||||
})}
|
||||
/>
|
||||
{errors.code && (
|
||||
<FieldError>{errors.code.message}</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.description}>
|
||||
<FieldLabel htmlFor="description">
|
||||
Description
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="description"
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={!!errors.description}
|
||||
{...register("description")}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter className="mt-4">
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Spinner />}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react";
|
||||
import { useForm, SubmitHandler } from "react-hook-form";
|
||||
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 { createPermission, updatePermission } from "@/actions/positions";
|
||||
import { Permission } from "@/types";
|
||||
import { X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface Props {
|
||||
permission: Permission
|
||||
}
|
||||
|
||||
interface FormData {
|
||||
code: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export default function EditPermissionDialog({ permission }: Props) {
|
||||
const { register, handleSubmit, formState: { errors, isSubmitting }, reset } = useForm<FormData>()
|
||||
|
||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||
const result = await updatePermission(data.code, data.description)
|
||||
|
||||
if (!result.success) {
|
||||
toast("Failed to update permission", { icon: <X size={16} /> })
|
||||
return
|
||||
}
|
||||
|
||||
reset()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="w-full px-2 justify-start">Edit</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit permission</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.code}>
|
||||
<FieldLabel htmlFor="code">Code</FieldLabel>
|
||||
<Input
|
||||
id="code"
|
||||
value={permission.code}
|
||||
disabled
|
||||
/>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.description}>
|
||||
<FieldLabel htmlFor="description">
|
||||
Description
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="description"
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={!!errors.description}
|
||||
{...register("description")}
|
||||
value={permission.description}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter className="mt-4">
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Spinner />}
|
||||
Update
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardFooter } from "@/components/ui/card";
|
||||
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 CreatePermissionDialog from "./dialogs/createPermissionDialog";
|
||||
import { Permission } from "@/types";
|
||||
import { deletePermission, listAllPermissions } from "@/actions/positions";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import EditPermissionDialog from "./dialogs/editPermissionDialog";
|
||||
|
||||
export default function Permissions() {
|
||||
const [permissions, setPermissions] = useState<Permission[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
const data = await listAllPermissions();
|
||||
setPermissions(data);
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
load()
|
||||
}, [])
|
||||
|
||||
const permissionsMemo = useMemo(() => permissions, [permissions]);
|
||||
|
||||
async function handleDelete(code: string) {
|
||||
const result = await deletePermission(code)
|
||||
|
||||
if (result.success) {
|
||||
setPermissions((prev) =>
|
||||
prev.filter((p) => p.code !== code)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-lg">Permissions</h2>
|
||||
<h4 className="text-sm text-muted-foreground">Here You can create permissions which later You can assign them to positions</h4>
|
||||
</div>
|
||||
<Card size="sm" className="w-full">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Code</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{permissionsMemo.map((permission) => (
|
||||
<TableRow key={permission.code}>
|
||||
<TableCell>{permission.code}</TableCell>
|
||||
<TableCell>{permission.description}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<EditPermissionDialog permission={permission} />
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(permission.code)}>Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
{isLoading && <p className="mx-2 my-1 text-muted-foreground animate-pulse">Permissions are loading...</p>}
|
||||
</Table>
|
||||
<CardFooter>
|
||||
<CreatePermissionDialog />
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,73 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { useLocale, useTranslations } from "next-intl"
|
||||
import type { Position } from "@/types"
|
||||
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { listAllPositions, upsertPosition, getMyPositions } from "@/actions/positions"
|
||||
import { toast } from "sonner"
|
||||
import { Check, X } from "lucide-react"
|
||||
import { getMyPositions } from "@/actions/positions"
|
||||
|
||||
export default function Positions() {
|
||||
const t = useTranslations("MePage.items.positions")
|
||||
const locale = useLocale()
|
||||
|
||||
const [positions, setPositions] = useState<Position[] | null>(null)
|
||||
const [isAdmin, setIsAdmin] = useState<boolean | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const [code, setCode] = useState("")
|
||||
const [name, setName] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [own, all] = await Promise.all([getMyPositions(), listAllPositions()])
|
||||
setPositions(all ?? own)
|
||||
setIsAdmin(all !== null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
void load()
|
||||
}, [])
|
||||
|
||||
const handleSave = async () => {
|
||||
setFormError(null)
|
||||
if (!code || !name) {
|
||||
setFormError(t("form.required"))
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const result = await upsertPosition(code, name, description || undefined)
|
||||
if (!result.success) {
|
||||
toast(t("form.saveError"), { icon: <X size={16} /> })
|
||||
return
|
||||
}
|
||||
|
||||
const updated = await listAllPositions()
|
||||
if (updated) setPositions(updated)
|
||||
|
||||
toast(t("form.saved"), { icon: <Check size={16} /> })
|
||||
setCode("")
|
||||
setName("")
|
||||
setDescription("")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
getMyPositions(locale)
|
||||
.then(setPositions)
|
||||
.finally(() => setLoading(false))
|
||||
}, [locale])
|
||||
|
||||
return (
|
||||
<div className="w-full lg:max-w-md flex flex-col gap-4">
|
||||
<div className="w-full lg:max-w-sm flex flex-col gap-4">
|
||||
<h1 className="text-xl">{t("title")}</h1>
|
||||
|
||||
{loading && (
|
||||
@@ -78,67 +33,32 @@ export default function Positions() {
|
||||
)}
|
||||
|
||||
{!loading && (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
{positions?.map((position) => (
|
||||
<div className="space-y-4">
|
||||
{positions && positions.length > 0 ? (
|
||||
positions.map((position) => (
|
||||
<Item key={position.code}>
|
||||
<ItemContent>
|
||||
<ItemTitle>{position.name}</ItemTitle>
|
||||
<ItemDescription>
|
||||
{position.description || t("noDescription")}
|
||||
</ItemDescription>
|
||||
{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 font-mono">
|
||||
{perm.code}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ItemContent>
|
||||
</Item>
|
||||
))}
|
||||
{(!positions || positions.length === 0) && (
|
||||
<p className="text-sm text-muted-foreground">{t("empty")}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isAdmin && (
|
||||
<div className="mt-6">
|
||||
<h2 className="text-lg mb-2">{t("form.title")}</h2>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="code">{t("form.code")}</FieldLabel>
|
||||
<Input
|
||||
id="code"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.toUpperCase())}
|
||||
disabled={saving}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="name">{t("form.name")}</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={saving}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="description">{t("form.description")}</FieldLabel>
|
||||
<Input
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
disabled={saving}
|
||||
/>
|
||||
</Field>
|
||||
{formError && <FieldError>{formError}</FieldError>}
|
||||
<Field>
|
||||
<Button type="button" onClick={handleSave} disabled={saving}>
|
||||
{saving && <Spinner />}
|
||||
{t("form.save")}
|
||||
</Button>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">{t("empty")}</p>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
||||
outline:
|
||||
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot.Root : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
data-variant={variant}
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
@@ -0,0 +1,103 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn(
|
||||
"text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn(
|
||||
"flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-background p-4 text-sm ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close data-slot="dialog-close" asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-2 right-2"
|
||||
size="icon-sm"
|
||||
>
|
||||
<XIcon
|
||||
/>
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-base leading-none font-medium", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
@@ -97,6 +97,9 @@
|
||||
"saveError": "Failed to save position"
|
||||
}
|
||||
},
|
||||
"admin": {
|
||||
"title": "Administration"
|
||||
},
|
||||
"logout": "Logout"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -6,11 +6,13 @@ export enum Sex {
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
second_name: string;
|
||||
birth_date: string;
|
||||
sex: Sex;
|
||||
is_admin: boolean;
|
||||
}
|
||||
|
||||
export interface OAuthSession {
|
||||
@@ -23,22 +25,30 @@ export interface OAuthSession {
|
||||
}
|
||||
|
||||
export interface Consent {
|
||||
client_id: string
|
||||
client_name: string
|
||||
scopes: string[]
|
||||
authorized_at: string
|
||||
last_used_at: string | null
|
||||
isRevokable: boolean
|
||||
client_id: string;
|
||||
client_name: string;
|
||||
scopes: string[];
|
||||
authorized_at: string;
|
||||
last_used_at: string | null;
|
||||
isRevokable: boolean;
|
||||
}
|
||||
|
||||
export interface Permission {
|
||||
id: string;
|
||||
code: string;
|
||||
description: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Position {
|
||||
code: string
|
||||
name: string
|
||||
description?: string | null
|
||||
code: string;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
permissions: Permission[];
|
||||
}
|
||||
|
||||
export const localeMap = {
|
||||
ru,
|
||||
en: enUS,
|
||||
it
|
||||
it,
|
||||
};
|
||||
Reference in New Issue
Block a user