diff --git a/kotosoft-id-backend/internal/handlers/positions.go b/kotosoft-id-backend/internal/handlers/positions.go index ee078de..b87590f 100644 --- a/kotosoft-id-backend/internal/handlers/positions.go +++ b/kotosoft-id-backend/internal/handlers/positions.go @@ -37,15 +37,6 @@ func userIDFromContext(c *gin.Context) (uuid.UUID, bool) { return id, ok } -func isAdminFromContext(c *gin.Context) bool { - v, ok := c.Get("is_admin") - if !ok { - return false - } - b, ok := v.(bool) - return ok && b -} - func (h *PositionsHandler) GetMyPositions(c *gin.Context) { userID, ok := userIDFromContext(c) if !ok { @@ -63,11 +54,6 @@ func (h *PositionsHandler) GetMyPositions(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)) if err != nil { c.Error(models.ErrInternal) @@ -84,11 +70,6 @@ type upsertPositionRequest struct { } func (h *PositionsHandler) UpsertPosition(c *gin.Context) { - if !isAdminFromContext(c) { - c.Error(models.ErrForbidden) - return - } - var req upsertPositionRequest if err := c.ShouldBindJSON(&req); err != nil { c.Error(models.ErrBadRequest) @@ -103,16 +84,38 @@ func (h *PositionsHandler) UpsertPosition(c *gin.Context) { c.Status(http.StatusNoContent) } +func (h *PositionsHandler) UpdatePosition(c *gin.Context) { + var req struct { + Name string `json:"name" binding:"required"` + Description *string `json:"description"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.Error(models.ErrBadRequest) + return + } + + if err := h.svc.UpsertPositionForLocale(c.Request.Context(), c.Param("code"), localeFromRequest(c), req.Name, req.Description); err != nil { + c.Error(models.ErrInternal) + return + } + + c.Status(http.StatusNoContent) +} + +func (h *PositionsHandler) DeletePosition(c *gin.Context) { + if err := h.svc.DeletePosition(c.Request.Context(), c.Param("code")); err != nil { + c.Error(err) + return + } + + c.Status(http.StatusNoContent) +} + type permissionCodeRequest struct { PermissionCode string `json:"permission_code" binding:"required"` } func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) { - if !isAdminFromContext(c) { - c.Error(models.ErrForbidden) - return - } - var req permissionCodeRequest if err := c.ShouldBindJSON(&req); err != nil { c.Error(models.ErrBadRequest) @@ -128,12 +131,7 @@ func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) { } func (h *PositionsHandler) RemovePermissionFromPosition(c *gin.Context) { - if !isAdminFromContext(c) { - c.Error(models.ErrForbidden) - return - } - - if err := h.svc.RemovePermissionFromPosition(c.Request.Context(), c.Param("code"), c.Param("permCode")); err != nil { + if err := h.svc.RemovePermissionFromPosition(c.Request.Context(), c.Param("code"), c.Param("permissionCode")); err != nil { c.Error(err) return } @@ -142,11 +140,6 @@ func (h *PositionsHandler) RemovePermissionFromPosition(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()) if err != nil { c.Error(models.ErrInternal) @@ -157,11 +150,6 @@ func (h *PositionsHandler) ListPermissions(c *gin.Context) { } func (h *PositionsHandler) AssignPosition(c *gin.Context) { - if !isAdminFromContext(c) { - c.Error(models.ErrForbidden) - return - } - adminID, ok := userIDFromContext(c) if !ok { c.Error(models.ErrUnauthorized) @@ -189,11 +177,6 @@ func (h *PositionsHandler) AssignPosition(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")) if err != nil { c.Error(models.ErrBadRequest) @@ -208,6 +191,50 @@ func (h *PositionsHandler) RevokePosition(c *gin.Context) { 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) { var req struct { Token string `json:"token" form:"token" binding:"required"` diff --git a/kotosoft-id-backend/internal/http/router.go b/kotosoft-id-backend/internal/http/router.go index 29d2ba3..6af9efc 100644 --- a/kotosoft-id-backend/internal/http/router.go +++ b/kotosoft-id-backend/internal/http/router.go @@ -22,6 +22,7 @@ func NewRouter( limiter *services.RateLimiter, ) *gin.Engine { r := gin.Default() + r.Use(middleware.LoggingMiddleware()) r.Use(errorMiddleware()) o := r.Group("/oauth") @@ -57,15 +58,19 @@ func NewRouter( me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess) me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions) - admin := api.Group("/admin", authMiddleware(svc, repo)) + admin := api.Group("/admin", authMiddleware(svc, repo), middleware.AdminOnly()) { 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.POST("/positions", positions.UpsertPosition) - + admin.PUT("/positions/:code", positions.UpdatePosition) + admin.DELETE("/positions/:code", positions.DeletePosition) 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.DELETE("/users/:userId/positions/:code", positions.RevokePosition) diff --git a/kotosoft-id-backend/internal/middleware/admin.go b/kotosoft-id-backend/internal/middleware/admin.go new file mode 100644 index 0000000..5d2a8be --- /dev/null +++ b/kotosoft-id-backend/internal/middleware/admin.go @@ -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() + } +} diff --git a/kotosoft-id-backend/internal/middleware/logging.go b/kotosoft-id-backend/internal/middleware/logging.go new file mode 100644 index 0000000..97dd13b --- /dev/null +++ b/kotosoft-id-backend/internal/middleware/logging.go @@ -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 "" +} diff --git a/kotosoft-id-backend/internal/repositories/positions.go b/kotosoft-id-backend/internal/repositories/positions.go index 7eae4e9..bbda5c5 100644 --- a/kotosoft-id-backend/internal/repositories/positions.go +++ b/kotosoft-id-backend/internal/repositories/positions.go @@ -39,6 +39,26 @@ func (r *PositionRepository) GetAllPermissions(ctx context.Context) ([]models.Pe 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) { var p models.Permission err := r.db.QueryRow(ctx, ` @@ -208,6 +228,11 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code, 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 { _, err := r.db.Exec(ctx, ` INSERT INTO user_positions (user_id, position_id, assigned_by, valid_from, valid_to) diff --git a/kotosoft-id-backend/internal/services/positions.go b/kotosoft-id-backend/internal/services/positions.go index 4d06dd1..bbba26f 100644 --- a/kotosoft-id-backend/internal/services/positions.go +++ b/kotosoft-id-backend/internal/services/positions.go @@ -61,6 +61,10 @@ func (s *Service) UpsertPositionForLocale(ctx context.Context, code, locale, nam return s.positions.UpsertPositionForLocale(ctx, code, locale, name, description) } +func (s *Service) DeletePosition(ctx context.Context, code string) error { + return s.positions.DeletePositionByCode(ctx, code) +} + func (s *Service) AssignPosition(ctx context.Context, adminID, targetUserID uuid.UUID, input models.AssignPositionInput) error { position, err := s.positions.GetPositionByCode(ctx, input.PositionCode) if err != nil { @@ -84,6 +88,18 @@ func (s *Service) RevokePosition(ctx context.Context, targetUserID uuid.UUID, po 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) { allowed, _, err := s.positions.UserHasPermission(ctx, userID, permissionCode) return allowed, err diff --git a/kotosoft-id-backend/internal/services/service.go b/kotosoft-id-backend/internal/services/service.go index c0097db..b547063 100644 --- a/kotosoft-id-backend/internal/services/service.go +++ b/kotosoft-id-backend/internal/services/service.go @@ -63,6 +63,11 @@ type PositionRepo interface { UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, string, 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 { diff --git a/kotosoft-id-backend/main.exe b/kotosoft-id-backend/main.exe new file mode 100644 index 0000000..08983fa Binary files /dev/null and b/kotosoft-id-backend/main.exe differ diff --git a/kotosoft-id-backend/migrations/migrations.sql b/kotosoft-id-backend/migrations/migrations.sql index aabf8ab..2c9e636 100644 --- a/kotosoft-id-backend/migrations/migrations.sql +++ b/kotosoft-id-backend/migrations/migrations.sql @@ -111,6 +111,20 @@ CREATE TABLE IF NOT EXISTS public.positions ( updated_at timestamptz NOT NULL DEFAULT now() ); +CREATE TABLE IF NOT EXISTS public.position_translations ( + position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE, + locale text NOT NULL DEFAULT 'en', + name text NOT NULL, + description text, + PRIMARY KEY (position_id, locale) +); + +CREATE INDEX IF NOT EXISTS idx_position_translations_position_id +ON public.position_translations (position_id); + +CREATE INDEX IF NOT EXISTS idx_position_translations_locale +ON public.position_translations (locale); + CREATE TABLE IF NOT EXISTS public.permissions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), code text NOT NULL UNIQUE, diff --git a/kotosoft-id-frontend/actions/auth.ts b/kotosoft-id-frontend/actions/auth.ts index 351f8c5..e5ea113 100644 --- a/kotosoft-id-frontend/actions/auth.ts +++ b/kotosoft-id-frontend/actions/auth.ts @@ -97,7 +97,7 @@ export async function SessionLogin( } } -export async function GetUser(): Promise { +export async function fetchUser(): Promise { const store = await cookies(); const accessToken = store.get("access_token")?.value; if (!accessToken) return null; @@ -114,7 +114,7 @@ export async function GetUser(): Promise { await clearTokens(); return null; } - return GetUser(); + return fetchUser(); } if (!response.ok) return null; @@ -124,7 +124,7 @@ export async function GetUser(): Promise { } } -export async function UpdateUser(first_name: string, second_name: string, birth_date: string): Promise { +export async function updateUser(first_name: string, second_name: string, birth_date: string): Promise { const store = await cookies(); const accessToken = store.get("access_token")?.value; if (!accessToken) return null; @@ -155,7 +155,7 @@ export async function UpdateUser(first_name: string, second_name: string, birth_ await clearTokens(); return null; } - return UpdateUser(first_name, second_name, birth_date); + return updateUser(first_name, second_name, birth_date); } 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"); if (!email || !password) return { success: false, message: t("allFieldsRequired") } diff --git a/kotosoft-id-frontend/actions/consents.ts b/kotosoft-id-frontend/actions/consents.ts index 41ffc7d..0b796e9 100644 --- a/kotosoft-id-frontend/actions/consents.ts +++ b/kotosoft-id-frontend/actions/consents.ts @@ -3,7 +3,7 @@ import { Consent } from "@/types" import { cookies } from "next/headers" -export async function getConsents() { +export async function fetchConsents() { const store = await cookies() const accessToken = store.get("access_token")?.value diff --git a/kotosoft-id-frontend/actions/oauth.ts b/kotosoft-id-frontend/actions/oauth.ts index ab583ec..2939b1b 100644 --- a/kotosoft-id-frontend/actions/oauth.ts +++ b/kotosoft-id-frontend/actions/oauth.ts @@ -2,7 +2,7 @@ import type { OAuthSession } from "@/types"; -export async function getSession(token: string): Promise { +export async function fetchSession(token: string): Promise { if (!token) return null; try { const response = await fetch( diff --git a/kotosoft-id-frontend/actions/positions.ts b/kotosoft-id-frontend/actions/positions.ts index 8d821d4..e1ec547 100644 --- a/kotosoft-id-frontend/actions/positions.ts +++ b/kotosoft-id-frontend/actions/positions.ts @@ -8,176 +8,153 @@ async function getAccessToken(): Promise { return store.get("access_token")?.value ?? null } -async function authHeaders(locale?: string): Promise { +async function getAuthHeaders(locale?: string): Promise { const token = await getAccessToken() - return { - Authorization: `Bearer ${token}`, - "Accept-Language": locale ?? "en", - } + return token + ? { + Authorization: `Bearer ${token}`, + "Accept-Language": locale ?? "en", + } + : {} } -export async function getMyPositions(locale?: string): Promise { +async function handleJsonResponse(response: Response): Promise { + 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 { const token = await getAccessToken() if (!token) return [] - const response = await fetch( + const res = await fetch( `${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 response.json()) as Position[] + return (await handleJsonResponse(res)) ?? [] } -export async function listAllPositions(locale?: string): Promise { +export async function fetchAllPositions(locale?: string): Promise { const token = await getAccessToken() if (!token) return null const response = await fetch( `${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.ok) return null - return (await response.json()) as Position[] + return await handleJsonResponse(response) } -export async function upsertPosition( +export async function savePosition( code: string, name: string, locale: string, - description?: string | null -): Promise<{ success: boolean }> { - const token = await getAccessToken() - if (!token) return { success: false } - - const response = await fetch( - `${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, - { - method: "POST", - headers: { ...(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 ): Promise<{ success: boolean }> { const token = await getAccessToken() if (!token) return { success: false } - const response = await fetch( - `${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, - { - method: "POST", - headers: { - ...(await authHeaders()), - "Content-Type": "application/json", - }, - body: JSON.stringify({ - code, - ...(description ? { description } : {}), - }), - } - ) + const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, { + method: "POST", + headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" }, + body: JSON.stringify({ code, name, ...(description ? { description } : {}) }), + }) - return { success: response.ok } + return handleSuccessResponse(res) } -export async function updatePermission( - code: string, - description?: string -): Promise<{ success: boolean }> { - const token = await getAccessToken() - if (!token) return { success: false } - - const response = await fetch( - `${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, - { - method: "PUT", - headers: { - ...(await authHeaders()), - "Content-Type": "application/json", - }, - body: JSON.stringify({ - ...(description ? { description } : {}), - }), - } - ) - - return { success: response.ok } -} - -export async function deletePermission( - code: string -): Promise<{ success: boolean }> { - const token = await getAccessToken() - if (!token) return { success: false } - - const response = await fetch( - `${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, - { - method: "DELETE", - headers: await authHeaders(), - } - ) - - return { success: response.ok } -} - -export async function listAllPermissions(): Promise { +export async function fetchAllPermissions(): Promise { const token = await getAccessToken() if (!token) return [] - const response = await fetch( - `${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, - { headers: await authHeaders(), cache: "no-store" } - ) + const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, { + headers: await getAuthHeaders(), + cache: "no-store", + }) - if (!response.ok) return [] - return (await response.json()) as Permission[] + return (await handleJsonResponse(res)) ?? [] } -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, permissionCode: string ): Promise<{ success: boolean }> { const token = await getAccessToken() 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`, { method: "POST", - headers: { ...(await authHeaders()), "Content-Type": "application/json" }, + headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" }, body: JSON.stringify({ permission_code: permissionCode }), } ) - return { success: response.ok } + return handleSuccessResponse(res) } -export async function removePermissionFromPosition( +export async function detachPermissionFromPosition( positionCode: string, permissionCode: string ): Promise<{ success: boolean }> { const token = await getAccessToken() 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}`, - { 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, positionCode: string, validFrom?: string, @@ -186,11 +163,11 @@ export async function assignPosition( const token = await getAccessToken() 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`, { method: "POST", - headers: { ...(await authHeaders()), "Content-Type": "application/json" }, + headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" }, body: JSON.stringify({ position_code: positionCode, ...(validFrom ? { valid_from: validFrom } : {}), @@ -199,20 +176,55 @@ export async function assignPosition( } ) - return { success: response.ok } + return handleSuccessResponse(res) } -export async function revokePosition( - userId: string, - positionCode: string -): Promise<{ success: boolean }> { +export async function revokePositionFromUser(userId: string, positionCode: string): Promise<{ success: boolean }> { const token = await getAccessToken() 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}`, - { 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) } \ No newline at end of file diff --git a/kotosoft-id-frontend/app/consent/page.tsx b/kotosoft-id-frontend/app/consent/page.tsx index 0a79650..7f12b0d 100644 --- a/kotosoft-id-frontend/app/consent/page.tsx +++ b/kotosoft-id-frontend/app/consent/page.tsx @@ -5,7 +5,7 @@ import { Spinner } from "@/components/ui/spinner"; import { useTranslations } from "next-intl"; import { useEffect, useState } from "react"; import { useSearchParams } from "next/navigation"; -import { getSession, Approve } from "@/actions/oauth"; +import { fetchSession, Approve } from "@/actions/oauth"; import { Check } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; import Link from "next/link"; @@ -26,7 +26,7 @@ export default function ConsentPage() { const [isSubmitting, setIsSubmitting] = useState(false); useEffect(() => { - getSession(sessionToken) + fetchSession(sessionToken) .then(data => { if (!data) throw new Error(); setSession(data); diff --git a/kotosoft-id-frontend/app/me/component.tsx b/kotosoft-id-frontend/app/me/component.tsx index d8cdd9c..80f179a 100644 --- a/kotosoft-id-frontend/app/me/component.tsx +++ b/kotosoft-id-frontend/app/me/component.tsx @@ -3,7 +3,7 @@ import Header from "@/components/header"; import { Skeleton } from "@/components/ui/skeleton"; 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 { Button } from "@/components/ui/button"; import { useState } from "react"; @@ -16,25 +16,30 @@ import Admin from "./items/admin"; interface Props { userData: User | 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 [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 baseItems = [ { name: t("items.profile.title"), icon: , component: }, { name: t("items.applications.title"), icon: , component: }, - { name: t("items.positions.title"), icon: , component: }, + // { name: t("items.positions.title"), icon: , component: }, ] const adminItem = user?.is_admin - ? [{ name: t("items.admin.title"), icon: , component: }] - : [] + ? [{ name: t("items.admin.title"), icon: , component: }] + : []; + const items = [...baseItems, ...adminItem] diff --git a/kotosoft-id-frontend/app/me/items/admin.tsx b/kotosoft-id-frontend/app/me/items/admin.tsx index e235824..79bdc21 100644 --- a/kotosoft-id-frontend/app/me/items/admin.tsx +++ b/kotosoft-id-frontend/app/me/items/admin.tsx @@ -1,43 +1,28 @@ "use client" -import { useEffect, useState } from "react" -import { useLocale, useTranslations } from "next-intl" -import type { Position } from "@/types" -import { Spinner } from "@/components/ui/spinner" -import { getMyPositions } from "@/actions/positions" +import { useTranslations } from "next-intl" +import type { Permission, Position } from "@/types" 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>; + + positions: Position[] | null; + setPositions: React.Dispatch>; +} + +export default function Admin({ permissions, setPermissions, positions, setPositions }: Props) { const t = useTranslations("MePage.items.admin") - const locale = useLocale() - - const [positions, setPositions] = useState(null) - const [loading, setLoading] = useState(true) - - useEffect(() => { - getMyPositions(locale) - .then(setPositions) - .finally(() => setLoading(false)) - }, [locale]) return (

{t("title")}

- - {loading && ( -
- - {t("loading")} -
- )} - - {!loading && ( -
- - {/* */} -
- )} +
+ + +
) } \ No newline at end of file diff --git a/kotosoft-id-frontend/app/me/items/admin/dialogs/createPermissionDialog.tsx b/kotosoft-id-frontend/app/me/items/admin/dialogs/createPermissionDialog.tsx deleted file mode 100644 index e160842..0000000 --- a/kotosoft-id-frontend/app/me/items/admin/dialogs/createPermissionDialog.tsx +++ /dev/null @@ -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() - - const onSubmit: SubmitHandler = async (data) => { - const result = await createPermission(data.code, data.description) - - if (!result.success) { - toast("Failed to create permission", { icon: }) - return - } - - reset() - window.location.reload() - } - - return ( - - - - - - - Create permission - -
- - - Code - - {errors.code && ( - {errors.code.message} - )} - - - - Description - - - - - - - - - - -
-
-
- ) -} \ No newline at end of file diff --git a/kotosoft-id-frontend/app/me/items/admin/dialogs/editPermissionDialog.tsx b/kotosoft-id-frontend/app/me/items/admin/dialogs/editPermissionDialog.tsx deleted file mode 100644 index 068dece..0000000 --- a/kotosoft-id-frontend/app/me/items/admin/dialogs/editPermissionDialog.tsx +++ /dev/null @@ -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() - - const onSubmit: SubmitHandler = async (data) => { - const result = await updatePermission(data.code, data.description) - - if (!result.success) { - toast("Failed to update permission", { icon: }) - return - } - - reset() - } - - return ( - - - - - - - Edit permission - -
- - - Code - - - - - Description - - - - - - - - - - -
-
-
- ) -} \ No newline at end of file diff --git a/kotosoft-id-frontend/app/me/items/admin/dialogs/permissionDialog.tsx b/kotosoft-id-frontend/app/me/items/admin/dialogs/permissionDialog.tsx new file mode 100644 index 0000000..1d03e8b --- /dev/null +++ b/kotosoft-id-frontend/app/me/items/admin/dialogs/permissionDialog.tsx @@ -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({ + 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 = 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: }) + 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: }) + props.onSuccess(updated) + reset() + setOpen(false) + } + + return ( + + {props.trigger} + + + {isEdit ? t("edit.title") : t("create.title")} + +
+ + + {isEdit ? t("edit.code") : t("create.code")} + isEdit || v.trim().length > 0 || t("create.codeRequired") })} + /> + {errors.code && {errors.code.message}} + + + {isEdit ? t("edit.description") : t("create.description")} + + + + + + + + + +
+
+
+ ) +} \ No newline at end of file diff --git a/kotosoft-id-frontend/app/me/items/admin/dialogs/positionDialog.tsx b/kotosoft-id-frontend/app/me/items/admin/dialogs/positionDialog.tsx new file mode 100644 index 0000000..b74287a --- /dev/null +++ b/kotosoft-id-frontend/app/me/items/admin/dialogs/positionDialog.tsx @@ -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({ + 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 = 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: }) + 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: }) + props.onSuccess(updated) + reset() + setOpen(false) + } + + return ( + + {props.trigger} + + + {isEdit ? t("edit.title") : t("create.title")} + +
+ + + {isEdit ? t("edit.code") : t("create.code")} + isEdit || v.trim().length > 0 || t("create.codeRequired") })} + /> + {errors.code && {errors.code.message}} + + + {isEdit ? t("edit.name") : t("create.name")} + v.trim().length > 0 || t("create.nameRequired") })} + /> + {errors.name && {errors.name.message}} + + + {isEdit ? t("edit.description") : t("create.description")} + + + + + + + + + +
+
+
+ ) +} \ No newline at end of file diff --git a/kotosoft-id-frontend/app/me/items/admin/permissions.tsx b/kotosoft-id-frontend/app/me/items/admin/permissions.tsx index 9ceda74..d920376 100644 --- a/kotosoft-id-frontend/app/me/items/admin/permissions.tsx +++ b/kotosoft-id-frontend/app/me/items/admin/permissions.tsx @@ -1,87 +1,96 @@ "use client" -import { useState, useEffect, useMemo } from "react"; -import { Button } from "@/components/ui/button" -import { Card, CardFooter } from "@/components/ui/card"; +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 CreatePermissionDialog from "./dialogs/createPermissionDialog"; -import { Permission } from "@/types"; -import { deletePermission, listAllPermissions } from "@/actions/positions"; -import { Spinner } from "@/components/ui/spinner"; -import EditPermissionDialog from "./dialogs/editPermissionDialog"; +import { MoreHorizontalIcon } from "lucide-react"; +import { Check, X } from "lucide-react"; +import { toast } from "sonner"; +import { PermissionDialog } from "./dialogs/permissionDialog"; +import { removePermission } from "@/actions/positions"; +import type { Permission } from "@/types"; -export default function Permissions() { - const [permissions, setPermissions] = useState([]); - const [isLoading, setIsLoading] = useState(true); +interface Props { + permissions: Permission[] | null; + setPermissions: React.Dispatch>; +} - useEffect(() => { - async function load() { - const data = await listAllPermissions(); - setPermissions(data); - setIsLoading(false); - } +export default function Permissions({ permissions, setPermissions }: Props) { + const t = useTranslations("MePage.items.admin.permissions") + const pt = useTranslations("permissions") - 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) { - const result = await deletePermission(code) - + const result = await removePermission(code) if (result.success) { - setPermissions((prev) => - prev.filter((p) => p.code !== code) - ) + setPermissions((prev) => (prev || []).filter((p) => p.code !== code)) + toast(t("delete.success"), { icon: }) + } else { + toast(t("delete.error"), { icon: }) } } return (
-

Permissions

-

Here You can create permissions which later You can assign them to positions

+

{t("title")}

+

{t("subtitle")}

- - - +
+ + + {t("columns.code")} + {t("columns.description")} + {t("columns.actions")} + + + + {permissions?.length === 0 && ( - Code - Description - Actions + {t("empty")} - - - {permissionsMemo.map((permission) => ( + )} + {permissions?.map((permission) => ( - {permission.code} - {permission.description} + {permission.code} + {pt(`${permission.code}`)} - + handleUpdated(permission.code, updated)} + trigger={} + /> - handleDelete(permission.code)}>Delete + handleDelete(permission.code)}>{t("actions.delete")} ))} - - {isLoading &&

Permissions are loading...

} -
- - - -
+ + + {t("actions.create")}} + />
) } \ No newline at end of file diff --git a/kotosoft-id-frontend/app/me/items/admin/positions.tsx b/kotosoft-id-frontend/app/me/items/admin/positions.tsx new file mode 100644 index 0000000..923964c --- /dev/null +++ b/kotosoft-id-frontend/app/me/items/admin/positions.tsx @@ -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>; +} + +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: }) + } else { + toast(t("delete.error"), { icon: }) + } + } + + return ( +
+
+

{t("title")}

+

{t("subtitle")}

+
+ + + + {t("columns.code")} + {t("columns.name")} + {t("columns.description")} + {t("columns.actions")} + + + + {positions?.length === 0 && ( + + {t("empty")} + + )} + {positions?.map((position) => ( + + {position.code} + {position.name} + {position.description || t("noDescription")} + + + + + + + handleUpdated(position.code, updated)} + trigger={} + /> + + handleDelete(position.code)}>{t("actions.delete")} + + + + + ))} + +
+ {t("actions.create")}} + /> +
+ ) +} \ No newline at end of file diff --git a/kotosoft-id-frontend/app/me/items/applications.tsx b/kotosoft-id-frontend/app/me/items/applications.tsx index e4510db..1cd9e63 100644 --- a/kotosoft-id-frontend/app/me/items/applications.tsx +++ b/kotosoft-id-frontend/app/me/items/applications.tsx @@ -49,8 +49,10 @@ export default function Applications({ consents, setConsents }: Props) { return (
-

{t("title")}

- +
+

{t("title")}

+

{t("subtitle")}

+
{list?.map((consent) => ( diff --git a/kotosoft-id-frontend/app/me/items/positions.tsx b/kotosoft-id-frontend/app/me/items/positions.tsx index 575206c..ddfda18 100644 --- a/kotosoft-id-frontend/app/me/items/positions.tsx +++ b/kotosoft-id-frontend/app/me/items/positions.tsx @@ -6,7 +6,7 @@ import type { Position } from "@/types" import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item" import { Badge } from "@/components/ui/badge" import { Spinner } from "@/components/ui/spinner" -import { getMyPositions } from "@/actions/positions" +import { fetchMyPositions } from "@/actions/positions" export default function Positions() { const t = useTranslations("MePage.items.positions") @@ -16,7 +16,7 @@ export default function Positions() { const [loading, setLoading] = useState(true) useEffect(() => { - getMyPositions(locale) + fetchMyPositions(locale) .then(setPositions) .finally(() => setLoading(false)) }, [locale]) diff --git a/kotosoft-id-frontend/app/me/items/profile.tsx b/kotosoft-id-frontend/app/me/items/profile.tsx index edf1bb2..35ea63c 100644 --- a/kotosoft-id-frontend/app/me/items/profile.tsx +++ b/kotosoft-id-frontend/app/me/items/profile.tsx @@ -8,7 +8,7 @@ import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field import { Input } from "@/components/ui/input"; import { Spinner } from "@/components/ui/spinner"; import { BirthdatePicker } from "@/components/ui/birthdate-picker"; -import { UpdateUser } from "@/actions/auth"; +import { updateUser } from "@/actions/auth"; import { toast } from "sonner"; import { Check, X } from "lucide-react"; @@ -36,7 +36,7 @@ export default function Profile({ user, setUser }: Props) { const onSubmit: SubmitHandler = async (data) => { 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: }) else { diff --git a/kotosoft-id-frontend/app/me/page.tsx b/kotosoft-id-frontend/app/me/page.tsx index 98f7960..3d3bde8 100644 --- a/kotosoft-id-frontend/app/me/page.tsx +++ b/kotosoft-id-frontend/app/me/page.tsx @@ -1,16 +1,19 @@ -import { GetUser } from "@/actions/auth"; +import { fetchUser } from "@/actions/auth"; import { redirect } from "next/navigation"; 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() { - const user = await GetUser(); + const user = await fetchUser(); if (!user) { 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 ; + return ; } \ No newline at end of file diff --git a/kotosoft-id-frontend/app/oauth/page.ts b/kotosoft-id-frontend/app/oauth/page.ts index d8c353a..c5910d9 100644 --- a/kotosoft-id-frontend/app/oauth/page.ts +++ b/kotosoft-id-frontend/app/oauth/page.ts @@ -1,4 +1,4 @@ -import { getSession } from "@/actions/oauth"; +import { fetchSession } from "@/actions/oauth"; import { isRedirectError } from "next/dist/client/components/redirect-error"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; @@ -14,7 +14,7 @@ export default async function OAuthPage({ const session = (await searchParams).session as string | undefined; if (!session) redirect("/oauth/error"); - const data = await getSession(session); + const data = await fetchSession(session); if (!data) redirect("/oauth/error"); const store = await cookies(); diff --git a/kotosoft-id-frontend/app/register/page.tsx b/kotosoft-id-frontend/app/register/page.tsx index d97a013..68dc2a1 100644 --- a/kotosoft-id-frontend/app/register/page.tsx +++ b/kotosoft-id-frontend/app/register/page.tsx @@ -1,6 +1,5 @@ "use client" -import { Register } from "@/actions/auth"; import Header from "@/components/header"; import { Button } from "@/components/ui/button"; 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 { Sex } from "@/types"; 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 { email: string; @@ -34,7 +34,7 @@ export default function RegisterPage() { const onSubmit: SubmitHandler = async (data) => { 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) { setError(result.message ?? null); return; diff --git a/kotosoft-id-frontend/messages/en.json b/kotosoft-id-frontend/messages/en.json index c3c6fa9..d8faba4 100644 --- a/kotosoft-id-frontend/messages/en.json +++ b/kotosoft-id-frontend/messages/en.json @@ -38,7 +38,7 @@ }, "sex": { "title": "Sex", - "select": "Specify Your sex", + "select": "Specify your sex", "male": "Male", "female": "Female" }, @@ -66,7 +66,7 @@ }, "birthdate": { "title": "Date of birth", - "pick": "Select Your date of birth" + "pick": "Select your date of birth" }, "required": "This field is required", "save": "Save", @@ -76,40 +76,110 @@ }, "applications": { "title": "Applications", + "subtitle": "Here you can review and revoke concents for connected applications.", "authorized": "Autorized on", "revoke": "Revoke", "successfullyRevoked": "Access successfully revoked!", "revocationError": "Failed to revoke access" }, "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" - } + "title": "Positions" }, "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" } }, "ConsentPage": { "title": "Access to {service}", - "subtitle": "{service} wants to access Your Kotosoft ID account to:", - "invalidSession": "This session is invalid. Please go back to Your application and try again.", + "subtitle": "{service} wants to access your Kotosoft ID account to:", + "invalidSession": "This session is invalid. Please go back to your application and try again.", "scopes": { - "profile:read": "See information of Your profile", - "profile:edit": "Edit information of Your profile" + "profile:read": "See information of your profile", + "profile:edit": "Edit information of your profile" }, "allow": "Allow", "deny": "Deny", @@ -121,6 +191,12 @@ "dark": "Dark", "system": "System" }, + "permissions": { + "positions": { + "manage": "Create and edit positions", + "assign": "Assign positions to users" + } + }, "errors": { "serverError": "Server error. Please try again later.", "invalidCredentialsError": "Incorrect email or password", diff --git a/kotosoft-id-frontend/messages/it.json b/kotosoft-id-frontend/messages/it.json index 072eb82..2f585c6 100644 --- a/kotosoft-id-frontend/messages/it.json +++ b/kotosoft-id-frontend/messages/it.json @@ -70,31 +70,104 @@ }, "required": "Questo campo è obbligatorio", "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." } }, "applications": { "title": "Applicazioni", + "subtitle": "Qui puoi vedere e revocare i consensi per le applicazioni connesse.", "authorized": "Autorizzato il", "revoke": "Revoca", "successfullyRevoked": "Accesso all'applicazione revocato con successo!", "revocationError": "Impossibile revocare l'accesso all'applicazione" }, "positions": { - "title": "Posizioni", - "loading": "Caricamento delle posizioni…", - "empty": "Non hai ancora posizioni assegnate.", - "noDescription": "Nessuna descrizione", - "form": { - "title": "Gestione delle posizioni", - "code": "Codice posizione", - "name": "Nome", - "description": "Descrizione", - "save": "Salva", - "required": "Compila tutti i campi obbligatori", - "saved": "Posizione salvata con successo", - "saveError": "Impossibile salvare la posizione" + "title": "Posizioni" + }, + "admin": { + "title": "Amministrazione", + "permissions": { + "title": "Permessi", + "subtitle": "I permessi possono essere assegnati alle posizioni per controllare l'accesso.", + "empty": "Non ci sono permessi", + "noDescription": "Senza descrizione", + "columns": { + "code": "Codice", + "description": "Descrizione", + "actions": "Azioni" + }, + "actions": { + "edit": "Modifica", + "delete": "Elimina", + "create": "Crea permesso" + }, + "create": { + "title": "Creazione del permesso", + "code": "Codice", + "description": "Descrizione", + "cancel": "Annulla", + "save": "Salva", + "codeRequired": "Il codice è obbligatorio", + "success": "Il permesso è stato creato con successo!", + "error": "Impossibile creare il permesso" + }, + "edit": { + "title": "Modifica permesso", + "code": "Codice", + "description": "Descrizione", + "cancel": "Annulla", + "save": "Aggiorna", + "success": "Il permesso è stato aggiornato con successo!", + "error": "Impossibile aggiornare il permesso" + }, + "delete": { + "success": "Il permesso è stato eliminato con successo!", + "error": "Impossibile eliminare il permesso" + } + }, + "positions": { + "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" @@ -118,6 +191,12 @@ "dark": "Scuro", "system": "Sistema" }, + "permissions": { + "positions": { + "manage": "Crea e modifica posizioni", + "assign": "Assegna posizioni agli utenti" + } + }, "errors": { "serverError": "Errore del server. Riprova più tardi.", "invalidCredentialsError": "Email o password non corretti", diff --git a/kotosoft-id-frontend/messages/ru.json b/kotosoft-id-frontend/messages/ru.json index 923462b..7e6e834 100644 --- a/kotosoft-id-frontend/messages/ru.json +++ b/kotosoft-id-frontend/messages/ru.json @@ -13,7 +13,7 @@ }, "required": "Это поле является обязательным", "login": "Вход", - "noAccountNote": "У Вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь здесь." + "noAccountNote": "У вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь здесь." }, "RegisterPage":{ "title": "Регистрация в Kotosoft ID", @@ -38,7 +38,7 @@ }, "sex": { "title": "Пол", - "select": "Выберите Ваш пол", + "select": "Выберите ваш пол", "male": "Мужской", "female": "Женский" }, @@ -46,7 +46,7 @@ "next": "Дальше", "back": "Назад", "register": "Зарегистрироваться", - "hasAccountNote": "У Вас уже есть аккаунт в Kotosoft ID? Войти можно тут." + "hasAccountNote": "У вас уже есть аккаунт в Kotosoft ID? Войти можно тут." }, "MePage": { "loadError": "Что-то пошло не так. Не получилось загрузить пользователя.", @@ -66,7 +66,7 @@ }, "birthdate": { "title": "Дата рождения", - "pick": "Выберите Вашу дату рождения" + "pick": "Выберите вашу дату рождения" }, "required": "Это поле является обязательным", "save": "Сохранить", @@ -76,25 +76,98 @@ }, "applications": { "title": "Приложения", - "authorized": "Авторизировано", + "subtitle": "Здесь вы можете просматривать и отзывать доступ приложений.", + "authorized": "Разрешено", "revoke": "Отозвать", "successfullyRevoked": "Доступ приложения успешно отозван!", "revocationError": "Не удалось отозвать доступ приложения" }, "positions": { - "title": "Должности", - "loading": "Загружаем должности…", - "empty": "У вас пока нет назначенных должностей.", - "noDescription": "Без описания", - "form": { - "title": "Управление должностями", - "code": "Код должности", - "name": "Название", - "description": "Описание", - "save": "Сохранить", - "required": "Заполните обязательные поля", - "saved": "Должность успешно сохранена", - "saveError": "Не удалось сохранить должность" + "title": "Должности" + }, + "admin": { + "title": "Администрирование", + "permissions": { + "title": "Разрешения", + "subtitle": "Разрешения могут быть присвоены должностям для контроля прав доступа.", + "empty": "Разрешений пока нет", + "noDescription": "Без описания", + "columns": { + "code": "Код", + "description": "Описание", + "actions": "Действия" + }, + "actions": { + "edit": "Изменить", + "delete": "Удалить", + "create": "Создать разрешение" + }, + "create": { + "title": "Создать разрешение", + "code": "Код", + "description": "Описание", + "cancel": "Отмена", + "save": "Сохранить", + "codeRequired": "Код разрешения обязателен", + "success": "Разрешение успешно создано!", + "error": "Не удалось создать разрешение" + }, + "edit": { + "title": "Редактирование разрешения", + "code": "Код", + "description": "Описание", + "cancel": "Отмена", + "save": "Сохранить", + "success": "Разрешение успешно обновлено!", + "error": "Не удалось обновить разрешение" + }, + "delete": { + "success": "Разрешение успешно удалено!", + "error": "Не удалось удалить разрешение" + } + }, + "positions": { + "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": "Выйти" @@ -102,11 +175,11 @@ }, "ConsentPage": { "title": "Вход в {service}", - "subtitle": "{service} хочет получить доступ к Вашему аккаунту Kotosoft ID, чтобы:", + "subtitle": "{service} хочет получить доступ к вашему аккаунту Kotosoft ID, чтобы:", "invalidSession": "Эта сессия недействительна. Пожалуйста, вернитесь в своё приложение и попробуйте ещё раз.", "scopes": { - "profile:read": "Видеть данные Вашего профиля", - "profile:edit": "Изменять данные в Вашем профиле" + "profile:read": "Видеть данные вашего профиля", + "profile:edit": "Изменять данные в вашем профиле" }, "allow": "Разрешить", "deny": "Запретить", @@ -118,6 +191,12 @@ "dark": "Тёмная", "system": "Как в системе" }, + "permissions": { + "positions": { + "manage": "Создание и редактирование должностей", + "assign": "Назначение должностей пользователям" + } + }, "errors": { "serverError": "Ошибка сервера. Пожалуйста, попробуйте ещё раз позже.", "invalidCredentialsError": "Неправильный адрес почты или пароль",