fixes
This commit is contained in:
@@ -37,15 +37,6 @@ func userIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
|||||||
return id, ok
|
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) {
|
func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
|
||||||
userID, ok := userIDFromContext(c)
|
userID, ok := userIDFromContext(c)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -63,11 +54,6 @@ func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *PositionsHandler) ListPositions(c *gin.Context) {
|
func (h *PositionsHandler) ListPositions(c *gin.Context) {
|
||||||
if !isAdminFromContext(c) {
|
|
||||||
c.Error(models.ErrForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
positions, err := h.svc.GetAllPositions(c.Request.Context(), localeFromRequest(c))
|
positions, err := h.svc.GetAllPositions(c.Request.Context(), localeFromRequest(c))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(models.ErrInternal)
|
c.Error(models.ErrInternal)
|
||||||
@@ -84,11 +70,6 @@ type upsertPositionRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
||||||
if !isAdminFromContext(c) {
|
|
||||||
c.Error(models.ErrForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var req upsertPositionRequest
|
var req upsertPositionRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.Error(models.ErrBadRequest)
|
c.Error(models.ErrBadRequest)
|
||||||
@@ -103,16 +84,38 @@ func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
|||||||
c.Status(http.StatusNoContent)
|
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 {
|
type permissionCodeRequest struct {
|
||||||
PermissionCode string `json:"permission_code" binding:"required"`
|
PermissionCode string `json:"permission_code" binding:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) {
|
func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) {
|
||||||
if !isAdminFromContext(c) {
|
|
||||||
c.Error(models.ErrForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var req permissionCodeRequest
|
var req permissionCodeRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.Error(models.ErrBadRequest)
|
c.Error(models.ErrBadRequest)
|
||||||
@@ -128,12 +131,7 @@ func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *PositionsHandler) RemovePermissionFromPosition(c *gin.Context) {
|
func (h *PositionsHandler) RemovePermissionFromPosition(c *gin.Context) {
|
||||||
if !isAdminFromContext(c) {
|
if err := h.svc.RemovePermissionFromPosition(c.Request.Context(), c.Param("code"), c.Param("permissionCode")); err != nil {
|
||||||
c.Error(models.ErrForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.svc.RemovePermissionFromPosition(c.Request.Context(), c.Param("code"), c.Param("permCode")); err != nil {
|
|
||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -142,11 +140,6 @@ func (h *PositionsHandler) RemovePermissionFromPosition(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *PositionsHandler) ListPermissions(c *gin.Context) {
|
func (h *PositionsHandler) ListPermissions(c *gin.Context) {
|
||||||
if !isAdminFromContext(c) {
|
|
||||||
c.Error(models.ErrForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
perms, err := h.svc.GetAllPermissions(c.Request.Context())
|
perms, err := h.svc.GetAllPermissions(c.Request.Context())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(models.ErrInternal)
|
c.Error(models.ErrInternal)
|
||||||
@@ -157,11 +150,6 @@ func (h *PositionsHandler) ListPermissions(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *PositionsHandler) AssignPosition(c *gin.Context) {
|
func (h *PositionsHandler) AssignPosition(c *gin.Context) {
|
||||||
if !isAdminFromContext(c) {
|
|
||||||
c.Error(models.ErrForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
adminID, ok := userIDFromContext(c)
|
adminID, ok := userIDFromContext(c)
|
||||||
if !ok {
|
if !ok {
|
||||||
c.Error(models.ErrUnauthorized)
|
c.Error(models.ErrUnauthorized)
|
||||||
@@ -189,11 +177,6 @@ func (h *PositionsHandler) AssignPosition(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *PositionsHandler) RevokePosition(c *gin.Context) {
|
func (h *PositionsHandler) RevokePosition(c *gin.Context) {
|
||||||
if !isAdminFromContext(c) {
|
|
||||||
c.Error(models.ErrForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
targetUserID, err := uuid.Parse(c.Param("userId"))
|
targetUserID, err := uuid.Parse(c.Param("userId"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(models.ErrBadRequest)
|
c.Error(models.ErrBadRequest)
|
||||||
@@ -208,6 +191,50 @@ func (h *PositionsHandler) RevokePosition(c *gin.Context) {
|
|||||||
c.Status(http.StatusNoContent)
|
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, 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"), 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) {
|
func (h *PositionsHandler) Introspect(c *gin.Context) {
|
||||||
var req struct {
|
var req struct {
|
||||||
Token string `json:"token" form:"token" binding:"required"`
|
Token string `json:"token" form:"token" binding:"required"`
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ func NewRouter(
|
|||||||
limiter *services.RateLimiter,
|
limiter *services.RateLimiter,
|
||||||
) *gin.Engine {
|
) *gin.Engine {
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
|
r.Use(middleware.LoggingMiddleware())
|
||||||
r.Use(errorMiddleware())
|
r.Use(errorMiddleware())
|
||||||
|
|
||||||
o := r.Group("/oauth")
|
o := r.Group("/oauth")
|
||||||
@@ -57,15 +58,19 @@ func NewRouter(
|
|||||||
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
|
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
|
||||||
me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions)
|
me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions)
|
||||||
|
|
||||||
admin := api.Group("/admin", authMiddleware(svc, repo))
|
admin := api.Group("/admin", authMiddleware(svc, repo), middleware.AdminOnly())
|
||||||
{
|
{
|
||||||
admin.GET("/permissions", positions.ListPermissions)
|
admin.GET("/permissions", positions.ListPermissions)
|
||||||
|
admin.POST("/permissions", positions.CreatePermission)
|
||||||
|
admin.PUT("/permissions/:code", positions.UpdatePermission)
|
||||||
|
admin.DELETE("/permissions/:code", positions.DeletePermission)
|
||||||
|
|
||||||
admin.GET("/positions", positions.ListPositions)
|
admin.GET("/positions", positions.ListPositions)
|
||||||
admin.POST("/positions", positions.UpsertPosition)
|
admin.POST("/positions", positions.UpsertPosition)
|
||||||
|
admin.PUT("/positions/:code", positions.UpdatePosition)
|
||||||
|
admin.DELETE("/positions/:code", positions.DeletePosition)
|
||||||
admin.POST("/positions/:code/permissions", positions.AddPermissionToPosition)
|
admin.POST("/positions/:code/permissions", positions.AddPermissionToPosition)
|
||||||
admin.DELETE("/positions/:code/permissions/:permCode", positions.RemovePermissionFromPosition)
|
admin.DELETE("/positions/:code/permissions/:permissionCode", positions.RemovePermissionFromPosition)
|
||||||
|
|
||||||
admin.POST("/users/:userId/positions", positions.AssignPosition)
|
admin.POST("/users/:userId/positions", positions.AssignPosition)
|
||||||
admin.DELETE("/users/:userId/positions/:code", positions.RevokePosition)
|
admin.DELETE("/users/:userId/positions/:code", positions.RevokePosition)
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AdminOnly() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
isAdmin, exists := c.Get("is_admin")
|
||||||
|
if !exists || !isAdmin.(bool) {
|
||||||
|
c.Error(models.ErrForbidden.WithMessage("Admin role required"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RequestLogger struct {
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
Method string `json:"method"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
Duration time.Duration `json:"duration_ms"`
|
||||||
|
UserID string `json:"user_id,omitempty"`
|
||||||
|
ClientIP string `json:"client_ip"`
|
||||||
|
UserAgent string `json:"user_agent"`
|
||||||
|
Errors []string `json:"errors,omitempty"`
|
||||||
|
Extra map[string]any `json:"extra,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoggingMiddleware() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
start := time.Now()
|
||||||
|
requestID := uuid.New().String()
|
||||||
|
|
||||||
|
c.Set("request_id", requestID)
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
|
||||||
|
duration := time.Since(start)
|
||||||
|
|
||||||
|
userID, _ := c.Get("user_id")
|
||||||
|
userIDStr := ""
|
||||||
|
if uid, ok := userID.(uuid.UUID); ok {
|
||||||
|
userIDStr = uid.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var errors []string
|
||||||
|
for _, err := range c.Errors {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := RequestLogger{
|
||||||
|
RequestID: requestID,
|
||||||
|
Method: c.Request.Method,
|
||||||
|
Path: c.Request.URL.Path,
|
||||||
|
Status: c.Writer.Status(),
|
||||||
|
Duration: duration,
|
||||||
|
UserID: userIDStr,
|
||||||
|
ClientIP: c.ClientIP(),
|
||||||
|
UserAgent: c.Request.UserAgent(),
|
||||||
|
Errors: errors,
|
||||||
|
}
|
||||||
|
|
||||||
|
if logData, err := json.Marshal(entry); err == nil {
|
||||||
|
log.Println(string(logData))
|
||||||
|
} else {
|
||||||
|
log.Printf("failed to marshal log entry: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func RequestIDFromContext(c *gin.Context) string {
|
||||||
|
if rid, exists := c.Get("request_id"); exists {
|
||||||
|
if ridStr, ok := rid.(string); ok {
|
||||||
|
return ridStr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -39,6 +39,26 @@ func (r *PositionRepository) GetAllPermissions(ctx context.Context) ([]models.Pe
|
|||||||
return result, rows.Err()
|
return result, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *PositionRepository) CreatePermission(ctx context.Context, code string, description *string) error {
|
||||||
|
_, err := r.db.Exec(ctx, `
|
||||||
|
INSERT INTO permissions (code, description)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
`, code, description)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *PositionRepository) UpdatePermission(ctx context.Context, code string, description *string) error {
|
||||||
|
_, err := r.db.Exec(ctx, `
|
||||||
|
UPDATE permissions SET description = $2 WHERE code = $1
|
||||||
|
`, code, description)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *PositionRepository) DeletePermission(ctx context.Context, code string) error {
|
||||||
|
_, err := r.db.Exec(ctx, `DELETE FROM permissions WHERE code = $1`, code)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
func (r *PositionRepository) GetPermissionByCode(ctx context.Context, code string) (*models.Permission, error) {
|
func (r *PositionRepository) GetPermissionByCode(ctx context.Context, code string) (*models.Permission, error) {
|
||||||
var p models.Permission
|
var p models.Permission
|
||||||
err := r.db.QueryRow(ctx, `
|
err := r.db.QueryRow(ctx, `
|
||||||
@@ -208,6 +228,11 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code,
|
|||||||
return tx.Commit(ctx)
|
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 interface{}, validTo *interface{}) error {
|
func (r *PositionRepository) AssignPosition(ctx context.Context, userID, positionID uuid.UUID, assignedBy *uuid.UUID, validFrom interface{}, validTo *interface{}) error {
|
||||||
_, err := r.db.Exec(ctx, `
|
_, err := r.db.Exec(ctx, `
|
||||||
INSERT INTO user_positions (user_id, position_id, assigned_by, valid_from, valid_to)
|
INSERT INTO user_positions (user_id, position_id, assigned_by, valid_from, valid_to)
|
||||||
|
|||||||
@@ -61,6 +61,10 @@ func (s *Service) UpsertPositionForLocale(ctx context.Context, code, locale, nam
|
|||||||
return s.positions.UpsertPositionForLocale(ctx, code, locale, name, description)
|
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 {
|
func (s *Service) AssignPosition(ctx context.Context, adminID, targetUserID uuid.UUID, input models.AssignPositionInput) error {
|
||||||
position, err := s.positions.GetPositionByCode(ctx, input.PositionCode)
|
position, err := s.positions.GetPositionByCode(ctx, input.PositionCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -84,6 +88,18 @@ func (s *Service) RevokePosition(ctx context.Context, targetUserID uuid.UUID, po
|
|||||||
return s.positions.RevokePosition(ctx, targetUserID, position.ID)
|
return s.positions.RevokePosition(ctx, targetUserID, position.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) CreatePermission(ctx context.Context, code string, description *string) error {
|
||||||
|
return s.positions.CreatePermission(ctx, code, description)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdatePermission(ctx context.Context, code string, description *string) error {
|
||||||
|
return s.positions.UpdatePermission(ctx, code, 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) {
|
func (s *Service) UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, error) {
|
||||||
allowed, _, err := s.positions.UserHasPermission(ctx, userID, permissionCode)
|
allowed, _, err := s.positions.UserHasPermission(ctx, userID, permissionCode)
|
||||||
return allowed, err
|
return allowed, err
|
||||||
|
|||||||
@@ -63,6 +63,11 @@ type PositionRepo interface {
|
|||||||
|
|
||||||
UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, string, error)
|
UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, string, error)
|
||||||
GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]models.Permission, error)
|
GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]models.Permission, error)
|
||||||
|
|
||||||
|
CreatePermission(ctx context.Context, code string, description *string) error
|
||||||
|
UpdatePermission(ctx context.Context, code string, description *string) error
|
||||||
|
DeletePositionByCode(ctx context.Context, code string) error
|
||||||
|
DeletePermission(ctx context.Context, code string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type TokenConfig struct {
|
type TokenConfig struct {
|
||||||
|
|||||||
Binary file not shown.
@@ -111,6 +111,20 @@ CREATE TABLE IF NOT EXISTS public.positions (
|
|||||||
updated_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 (
|
CREATE TABLE IF NOT EXISTS public.permissions (
|
||||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
code text NOT NULL UNIQUE,
|
code text NOT NULL UNIQUE,
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ export async function SessionLogin(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GetUser(): Promise<User | null> {
|
export async function fetchUser(): Promise<User | null> {
|
||||||
const store = await cookies();
|
const store = await cookies();
|
||||||
const accessToken = store.get("access_token")?.value;
|
const accessToken = store.get("access_token")?.value;
|
||||||
if (!accessToken) return null;
|
if (!accessToken) return null;
|
||||||
@@ -114,7 +114,7 @@ export async function GetUser(): Promise<User | null> {
|
|||||||
await clearTokens();
|
await clearTokens();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return GetUser();
|
return fetchUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!response.ok) return null;
|
if (!response.ok) return null;
|
||||||
@@ -124,7 +124,7 @@ export async function GetUser(): Promise<User | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function UpdateUser(first_name: string, second_name: string, birth_date: string): Promise<User | null> {
|
export async function updateUser(first_name: string, second_name: string, birth_date: string): Promise<User | null> {
|
||||||
const store = await cookies();
|
const store = await cookies();
|
||||||
const accessToken = store.get("access_token")?.value;
|
const accessToken = store.get("access_token")?.value;
|
||||||
if (!accessToken) return null;
|
if (!accessToken) return null;
|
||||||
@@ -155,7 +155,7 @@ export async function UpdateUser(first_name: string, second_name: string, birth_
|
|||||||
await clearTokens();
|
await clearTokens();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return UpdateUser(first_name, second_name, birth_date);
|
return updateUser(first_name, second_name, birth_date);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!response.ok) return null;
|
if (!response.ok) return null;
|
||||||
@@ -165,7 +165,7 @@ export async function UpdateUser(first_name: string, second_name: string, birth_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function Register(email: string, password: string, first_name: string, second_name: string, sex: string): Promise<{ success: boolean; redirectURL?: string; expired?: boolean; message?: string }> {
|
export async function registerUser(email: string, password: string, first_name: string, second_name: string, sex: string): Promise<{ success: boolean; redirectURL?: string; expired?: boolean; message?: string }> {
|
||||||
const t = await getTranslations("errors");
|
const t = await getTranslations("errors");
|
||||||
if (!email || !password) return { success: false, message: t("allFieldsRequired") }
|
if (!email || !password) return { success: false, message: t("allFieldsRequired") }
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { Consent } from "@/types"
|
import { Consent } from "@/types"
|
||||||
import { cookies } from "next/headers"
|
import { cookies } from "next/headers"
|
||||||
|
|
||||||
export async function getConsents() {
|
export async function fetchConsents() {
|
||||||
const store = await cookies()
|
const store = await cookies()
|
||||||
const accessToken = store.get("access_token")?.value
|
const accessToken = store.get("access_token")?.value
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import type { OAuthSession } from "@/types";
|
import type { OAuthSession } from "@/types";
|
||||||
|
|
||||||
export async function getSession(token: string): Promise<OAuthSession | null> {
|
export async function fetchSession(token: string): Promise<OAuthSession | null> {
|
||||||
if (!token) return null;
|
if (!token) return null;
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
|
|||||||
@@ -8,176 +8,153 @@ async function getAccessToken(): Promise<string | null> {
|
|||||||
return store.get("access_token")?.value ?? null
|
return store.get("access_token")?.value ?? null
|
||||||
}
|
}
|
||||||
|
|
||||||
async function authHeaders(locale?: string): Promise<HeadersInit> {
|
async function getAuthHeaders(locale?: string): Promise<HeadersInit> {
|
||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
return {
|
return token
|
||||||
Authorization: `Bearer ${token}`,
|
? {
|
||||||
"Accept-Language": locale ?? "en",
|
Authorization: `Bearer ${token}`,
|
||||||
}
|
"Accept-Language": locale ?? "en",
|
||||||
|
}
|
||||||
|
: {}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getMyPositions(locale?: string): Promise<Position[]> {
|
async function handleJsonResponse<T>(response: Response): Promise<T | null> {
|
||||||
|
if (!response.ok) return null
|
||||||
|
return (await response.json()) as T
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSuccessResponse(response: Response): Promise<{ success: boolean }> {
|
||||||
|
return { success: response.ok }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchMyPositions(locale?: string): Promise<Position[]> {
|
||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
if (!token) return []
|
if (!token) return []
|
||||||
|
|
||||||
const response = await fetch(
|
const res = await fetch(
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/positions`,
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/positions`,
|
||||||
{ headers: await authHeaders(locale), cache: "no-store" }
|
{ headers: await getAuthHeaders(locale), cache: "no-store" }
|
||||||
)
|
)
|
||||||
|
|
||||||
if (!response.ok) return []
|
return (await handleJsonResponse<Position[]>(res)) ?? []
|
||||||
return (await response.json()) as Position[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listAllPositions(locale?: string): Promise<Position[] | null> {
|
export async function fetchAllPositions(locale?: string): Promise<Position[] | null> {
|
||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
if (!token) return null
|
if (!token) return null
|
||||||
|
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`,
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`,
|
||||||
{ headers: await authHeaders(locale), cache: "no-store" }
|
{ headers: await getAuthHeaders(locale), cache: "no-store" }
|
||||||
)
|
)
|
||||||
|
|
||||||
if (response.status === 403) return null
|
if (response.status === 403) return null
|
||||||
if (!response.ok) return null
|
return await handleJsonResponse<Position[]>(response)
|
||||||
return (await response.json()) as Position[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function upsertPosition(
|
export async function savePosition(
|
||||||
code: string,
|
code: string,
|
||||||
name: string,
|
name: string,
|
||||||
locale: 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: { ...(await authHeaders(locale)), "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
return { success: response.ok }
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createPermission(
|
|
||||||
code: string,
|
|
||||||
description?: string
|
description?: string
|
||||||
): Promise<{ success: boolean }> {
|
): Promise<{ success: boolean }> {
|
||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
if (!token) return { success: false }
|
if (!token) return { success: false }
|
||||||
|
|
||||||
const response = await fetch(
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, {
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`,
|
method: "POST",
|
||||||
{
|
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
|
||||||
method: "POST",
|
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
|
||||||
headers: {
|
})
|
||||||
...(await authHeaders()),
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
code,
|
|
||||||
...(description ? { description } : {}),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
return { success: response.ok }
|
return handleSuccessResponse(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updatePermission(
|
export async function fetchAllPermissions(): Promise<Permission[]> {
|
||||||
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()
|
const token = await getAccessToken()
|
||||||
if (!token) return []
|
if (!token) return []
|
||||||
|
|
||||||
const response = await fetch(
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, {
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`,
|
headers: await getAuthHeaders(),
|
||||||
{ headers: await authHeaders(), cache: "no-store" }
|
cache: "no-store",
|
||||||
)
|
})
|
||||||
|
|
||||||
if (!response.ok) return []
|
return (await handleJsonResponse<Permission[]>(res)) ?? []
|
||||||
return (await response.json()) as Permission[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function addPermissionToPosition(
|
export async function addPermission(code: string, description?: string): Promise<{ success: boolean }> {
|
||||||
|
const token = await getAccessToken()
|
||||||
|
if (!token) return { success: false }
|
||||||
|
|
||||||
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ code, ...(description ? { description } : {}) }),
|
||||||
|
})
|
||||||
|
|
||||||
|
return handleSuccessResponse(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function editPermission(code: string, description?: string): Promise<{ success: boolean }> {
|
||||||
|
const token = await getAccessToken()
|
||||||
|
if (!token) return { success: false }
|
||||||
|
|
||||||
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ ...(description ? { description } : {}) }),
|
||||||
|
})
|
||||||
|
|
||||||
|
return handleSuccessResponse(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removePermission(code: string): Promise<{ success: boolean }> {
|
||||||
|
const token = await getAccessToken()
|
||||||
|
if (!token) return { success: false }
|
||||||
|
|
||||||
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: await getAuthHeaders(),
|
||||||
|
})
|
||||||
|
|
||||||
|
return handleSuccessResponse(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function attachPermissionToPosition(
|
||||||
positionCode: string,
|
positionCode: string,
|
||||||
permissionCode: string
|
permissionCode: string
|
||||||
): Promise<{ success: boolean }> {
|
): Promise<{ success: boolean }> {
|
||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
if (!token) return { success: false }
|
if (!token) return { success: false }
|
||||||
|
|
||||||
const response = await fetch(
|
const res = await fetch(
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions`,
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { ...(await authHeaders()), "Content-Type": "application/json" },
|
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ permission_code: permissionCode }),
|
body: JSON.stringify({ permission_code: permissionCode }),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
return { success: response.ok }
|
return handleSuccessResponse(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function removePermissionFromPosition(
|
export async function detachPermissionFromPosition(
|
||||||
positionCode: string,
|
positionCode: string,
|
||||||
permissionCode: string
|
permissionCode: string
|
||||||
): Promise<{ success: boolean }> {
|
): Promise<{ success: boolean }> {
|
||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
if (!token) return { success: false }
|
if (!token) return { success: false }
|
||||||
|
|
||||||
const response = await fetch(
|
const res = await fetch(
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions/${permissionCode}`,
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions/${permissionCode}`,
|
||||||
{ method: "DELETE", headers: await authHeaders() }
|
{ method: "DELETE", headers: await getAuthHeaders() }
|
||||||
)
|
)
|
||||||
|
|
||||||
return { success: response.ok }
|
return handleSuccessResponse(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function assignPosition(
|
export async function assignPositionToUser(
|
||||||
userId: string,
|
userId: string,
|
||||||
positionCode: string,
|
positionCode: string,
|
||||||
validFrom?: string,
|
validFrom?: string,
|
||||||
@@ -186,11 +163,11 @@ export async function assignPosition(
|
|||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
if (!token) return { success: false }
|
if (!token) return { success: false }
|
||||||
|
|
||||||
const response = await fetch(
|
const res = await fetch(
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions`,
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { ...(await authHeaders()), "Content-Type": "application/json" },
|
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
position_code: positionCode,
|
position_code: positionCode,
|
||||||
...(validFrom ? { valid_from: validFrom } : {}),
|
...(validFrom ? { valid_from: validFrom } : {}),
|
||||||
@@ -199,20 +176,55 @@ export async function assignPosition(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
return { success: response.ok }
|
return handleSuccessResponse(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function revokePosition(
|
export async function revokePositionFromUser(userId: string, positionCode: string): Promise<{ success: boolean }> {
|
||||||
userId: string,
|
|
||||||
positionCode: string
|
|
||||||
): Promise<{ success: boolean }> {
|
|
||||||
const token = await getAccessToken()
|
const token = await getAccessToken()
|
||||||
if (!token) return { success: false }
|
if (!token) return { success: false }
|
||||||
|
|
||||||
const response = await fetch(
|
const res = await fetch(
|
||||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions/${positionCode}`,
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions/${positionCode}`,
|
||||||
{ method: "DELETE", headers: await authHeaders() }
|
{ method: "DELETE", headers: await getAuthHeaders() }
|
||||||
)
|
)
|
||||||
|
|
||||||
return { success: response.ok }
|
return handleSuccessResponse(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addPosition(code: string, name: string, description?: string): Promise<{ success: boolean }> {
|
||||||
|
const token = await getAccessToken()
|
||||||
|
if (!token) return { success: false }
|
||||||
|
|
||||||
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
|
||||||
|
})
|
||||||
|
|
||||||
|
return handleSuccessResponse(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function editPosition(code: string, name: string, description?: string): Promise<{ success: boolean }> {
|
||||||
|
const token = await getAccessToken()
|
||||||
|
if (!token) return { success: false }
|
||||||
|
|
||||||
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${code}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name, ...(description ? { description } : {}) }),
|
||||||
|
})
|
||||||
|
|
||||||
|
return handleSuccessResponse(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePosition(code: string): Promise<{ success: boolean }> {
|
||||||
|
const token = await getAccessToken()
|
||||||
|
if (!token) return { success: false }
|
||||||
|
|
||||||
|
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${code}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: await getAuthHeaders(),
|
||||||
|
})
|
||||||
|
|
||||||
|
return handleSuccessResponse(res)
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,7 @@ import { Spinner } from "@/components/ui/spinner";
|
|||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useSearchParams } from "next/navigation";
|
import { useSearchParams } from "next/navigation";
|
||||||
import { getSession, Approve } from "@/actions/oauth";
|
import { fetchSession, Approve } from "@/actions/oauth";
|
||||||
import { Check } from "lucide-react";
|
import { Check } from "lucide-react";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
@@ -26,7 +26,7 @@ export default function ConsentPage() {
|
|||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getSession(sessionToken)
|
fetchSession(sessionToken)
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (!data) throw new Error();
|
if (!data) throw new Error();
|
||||||
setSession(data);
|
setSession(data);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import Header from "@/components/header";
|
import Header from "@/components/header";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import type { Consent, User } from "@/types";
|
import type { Consent, Permission, Position, User } from "@/types";
|
||||||
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, ShieldIcon, UserIcon } from "lucide-react";
|
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, ShieldIcon, UserIcon } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
@@ -16,25 +16,30 @@ import Admin from "./items/admin";
|
|||||||
interface Props {
|
interface Props {
|
||||||
userData: User | null;
|
userData: User | null;
|
||||||
consentsData: Consent[] | null;
|
consentsData: Consent[] | null;
|
||||||
|
permissionsData: Permission[] | null;
|
||||||
|
positionsData: Position[] | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function MeClient({ userData, consentsData }: Props) {
|
export default function MeClient({ userData, consentsData, permissionsData, positionsData }: Props) {
|
||||||
const t = useTranslations("MePage");
|
const t = useTranslations("MePage");
|
||||||
|
|
||||||
const [user, setUser] = useState(userData);
|
const [user, setUser] = useState(userData);
|
||||||
const [consents, setConsents] = useState(consentsData)
|
const [consents, setConsents] = useState(consentsData);
|
||||||
|
const [permissions, setPermissions] = useState(permissionsData);
|
||||||
|
const [positions, setPositions] = useState(positionsData);
|
||||||
const [selectedItem, setSelectedItem] = useState(0);
|
const [selectedItem, setSelectedItem] = useState(0);
|
||||||
|
|
||||||
|
|
||||||
const baseItems = [
|
const baseItems = [
|
||||||
{ name: t("items.profile.title"), icon: <UserIcon />, component: <Profile user={user} setUser={setUser} /> },
|
{ name: t("items.profile.title"), icon: <UserIcon />, component: <Profile user={user} setUser={setUser} /> },
|
||||||
{ name: t("items.applications.title"), icon: <AppWindowMacIcon />, component: <Applications consents={consents} setConsents={setConsents} /> },
|
{ name: t("items.applications.title"), icon: <AppWindowMacIcon />, component: <Applications consents={consents} setConsents={setConsents} /> },
|
||||||
{ name: t("items.positions.title"), icon: <BriefcaseBusinessIcon />, component: <Positions /> },
|
// { name: t("items.positions.title"), icon: <BriefcaseBusinessIcon />, component: <Positions /> },
|
||||||
]
|
]
|
||||||
|
|
||||||
const adminItem = user?.is_admin
|
const adminItem = user?.is_admin
|
||||||
? [{ name: t("items.admin.title"), icon: <ShieldIcon />, component: <Admin /> }]
|
? [{ name: t("items.admin.title"), icon: <ShieldIcon />, component: <Admin permissions={permissions} setPermissions={setPermissions} positions={positions} setPositions={setPositions} /> }]
|
||||||
: []
|
: [];
|
||||||
|
|
||||||
|
|
||||||
const items = [...baseItems, ...adminItem]
|
const items = [...baseItems, ...adminItem]
|
||||||
|
|
||||||
|
|||||||
@@ -1,43 +1,28 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useEffect, useState } from "react"
|
import { useTranslations } from "next-intl"
|
||||||
import { useLocale, useTranslations } from "next-intl"
|
import type { Permission, Position } from "@/types"
|
||||||
import type { Position } from "@/types"
|
|
||||||
import { Spinner } from "@/components/ui/spinner"
|
|
||||||
import { getMyPositions } from "@/actions/positions"
|
|
||||||
import Permissions from "./admin/permissions"
|
import Permissions from "./admin/permissions"
|
||||||
// import Positions from "./admin/positions"
|
import Positions from "./admin/positions";
|
||||||
|
|
||||||
export default function Admin() {
|
interface Props {
|
||||||
|
permissions: Permission[] | null;
|
||||||
|
setPermissions: React.Dispatch<React.SetStateAction<Permission[] | null>>;
|
||||||
|
|
||||||
|
positions: Position[] | null;
|
||||||
|
setPositions: React.Dispatch<React.SetStateAction<Position[] | null>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Admin({ permissions, setPermissions, positions, setPositions }: Props) {
|
||||||
const t = useTranslations("MePage.items.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 (
|
return (
|
||||||
<div className="w-full lg:max-w-xl flex flex-col gap-6">
|
<div className="w-full lg:max-w-xl flex flex-col gap-6">
|
||||||
<h1 className="text-xl">{t("title")}</h1>
|
<h1 className="text-xl">{t("title")}</h1>
|
||||||
|
<div className="space-y-8">
|
||||||
{loading && (
|
<Permissions permissions={permissions} setPermissions={setPermissions} />
|
||||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
<Positions positions={positions} setPositions={setPositions} />
|
||||||
<Spinner />
|
</div>
|
||||||
<span>{t("loading")}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!loading && (
|
|
||||||
<div className="space-y-8">
|
|
||||||
<Permissions />
|
|
||||||
{/* <Positions /> */}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
"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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
"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,107 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useForm, SubmitHandler } from "react-hook-form";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { addPermission, editPermission } from "@/actions/positions";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Check, X } from "lucide-react";
|
||||||
|
import type { Permission } from "@/types";
|
||||||
|
|
||||||
|
interface CreateProps {
|
||||||
|
mode: "create";
|
||||||
|
trigger: React.ReactNode;
|
||||||
|
onSuccess: (permission: Permission) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EditProps {
|
||||||
|
mode: "edit";
|
||||||
|
permission: Permission;
|
||||||
|
trigger: React.ReactNode;
|
||||||
|
onSuccess: (permission: Permission) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = CreateProps | EditProps;
|
||||||
|
|
||||||
|
interface FormData {
|
||||||
|
code: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PermissionDialog(props: Props) {
|
||||||
|
const t = useTranslations("MePage.items.admin.permissions")
|
||||||
|
const isEdit = props.mode === "edit"
|
||||||
|
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const { register, handleSubmit, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||||
|
defaultValues: isEdit ? { code: props.permission.code, description: props.permission.description ?? "" } : { code: "", description: "" },
|
||||||
|
})
|
||||||
|
|
||||||
|
function handleOpenChange(o: boolean) {
|
||||||
|
setOpen(o)
|
||||||
|
if (!o) reset(isEdit ? { code: props.permission.code, description: props.permission.description ?? "" } : { code: "", description: "" })
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||||
|
const result = isEdit
|
||||||
|
? await editPermission((props as EditProps).permission.code, data.description || undefined)
|
||||||
|
: await addPermission(data.code, data.description || undefined)
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
toast(isEdit ? t("edit.error") : t("create.error"), { icon: <X size={16} /> })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated: Permission = isEdit
|
||||||
|
? { ...(props as EditProps).permission, description: data.description }
|
||||||
|
: { id: crypto.randomUUID(), code: data.code, description: data.description, created_at: new Date().toISOString() }
|
||||||
|
|
||||||
|
toast(isEdit ? t("edit.success") : t("create.success"), { icon: <Check size={16} /> })
|
||||||
|
props.onSuccess(updated)
|
||||||
|
reset()
|
||||||
|
setOpen(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogTrigger asChild>{props.trigger}</DialogTrigger>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{isEdit ? t("edit.title") : t("create.title")}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<FieldGroup>
|
||||||
|
<Field data-invalid={!!errors.code}>
|
||||||
|
<FieldLabel htmlFor="code">{isEdit ? t("edit.code") : t("create.code")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="code"
|
||||||
|
disabled={isEdit || isSubmitting}
|
||||||
|
aria-invalid={!!errors.code}
|
||||||
|
{...register("code", { validate: (v) => isEdit || v.trim().length > 0 || t("create.codeRequired") })}
|
||||||
|
/>
|
||||||
|
{errors.code && <FieldError>{errors.code.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="description">{isEdit ? t("edit.description") : t("create.description")}</FieldLabel>
|
||||||
|
<Input id="description" disabled={isSubmitting} {...register("description")} />
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
<DialogFooter className="mt-4">
|
||||||
|
<DialogClose asChild>
|
||||||
|
<Button variant="outline" type="button">{isEdit ? t("edit.cancel") : t("create.cancel")}</Button>
|
||||||
|
</DialogClose>
|
||||||
|
<Button type="submit" disabled={isSubmitting}>
|
||||||
|
{isSubmitting && <Spinner />}
|
||||||
|
{isEdit ? t("edit.save") : t("create.save")}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useForm, SubmitHandler } from "react-hook-form";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { addPosition, editPosition } from "@/actions/positions";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Check, X } from "lucide-react";
|
||||||
|
import type { Position } from "@/types";
|
||||||
|
|
||||||
|
interface CreateProps {
|
||||||
|
mode: "create";
|
||||||
|
trigger: React.ReactNode;
|
||||||
|
onSuccess: (position: Position) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EditProps {
|
||||||
|
mode: "edit";
|
||||||
|
position: Position;
|
||||||
|
trigger: React.ReactNode;
|
||||||
|
onSuccess: (position: Position) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = CreateProps | EditProps;
|
||||||
|
|
||||||
|
interface FormData {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PositionDialog(props: Props) {
|
||||||
|
const t = useTranslations("MePage.items.admin.positions")
|
||||||
|
const isEdit = props.mode === "edit"
|
||||||
|
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const { register, handleSubmit, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||||
|
defaultValues: isEdit
|
||||||
|
? { code: props.position.code, name: props.position.name, description: props.position.description ?? "" }
|
||||||
|
: { code: "", name: "", description: "" },
|
||||||
|
})
|
||||||
|
|
||||||
|
function handleOpenChange(o: boolean) {
|
||||||
|
setOpen(o)
|
||||||
|
if (!o) {
|
||||||
|
reset(isEdit
|
||||||
|
? { code: props.position.code, name: props.position.name, description: props.position.description ?? "" }
|
||||||
|
: { code: "", name: "", description: "" }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||||
|
const result = isEdit
|
||||||
|
? await editPosition((props as EditProps).position.code, data.name, data.description || undefined)
|
||||||
|
: await addPosition(data.code, data.name, data.description || undefined)
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
toast(isEdit ? t("edit.error") : t("create.error"), { icon: <X size={16} /> })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated: Position = isEdit
|
||||||
|
? { ...(props as EditProps).position, name: data.name, description: data.description }
|
||||||
|
: { code: data.code, name: data.name, description: data.description, permissions: [] }
|
||||||
|
|
||||||
|
toast(isEdit ? t("edit.success") : t("create.success"), { icon: <Check size={16} /> })
|
||||||
|
props.onSuccess(updated)
|
||||||
|
reset()
|
||||||
|
setOpen(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogTrigger asChild>{props.trigger}</DialogTrigger>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{isEdit ? t("edit.title") : t("create.title")}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<FieldGroup>
|
||||||
|
<Field data-invalid={!!errors.code}>
|
||||||
|
<FieldLabel htmlFor="code">{isEdit ? t("edit.code") : t("create.code")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="code"
|
||||||
|
disabled={isEdit || isSubmitting}
|
||||||
|
aria-invalid={!!errors.code}
|
||||||
|
{...register("code", { validate: (v) => isEdit || v.trim().length > 0 || t("create.codeRequired") })}
|
||||||
|
/>
|
||||||
|
{errors.code && <FieldError>{errors.code.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
<Field data-invalid={!!errors.name}>
|
||||||
|
<FieldLabel htmlFor="name">{isEdit ? t("edit.name") : t("create.name")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.name}
|
||||||
|
{...register("name", { validate: (v) => v.trim().length > 0 || t("create.nameRequired") })}
|
||||||
|
/>
|
||||||
|
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="description">{isEdit ? t("edit.description") : t("create.description")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="description"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
{...register("description")}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
<DialogFooter className="mt-6">
|
||||||
|
<DialogClose asChild>
|
||||||
|
<Button variant="outline">{t("create.cancel") || t("edit.cancel")}</Button>
|
||||||
|
</DialogClose>
|
||||||
|
<Button type="submit" disabled={isSubmitting}>
|
||||||
|
{isSubmitting && <Spinner className="mr-2 size-4" />}
|
||||||
|
{isEdit ? t("edit.save") : t("create.save")}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,87 +1,96 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, useEffect, useMemo } from "react";
|
import { useTranslations } from "next-intl";
|
||||||
import { Button } from "@/components/ui/button"
|
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 { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||||
import { MoreHorizontalIcon } from "lucide-react"
|
import { MoreHorizontalIcon } from "lucide-react";
|
||||||
import CreatePermissionDialog from "./dialogs/createPermissionDialog";
|
import { Check, X } from "lucide-react";
|
||||||
import { Permission } from "@/types";
|
import { toast } from "sonner";
|
||||||
import { deletePermission, listAllPermissions } from "@/actions/positions";
|
import { PermissionDialog } from "./dialogs/permissionDialog";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { removePermission } from "@/actions/positions";
|
||||||
import EditPermissionDialog from "./dialogs/editPermissionDialog";
|
import type { Permission } from "@/types";
|
||||||
|
|
||||||
export default function Permissions() {
|
interface Props {
|
||||||
const [permissions, setPermissions] = useState<Permission[]>([]);
|
permissions: Permission[] | null;
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
setPermissions: React.Dispatch<React.SetStateAction<Permission[] | null>>;
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
export default function Permissions({ permissions, setPermissions }: Props) {
|
||||||
async function load() {
|
const t = useTranslations("MePage.items.admin.permissions")
|
||||||
const data = await listAllPermissions();
|
const pt = useTranslations("permissions")
|
||||||
setPermissions(data);
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
load()
|
function handleCreated(permission: Permission) {
|
||||||
}, [])
|
setPermissions((prev) => [...(prev || []), permission])
|
||||||
|
}
|
||||||
|
|
||||||
const permissionsMemo = useMemo(() => permissions, [permissions]);
|
function handleUpdated(code: string, permission: Permission) {
|
||||||
|
setPermissions((prev) => (prev || []).map((p) => (p.code === code ? permission : p)))
|
||||||
|
}
|
||||||
|
|
||||||
async function handleDelete(code: string) {
|
async function handleDelete(code: string) {
|
||||||
const result = await deletePermission(code)
|
const result = await removePermission(code)
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
setPermissions((prev) =>
|
setPermissions((prev) => (prev || []).filter((p) => p.code !== code))
|
||||||
prev.filter((p) => p.code !== code)
|
toast(t("delete.success"), { icon: <Check size={16} /> })
|
||||||
)
|
} else {
|
||||||
|
toast(t("delete.error"), { icon: <X size={16} /> })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<h2 className="text-lg">Permissions</h2>
|
<h2 className="text-lg">{t("title")}</h2>
|
||||||
<h4 className="text-sm text-muted-foreground">Here You can create permissions which later You can assign them to positions</h4>
|
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||||
</div>
|
</div>
|
||||||
<Card size="sm" className="w-full">
|
<Table>
|
||||||
<Table>
|
<TableHeader className="rounded-lg">
|
||||||
<TableHeader>
|
<TableRow>
|
||||||
|
<TableHead>{t("columns.code")}</TableHead>
|
||||||
|
<TableHead>{t("columns.description")}</TableHead>
|
||||||
|
<TableHead className="text-right">{t("columns.actions")}</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{permissions?.length === 0 && (
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableHead>Code</TableHead>
|
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
|
||||||
<TableHead>Description</TableHead>
|
|
||||||
<TableHead className="text-right">Actions</TableHead>
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
)}
|
||||||
<TableBody>
|
{permissions?.map((permission) => (
|
||||||
{permissionsMemo.map((permission) => (
|
|
||||||
<TableRow key={permission.code}>
|
<TableRow key={permission.code}>
|
||||||
<TableCell>{permission.code}</TableCell>
|
<TableCell className="font-mono">{permission.code}</TableCell>
|
||||||
<TableCell>{permission.description}</TableCell>
|
<TableCell className="text-muted-foreground">{pt(`${permission.code}`)}</TableCell>
|
||||||
<TableCell className="text-right">
|
<TableCell className="text-right">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="ghost" size="icon" className="size-8">
|
<Button variant="ghost" size="icon" className="size-8">
|
||||||
<MoreHorizontalIcon />
|
<MoreHorizontalIcon />
|
||||||
<span className="sr-only">Open menu</span>
|
<span className="sr-only">{t("columns.actions")}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<EditPermissionDialog permission={permission} />
|
<PermissionDialog
|
||||||
|
mode="edit"
|
||||||
|
permission={permission}
|
||||||
|
onSuccess={(updated) => handleUpdated(permission.code, updated)}
|
||||||
|
trigger={<Button variant="ghost" size="sm" className="w-full px-2 justify-start">{t("actions.edit")}</Button>}
|
||||||
|
/>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(permission.code)}>Delete</DropdownMenuItem>
|
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(permission.code)}>{t("actions.delete")}</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
{isLoading && <p className="mx-2 my-1 text-muted-foreground animate-pulse">Permissions are loading...</p>}
|
</Table>
|
||||||
</Table>
|
<PermissionDialog
|
||||||
<CardFooter>
|
mode="create"
|
||||||
<CreatePermissionDialog />
|
onSuccess={handleCreated}
|
||||||
</CardFooter>
|
trigger={<Button variant="outline" size="sm" className="w-full">{t("actions.create")}</Button>}
|
||||||
</Card>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||||
|
import { MoreHorizontalIcon } from "lucide-react";
|
||||||
|
import { Check, X } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { PositionDialog } from "./dialogs/positionDialog";
|
||||||
|
import { deletePosition } from "@/actions/positions";
|
||||||
|
import type { Position } from "@/types";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
positions: Position[] | null;
|
||||||
|
setPositions: React.Dispatch<React.SetStateAction<Position[] | null>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Positions({ positions, setPositions }: Props) {
|
||||||
|
const t = useTranslations("MePage.items.admin.positions")
|
||||||
|
|
||||||
|
function handleCreated(position: Position) {
|
||||||
|
setPositions((prev) => [...(prev || []), position])
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleUpdated(code: string, position: Position) {
|
||||||
|
setPositions((prev) => (prev || []).map((p) => (p.code === code ? position : p)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(code: string) {
|
||||||
|
const result = await deletePosition(code)
|
||||||
|
if (result.success) {
|
||||||
|
setPositions((prev) => (prev || []).filter((p) => p.code !== code))
|
||||||
|
toast(t("delete.success"), { icon: <Check size={16} /> })
|
||||||
|
} else {
|
||||||
|
toast(t("delete.error"), { icon: <X size={16} /> })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<h2 className="text-lg">{t("title")}</h2>
|
||||||
|
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||||
|
</div>
|
||||||
|
<Table>
|
||||||
|
<TableHeader className="rounded-lg">
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>{t("columns.code")}</TableHead>
|
||||||
|
<TableHead>{t("columns.name")}</TableHead>
|
||||||
|
<TableHead>{t("columns.description")}</TableHead>
|
||||||
|
<TableHead className="text-right">{t("columns.actions")}</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{positions?.length === 0 && (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={4} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
{positions?.map((position) => (
|
||||||
|
<TableRow key={position.code}>
|
||||||
|
<TableCell className="font-mono">{position.code}</TableCell>
|
||||||
|
<TableCell>{position.name}</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">{position.description || t("noDescription")}</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon" className="size-8">
|
||||||
|
<MoreHorizontalIcon />
|
||||||
|
<span className="sr-only">{t("columns.actions")}</span>
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<PositionDialog
|
||||||
|
mode="edit"
|
||||||
|
position={position}
|
||||||
|
onSuccess={(updated) => handleUpdated(position.code, updated)}
|
||||||
|
trigger={<Button variant="ghost" size="sm" className="w-full px-2 justify-start">{t("actions.edit")}</Button>}
|
||||||
|
/>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(position.code)}>{t("actions.delete")}</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
<PositionDialog
|
||||||
|
mode="create"
|
||||||
|
onSuccess={handleCreated}
|
||||||
|
trigger={<Button variant="outline" size="sm" className="w-full">{t("actions.create")}</Button>}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -49,8 +49,10 @@ export default function Applications({ consents, setConsents }: Props) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full lg:max-w-sm 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>
|
<div className="space-y-2">
|
||||||
|
<h1 className="text-xl">{t("title")}</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||||
|
</div>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{list?.map((consent) => (
|
{list?.map((consent) => (
|
||||||
<Item key={consent.client_id}>
|
<Item key={consent.client_id}>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import type { Position } from "@/types"
|
|||||||
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"
|
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Spinner } from "@/components/ui/spinner"
|
import { Spinner } from "@/components/ui/spinner"
|
||||||
import { getMyPositions } from "@/actions/positions"
|
import { fetchMyPositions } from "@/actions/positions"
|
||||||
|
|
||||||
export default function Positions() {
|
export default function Positions() {
|
||||||
const t = useTranslations("MePage.items.positions")
|
const t = useTranslations("MePage.items.positions")
|
||||||
@@ -16,7 +16,7 @@ export default function Positions() {
|
|||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getMyPositions(locale)
|
fetchMyPositions(locale)
|
||||||
.then(setPositions)
|
.then(setPositions)
|
||||||
.finally(() => setLoading(false))
|
.finally(() => setLoading(false))
|
||||||
}, [locale])
|
}, [locale])
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
import { BirthdatePicker } from "@/components/ui/birthdate-picker";
|
import { BirthdatePicker } from "@/components/ui/birthdate-picker";
|
||||||
import { UpdateUser } from "@/actions/auth";
|
import { updateUser } from "@/actions/auth";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Check, X } from "lucide-react";
|
import { Check, X } from "lucide-react";
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ export default function Profile({ user, setUser }: Props) {
|
|||||||
|
|
||||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||||
try {
|
try {
|
||||||
const response = await UpdateUser(data.first_name, data.second_name, data.birth_date);
|
const response = await updateUser(data.first_name, data.second_name, data.birth_date);
|
||||||
|
|
||||||
if (response == null) toast(t("form.updateError"), { icon: <X size={16} /> })
|
if (response == null) toast(t("form.updateError"), { icon: <X size={16} /> })
|
||||||
else {
|
else {
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
import { GetUser } from "@/actions/auth";
|
import { fetchUser } from "@/actions/auth";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import MeComponent from "./component";
|
import MeComponent from "./component";
|
||||||
import { getConsents } from "@/actions/consents";
|
import { fetchConsents } from "@/actions/consents";
|
||||||
|
import { fetchAllPositions, fetchAllPermissions } from "@/actions/positions";
|
||||||
|
|
||||||
export default async function Me() {
|
export default async function Me() {
|
||||||
const user = await GetUser();
|
const user = await fetchUser();
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
redirect("/api/auth/initiate");
|
redirect("/api/auth/initiate");
|
||||||
}
|
}
|
||||||
|
|
||||||
const consents = await getConsents();
|
const consents = await fetchConsents();
|
||||||
|
const permissions = user.is_admin ? await fetchAllPermissions() : null;
|
||||||
|
const positions = user.is_admin ? await fetchAllPositions() : null;
|
||||||
|
|
||||||
return <MeComponent userData={user} consentsData={consents} />;
|
return <MeComponent userData={user} consentsData={consents} permissionsData={permissions} positionsData={positions} />;
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { getSession } from "@/actions/oauth";
|
import { fetchSession } from "@/actions/oauth";
|
||||||
import { isRedirectError } from "next/dist/client/components/redirect-error";
|
import { isRedirectError } from "next/dist/client/components/redirect-error";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
@@ -14,7 +14,7 @@ export default async function OAuthPage({
|
|||||||
const session = (await searchParams).session as string | undefined;
|
const session = (await searchParams).session as string | undefined;
|
||||||
if (!session) redirect("/oauth/error");
|
if (!session) redirect("/oauth/error");
|
||||||
|
|
||||||
const data = await getSession(session);
|
const data = await fetchSession(session);
|
||||||
if (!data) redirect("/oauth/error");
|
if (!data) redirect("/oauth/error");
|
||||||
|
|
||||||
const store = await cookies();
|
const store = await cookies();
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { Register } from "@/actions/auth";
|
|
||||||
import Header from "@/components/header";
|
import Header from "@/components/header";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
@@ -13,7 +12,8 @@ import { useRouter } from "next/navigation";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Sex } from "@/types";
|
import { Sex } from "@/types";
|
||||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { ArrowLeft, ArrowRight, Check } from "lucide-react";
|
import { ArrowLeft, ArrowRight } from "lucide-react";
|
||||||
|
import { registerUser } from "@/actions/auth";
|
||||||
|
|
||||||
interface FormData {
|
interface FormData {
|
||||||
email: string;
|
email: string;
|
||||||
@@ -34,7 +34,7 @@ export default function RegisterPage() {
|
|||||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
const result = await Register(data.email, data.password, data.first_name, data.second_name, data.sex);
|
const result = await registerUser(data.email, data.password, data.first_name, data.second_name, data.sex);
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
setError(result.message ?? null);
|
setError(result.message ?? null);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -38,7 +38,7 @@
|
|||||||
},
|
},
|
||||||
"sex": {
|
"sex": {
|
||||||
"title": "Sex",
|
"title": "Sex",
|
||||||
"select": "Specify Your sex",
|
"select": "Specify your sex",
|
||||||
"male": "Male",
|
"male": "Male",
|
||||||
"female": "Female"
|
"female": "Female"
|
||||||
},
|
},
|
||||||
@@ -66,7 +66,7 @@
|
|||||||
},
|
},
|
||||||
"birthdate": {
|
"birthdate": {
|
||||||
"title": "Date of birth",
|
"title": "Date of birth",
|
||||||
"pick": "Select Your date of birth"
|
"pick": "Select your date of birth"
|
||||||
},
|
},
|
||||||
"required": "This field is required",
|
"required": "This field is required",
|
||||||
"save": "Save",
|
"save": "Save",
|
||||||
@@ -76,40 +76,110 @@
|
|||||||
},
|
},
|
||||||
"applications": {
|
"applications": {
|
||||||
"title": "Applications",
|
"title": "Applications",
|
||||||
|
"subtitle": "Here you can review and revoke concents for connected applications.",
|
||||||
"authorized": "Autorized on",
|
"authorized": "Autorized on",
|
||||||
"revoke": "Revoke",
|
"revoke": "Revoke",
|
||||||
"successfullyRevoked": "Access successfully revoked!",
|
"successfullyRevoked": "Access successfully revoked!",
|
||||||
"revocationError": "Failed to revoke access"
|
"revocationError": "Failed to revoke access"
|
||||||
},
|
},
|
||||||
"positions": {
|
"positions": {
|
||||||
"title": "Positions",
|
"title": "Positions"
|
||||||
"loading": "Loading positions…",
|
|
||||||
"empty": "You don't have any positions yet.",
|
|
||||||
"noDescription": "No description",
|
|
||||||
"form": {
|
|
||||||
"title": "Manage positions",
|
|
||||||
"code": "Code",
|
|
||||||
"name": "Name",
|
|
||||||
"description": "Description",
|
|
||||||
"save": "Save",
|
|
||||||
"required": "Please fill in all required fields",
|
|
||||||
"saved": "Position saved successfully",
|
|
||||||
"saveError": "Failed to save position"
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"admin": {
|
"admin": {
|
||||||
"title": "Administration"
|
"title": "Administration",
|
||||||
|
"permissions": {
|
||||||
|
"title": "Permissions",
|
||||||
|
"subtitle": "Permissions can be assigned to positions to control access.",
|
||||||
|
"empty": "There're no permissions yet",
|
||||||
|
"noDescription": "No description",
|
||||||
|
"columns": {
|
||||||
|
"code": "Code",
|
||||||
|
"description": "Description",
|
||||||
|
"actions": "Actions"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "Edit",
|
||||||
|
"delete": "Delete",
|
||||||
|
"create": "Create permission"
|
||||||
|
},
|
||||||
|
"create": {
|
||||||
|
"title": "Create permission",
|
||||||
|
"code": "Code",
|
||||||
|
"description": "Description",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"save": "Save",
|
||||||
|
"codeRequired": "Code is required",
|
||||||
|
"success": "Permission successfully created!",
|
||||||
|
"error": "Failed to create permission"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Edit permission",
|
||||||
|
"code": "Code",
|
||||||
|
"description": "Description",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"save": "Update",
|
||||||
|
"success": "Permission successfully updated!",
|
||||||
|
"error": "Failed to update permission"
|
||||||
|
},
|
||||||
|
"delete": {
|
||||||
|
"success": "Permission successfully deleted!",
|
||||||
|
"error": "Failed to delete permission"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"positions": {
|
||||||
|
"title": "Positions",
|
||||||
|
"subtitle": "Manage positions and assign permissions to control access.",
|
||||||
|
"empty": "There're no positions yet",
|
||||||
|
"noDescription": "No description",
|
||||||
|
"columns": {
|
||||||
|
"code": "Code",
|
||||||
|
"name": "Name",
|
||||||
|
"description": "Description",
|
||||||
|
"actions": "Actions"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "Edit",
|
||||||
|
"delete": "Delete",
|
||||||
|
"create": "Create position"
|
||||||
|
},
|
||||||
|
"create": {
|
||||||
|
"title": "Create position",
|
||||||
|
"code": "Code",
|
||||||
|
"name": "Name",
|
||||||
|
"description": "Description",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"save": "Save",
|
||||||
|
"codeRequired": "Code is required",
|
||||||
|
"nameRequired": "Name is required",
|
||||||
|
"success": "Position successfully created!",
|
||||||
|
"error": "Failed to create position"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Edit position",
|
||||||
|
"code": "Code",
|
||||||
|
"name": "Name",
|
||||||
|
"description": "Description",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"save": "Update",
|
||||||
|
"success": "Position successfully updated!",
|
||||||
|
"error": "Failed to update position"
|
||||||
|
},
|
||||||
|
"delete": {
|
||||||
|
"success": "Position successfully deleted!",
|
||||||
|
"error": "Failed to delete position"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"logout": "Logout"
|
"logout": "Logout"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ConsentPage": {
|
"ConsentPage": {
|
||||||
"title": "Access to {service}",
|
"title": "Access to {service}",
|
||||||
"subtitle": "{service} wants to access Your Kotosoft ID account to:",
|
"subtitle": "{service} wants to access your Kotosoft ID account to:",
|
||||||
"invalidSession": "This session is invalid. Please go back to Your application and try again.",
|
"invalidSession": "This session is invalid. Please go back to your application and try again.",
|
||||||
"scopes": {
|
"scopes": {
|
||||||
"profile:read": "See information of Your profile",
|
"profile:read": "See information of your profile",
|
||||||
"profile:edit": "Edit information of Your profile"
|
"profile:edit": "Edit information of your profile"
|
||||||
},
|
},
|
||||||
"allow": "Allow",
|
"allow": "Allow",
|
||||||
"deny": "Deny",
|
"deny": "Deny",
|
||||||
@@ -121,6 +191,12 @@
|
|||||||
"dark": "Dark",
|
"dark": "Dark",
|
||||||
"system": "System"
|
"system": "System"
|
||||||
},
|
},
|
||||||
|
"permissions": {
|
||||||
|
"positions": {
|
||||||
|
"manage": "Create and edit positions",
|
||||||
|
"assign": "Assign positions to users"
|
||||||
|
}
|
||||||
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
"serverError": "Server error. Please try again later.",
|
"serverError": "Server error. Please try again later.",
|
||||||
"invalidCredentialsError": "Incorrect email or password",
|
"invalidCredentialsError": "Incorrect email or password",
|
||||||
|
|||||||
@@ -70,31 +70,104 @@
|
|||||||
},
|
},
|
||||||
"required": "Questo campo è obbligatorio",
|
"required": "Questo campo è obbligatorio",
|
||||||
"save": "Salva",
|
"save": "Salva",
|
||||||
"successfullyUpdated": "Il tuo profilo è aggiornato con successo!",
|
"successfullyUpdated": "Il tuo profilo è stato aggiornato con successo!",
|
||||||
"updateError": "Si è verificato un errore durante l'aggiornamento. Riprova più tardi."
|
"updateError": "Si è verificato un errore durante l'aggiornamento. Riprova più tardi."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"applications": {
|
"applications": {
|
||||||
"title": "Applicazioni",
|
"title": "Applicazioni",
|
||||||
|
"subtitle": "Qui puoi vedere e revocare i consensi per le applicazioni connesse.",
|
||||||
"authorized": "Autorizzato il",
|
"authorized": "Autorizzato il",
|
||||||
"revoke": "Revoca",
|
"revoke": "Revoca",
|
||||||
"successfullyRevoked": "Accesso all'applicazione revocato con successo!",
|
"successfullyRevoked": "Accesso all'applicazione revocato con successo!",
|
||||||
"revocationError": "Impossibile revocare l'accesso all'applicazione"
|
"revocationError": "Impossibile revocare l'accesso all'applicazione"
|
||||||
},
|
},
|
||||||
"positions": {
|
"positions": {
|
||||||
"title": "Posizioni",
|
"title": "Posizioni"
|
||||||
"loading": "Caricamento delle posizioni…",
|
},
|
||||||
"empty": "Non hai ancora posizioni assegnate.",
|
"admin": {
|
||||||
"noDescription": "Nessuna descrizione",
|
"title": "Amministrazione",
|
||||||
"form": {
|
"permissions": {
|
||||||
"title": "Gestione delle posizioni",
|
"title": "Permessi",
|
||||||
"code": "Codice posizione",
|
"subtitle": "I permessi possono essere assegnati alle posizioni per controllare l'accesso.",
|
||||||
"name": "Nome",
|
"empty": "Non ci sono permessi",
|
||||||
"description": "Descrizione",
|
"noDescription": "Senza descrizione",
|
||||||
"save": "Salva",
|
"columns": {
|
||||||
"required": "Compila tutti i campi obbligatori",
|
"code": "Codice",
|
||||||
"saved": "Posizione salvata con successo",
|
"description": "Descrizione",
|
||||||
"saveError": "Impossibile salvare la posizione"
|
"actions": "Azioni"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "Modifica",
|
||||||
|
"delete": "Elimina",
|
||||||
|
"create": "Crea permesso"
|
||||||
|
},
|
||||||
|
"create": {
|
||||||
|
"title": "Creazione del permesso",
|
||||||
|
"code": "Codice",
|
||||||
|
"description": "Descrizione",
|
||||||
|
"cancel": "Annulla",
|
||||||
|
"save": "Salva",
|
||||||
|
"codeRequired": "Il codice è obbligatorio",
|
||||||
|
"success": "Il permesso è stato creato con successo!",
|
||||||
|
"error": "Impossibile creare il permesso"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Modifica permesso",
|
||||||
|
"code": "Codice",
|
||||||
|
"description": "Descrizione",
|
||||||
|
"cancel": "Annulla",
|
||||||
|
"save": "Aggiorna",
|
||||||
|
"success": "Il permesso è stato aggiornato con successo!",
|
||||||
|
"error": "Impossibile aggiornare il permesso"
|
||||||
|
},
|
||||||
|
"delete": {
|
||||||
|
"success": "Il permesso è stato eliminato con successo!",
|
||||||
|
"error": "Impossibile eliminare il permesso"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"positions": {
|
||||||
|
"title": "Posizioni",
|
||||||
|
"subtitle": "Gestire le posizioni e assegnare i permessi per controllare l'accesso.",
|
||||||
|
"empty": "Non ci sono posizioni",
|
||||||
|
"noDescription": "Senza descrizione",
|
||||||
|
"columns": {
|
||||||
|
"code": "Codice",
|
||||||
|
"name": "Nome",
|
||||||
|
"description": "Descrizione",
|
||||||
|
"actions": "Azioni"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "Modifica",
|
||||||
|
"delete": "Elimina",
|
||||||
|
"create": "Crea posizione"
|
||||||
|
},
|
||||||
|
"create": {
|
||||||
|
"title": "Crea posizione",
|
||||||
|
"code": "Codice",
|
||||||
|
"name": "Nome",
|
||||||
|
"description": "Descrizione",
|
||||||
|
"cancel": "Annulla",
|
||||||
|
"save": "Salva",
|
||||||
|
"codeRequired": "Il codice è obbligatorio",
|
||||||
|
"nameRequired": "Il nome è obbligatorio",
|
||||||
|
"success": "La posizione è stata creata con successo!",
|
||||||
|
"error": "Impossibile creare la posizione"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Modifica posizione",
|
||||||
|
"code": "Codice",
|
||||||
|
"name": "Nome",
|
||||||
|
"description": "Descrizione",
|
||||||
|
"cancel": "Annulla",
|
||||||
|
"save": "Aggiorna",
|
||||||
|
"success": "La posizione è stata aggiornata con successo!",
|
||||||
|
"error": "Impossibile aggiornare la posizione"
|
||||||
|
},
|
||||||
|
"delete": {
|
||||||
|
"success": "La posizione è stata eliminata con successo!",
|
||||||
|
"error": "Impossibile eliminare la posizione"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"logout": "Esci"
|
"logout": "Esci"
|
||||||
@@ -118,6 +191,12 @@
|
|||||||
"dark": "Scuro",
|
"dark": "Scuro",
|
||||||
"system": "Sistema"
|
"system": "Sistema"
|
||||||
},
|
},
|
||||||
|
"permissions": {
|
||||||
|
"positions": {
|
||||||
|
"manage": "Crea e modifica posizioni",
|
||||||
|
"assign": "Assegna posizioni agli utenti"
|
||||||
|
}
|
||||||
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
"serverError": "Errore del server. Riprova più tardi.",
|
"serverError": "Errore del server. Riprova più tardi.",
|
||||||
"invalidCredentialsError": "Email o password non corretti",
|
"invalidCredentialsError": "Email o password non corretti",
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
},
|
},
|
||||||
"required": "Это поле является обязательным",
|
"required": "Это поле является обязательным",
|
||||||
"login": "Вход",
|
"login": "Вход",
|
||||||
"noAccountNote": "У Вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь <register>здесь</register>."
|
"noAccountNote": "У вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь <register>здесь</register>."
|
||||||
},
|
},
|
||||||
"RegisterPage":{
|
"RegisterPage":{
|
||||||
"title": "Регистрация в Kotosoft ID",
|
"title": "Регистрация в Kotosoft ID",
|
||||||
@@ -38,7 +38,7 @@
|
|||||||
},
|
},
|
||||||
"sex": {
|
"sex": {
|
||||||
"title": "Пол",
|
"title": "Пол",
|
||||||
"select": "Выберите Ваш пол",
|
"select": "Выберите ваш пол",
|
||||||
"male": "Мужской",
|
"male": "Мужской",
|
||||||
"female": "Женский"
|
"female": "Женский"
|
||||||
},
|
},
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
"next": "Дальше",
|
"next": "Дальше",
|
||||||
"back": "Назад",
|
"back": "Назад",
|
||||||
"register": "Зарегистрироваться",
|
"register": "Зарегистрироваться",
|
||||||
"hasAccountNote": "У Вас уже есть аккаунт в Kotosoft ID? Войти можно <login>тут</login>."
|
"hasAccountNote": "У вас уже есть аккаунт в Kotosoft ID? Войти можно <login>тут</login>."
|
||||||
},
|
},
|
||||||
"MePage": {
|
"MePage": {
|
||||||
"loadError": "Что-то пошло не так. Не получилось загрузить пользователя.",
|
"loadError": "Что-то пошло не так. Не получилось загрузить пользователя.",
|
||||||
@@ -66,7 +66,7 @@
|
|||||||
},
|
},
|
||||||
"birthdate": {
|
"birthdate": {
|
||||||
"title": "Дата рождения",
|
"title": "Дата рождения",
|
||||||
"pick": "Выберите Вашу дату рождения"
|
"pick": "Выберите вашу дату рождения"
|
||||||
},
|
},
|
||||||
"required": "Это поле является обязательным",
|
"required": "Это поле является обязательным",
|
||||||
"save": "Сохранить",
|
"save": "Сохранить",
|
||||||
@@ -76,25 +76,98 @@
|
|||||||
},
|
},
|
||||||
"applications": {
|
"applications": {
|
||||||
"title": "Приложения",
|
"title": "Приложения",
|
||||||
"authorized": "Авторизировано",
|
"subtitle": "Здесь вы можете просматривать и отзывать доступ приложений.",
|
||||||
|
"authorized": "Разрешено",
|
||||||
"revoke": "Отозвать",
|
"revoke": "Отозвать",
|
||||||
"successfullyRevoked": "Доступ приложения успешно отозван!",
|
"successfullyRevoked": "Доступ приложения успешно отозван!",
|
||||||
"revocationError": "Не удалось отозвать доступ приложения"
|
"revocationError": "Не удалось отозвать доступ приложения"
|
||||||
},
|
},
|
||||||
"positions": {
|
"positions": {
|
||||||
"title": "Должности",
|
"title": "Должности"
|
||||||
"loading": "Загружаем должности…",
|
},
|
||||||
"empty": "У вас пока нет назначенных должностей.",
|
"admin": {
|
||||||
"noDescription": "Без описания",
|
"title": "Администрирование",
|
||||||
"form": {
|
"permissions": {
|
||||||
"title": "Управление должностями",
|
"title": "Разрешения",
|
||||||
"code": "Код должности",
|
"subtitle": "Разрешения могут быть присвоены должностям для контроля прав доступа.",
|
||||||
"name": "Название",
|
"empty": "Разрешений пока нет",
|
||||||
"description": "Описание",
|
"noDescription": "Без описания",
|
||||||
"save": "Сохранить",
|
"columns": {
|
||||||
"required": "Заполните обязательные поля",
|
"code": "Код",
|
||||||
"saved": "Должность успешно сохранена",
|
"description": "Описание",
|
||||||
"saveError": "Не удалось сохранить должность"
|
"actions": "Действия"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "Изменить",
|
||||||
|
"delete": "Удалить",
|
||||||
|
"create": "Создать разрешение"
|
||||||
|
},
|
||||||
|
"create": {
|
||||||
|
"title": "Создать разрешение",
|
||||||
|
"code": "Код",
|
||||||
|
"description": "Описание",
|
||||||
|
"cancel": "Отмена",
|
||||||
|
"save": "Сохранить",
|
||||||
|
"codeRequired": "Код разрешения обязателен",
|
||||||
|
"success": "Разрешение успешно создано!",
|
||||||
|
"error": "Не удалось создать разрешение"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Редактирование разрешения",
|
||||||
|
"code": "Код",
|
||||||
|
"description": "Описание",
|
||||||
|
"cancel": "Отмена",
|
||||||
|
"save": "Сохранить",
|
||||||
|
"success": "Разрешение успешно обновлено!",
|
||||||
|
"error": "Не удалось обновить разрешение"
|
||||||
|
},
|
||||||
|
"delete": {
|
||||||
|
"success": "Разрешение успешно удалено!",
|
||||||
|
"error": "Не удалось удалить разрешение"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"positions": {
|
||||||
|
"title": "Должности",
|
||||||
|
"subtitle": "Управление должностями и назначение разрешений для контроля доступа.",
|
||||||
|
"empty": "Должностей пока нет",
|
||||||
|
"noDescription": "Без описания",
|
||||||
|
"columns": {
|
||||||
|
"code": "Код",
|
||||||
|
"name": "Название",
|
||||||
|
"description": "Описание",
|
||||||
|
"actions": "Действия"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "Изменить",
|
||||||
|
"delete": "Удалить",
|
||||||
|
"create": "Создать должность"
|
||||||
|
},
|
||||||
|
"create": {
|
||||||
|
"title": "Создать должность",
|
||||||
|
"code": "Код",
|
||||||
|
"name": "Название",
|
||||||
|
"description": "Описание",
|
||||||
|
"cancel": "Отмена",
|
||||||
|
"save": "Сохранить",
|
||||||
|
"codeRequired": "Код должности обязателен",
|
||||||
|
"nameRequired": "Название должности обязательно",
|
||||||
|
"success": "Должность успешно создана!",
|
||||||
|
"error": "Не удалось создать должность"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Редактирование должности",
|
||||||
|
"code": "Код",
|
||||||
|
"name": "Название",
|
||||||
|
"description": "Описание",
|
||||||
|
"cancel": "Отмена",
|
||||||
|
"save": "Сохранить",
|
||||||
|
"success": "Должность успешно обновлена!",
|
||||||
|
"error": "Не удалось обновить должность"
|
||||||
|
},
|
||||||
|
"delete": {
|
||||||
|
"success": "Должность успешно удалена!",
|
||||||
|
"error": "Не удалось удалить должность"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"logout": "Выйти"
|
"logout": "Выйти"
|
||||||
@@ -102,11 +175,11 @@
|
|||||||
},
|
},
|
||||||
"ConsentPage": {
|
"ConsentPage": {
|
||||||
"title": "Вход в {service}",
|
"title": "Вход в {service}",
|
||||||
"subtitle": "{service} хочет получить доступ к Вашему аккаунту Kotosoft ID, чтобы:",
|
"subtitle": "{service} хочет получить доступ к вашему аккаунту Kotosoft ID, чтобы:",
|
||||||
"invalidSession": "Эта сессия недействительна. Пожалуйста, вернитесь в своё приложение и попробуйте ещё раз.",
|
"invalidSession": "Эта сессия недействительна. Пожалуйста, вернитесь в своё приложение и попробуйте ещё раз.",
|
||||||
"scopes": {
|
"scopes": {
|
||||||
"profile:read": "Видеть данные Вашего профиля",
|
"profile:read": "Видеть данные вашего профиля",
|
||||||
"profile:edit": "Изменять данные в Вашем профиле"
|
"profile:edit": "Изменять данные в вашем профиле"
|
||||||
},
|
},
|
||||||
"allow": "Разрешить",
|
"allow": "Разрешить",
|
||||||
"deny": "Запретить",
|
"deny": "Запретить",
|
||||||
@@ -118,6 +191,12 @@
|
|||||||
"dark": "Тёмная",
|
"dark": "Тёмная",
|
||||||
"system": "Как в системе"
|
"system": "Как в системе"
|
||||||
},
|
},
|
||||||
|
"permissions": {
|
||||||
|
"positions": {
|
||||||
|
"manage": "Создание и редактирование должностей",
|
||||||
|
"assign": "Назначение должностей пользователям"
|
||||||
|
}
|
||||||
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
"serverError": "Ошибка сервера. Пожалуйста, попробуйте ещё раз позже.",
|
"serverError": "Ошибка сервера. Пожалуйста, попробуйте ещё раз позже.",
|
||||||
"invalidCredentialsError": "Неправильный адрес почты или пароль",
|
"invalidCredentialsError": "Неправильный адрес почты или пароль",
|
||||||
|
|||||||
Reference in New Issue
Block a user