fixes
This commit is contained in:
@@ -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"`
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Binary file not shown.
@@ -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,
|
||||
|
||||
@@ -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 accessToken = store.get("access_token")?.value;
|
||||
if (!accessToken) return null;
|
||||
@@ -114,7 +114,7 @@ export async function GetUser(): Promise<User | null> {
|
||||
await clearTokens();
|
||||
return null;
|
||||
}
|
||||
return GetUser();
|
||||
return fetchUser();
|
||||
}
|
||||
|
||||
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 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") }
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
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;
|
||||
try {
|
||||
const response = await fetch(
|
||||
|
||||
@@ -8,176 +8,153 @@ async function getAccessToken(): Promise<string | 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()
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Accept-Language": locale ?? "en",
|
||||
}
|
||||
return token
|
||||
? {
|
||||
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()
|
||||
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<Position[]>(res)) ?? []
|
||||
}
|
||||
|
||||
export async function listAllPositions(locale?: string): Promise<Position[] | null> {
|
||||
export async function fetchAllPositions(locale?: string): Promise<Position[] | null> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return null
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`,
|
||||
{ headers: await 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<Position[]>(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<Permission[]> {
|
||||
export async function fetchAllPermissions(): Promise<Permission[]> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return []
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`,
|
||||
{ headers: await authHeaders(), cache: "no-store" }
|
||||
)
|
||||
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<Permission[]>(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)
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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: <UserIcon />, component: <Profile user={user} setUser={setUser} /> },
|
||||
{ name: t("items.applications.title"), icon: <AppWindowMacIcon />, component: <Applications consents={consents} setConsents={setConsents} /> },
|
||||
{ name: t("items.positions.title"), icon: <BriefcaseBusinessIcon />, component: <Positions /> },
|
||||
// { name: t("items.positions.title"), icon: <BriefcaseBusinessIcon />, component: <Positions /> },
|
||||
]
|
||||
|
||||
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]
|
||||
|
||||
|
||||
@@ -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<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 locale = useLocale()
|
||||
|
||||
const [positions, setPositions] = useState<Position[] | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
getMyPositions(locale)
|
||||
.then(setPositions)
|
||||
.finally(() => setLoading(false))
|
||||
}, [locale])
|
||||
|
||||
return (
|
||||
<div className="w-full lg:max-w-xl flex flex-col gap-6">
|
||||
<h1 className="text-xl">{t("title")}</h1>
|
||||
|
||||
{loading && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Spinner />
|
||||
<span>{t("loading")}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && (
|
||||
<div className="space-y-8">
|
||||
<Permissions />
|
||||
{/* <Positions /> */}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-8">
|
||||
<Permissions permissions={permissions} setPermissions={setPermissions} />
|
||||
<Positions positions={positions} setPositions={setPositions} />
|
||||
</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"
|
||||
|
||||
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<Permission[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
interface Props {
|
||||
permissions: Permission[] | null;
|
||||
setPermissions: React.Dispatch<React.SetStateAction<Permission[] | null>>;
|
||||
}
|
||||
|
||||
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: <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">Permissions</h2>
|
||||
<h4 className="text-sm text-muted-foreground">Here You can create permissions which later You can assign them to positions</h4>
|
||||
<h2 className="text-lg">{t("title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||
</div>
|
||||
<Card size="sm" className="w-full">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<Table>
|
||||
<TableHeader className="rounded-lg">
|
||||
<TableRow>
|
||||
<TableHead>{t("columns.code")}</TableHead>
|
||||
<TableHead>{t("columns.description")}</TableHead>
|
||||
<TableHead className="text-right">{t("columns.actions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{permissions?.length === 0 && (
|
||||
<TableRow>
|
||||
<TableHead>Code</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{permissionsMemo.map((permission) => (
|
||||
)}
|
||||
{permissions?.map((permission) => (
|
||||
<TableRow key={permission.code}>
|
||||
<TableCell>{permission.code}</TableCell>
|
||||
<TableCell>{permission.description}</TableCell>
|
||||
<TableCell className="font-mono">{permission.code}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{pt(`${permission.code}`)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">Open menu</span>
|
||||
<span className="sr-only">{t("columns.actions")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<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 />
|
||||
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(permission.code)}>Delete</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(permission.code)}>{t("actions.delete")}</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
{isLoading && <p className="mx-2 my-1 text-muted-foreground animate-pulse">Permissions are loading...</p>}
|
||||
</Table>
|
||||
<CardFooter>
|
||||
<CreatePermissionDialog />
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</TableBody>
|
||||
</Table>
|
||||
<PermissionDialog
|
||||
mode="create"
|
||||
onSuccess={handleCreated}
|
||||
trigger={<Button variant="outline" size="sm" className="w-full">{t("actions.create")}</Button>}
|
||||
/>
|
||||
</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 (
|
||||
<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">
|
||||
{list?.map((consent) => (
|
||||
<Item key={consent.client_id}>
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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<FormData> = 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: <X size={16} /> })
|
||||
else {
|
||||
|
||||
@@ -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 <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 { 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();
|
||||
|
||||
@@ -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<FormData> = 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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
},
|
||||
"required": "Это поле является обязательным",
|
||||
"login": "Вход",
|
||||
"noAccountNote": "У Вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь <register>здесь</register>."
|
||||
"noAccountNote": "У вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь <register>здесь</register>."
|
||||
},
|
||||
"RegisterPage":{
|
||||
"title": "Регистрация в Kotosoft ID",
|
||||
@@ -38,7 +38,7 @@
|
||||
},
|
||||
"sex": {
|
||||
"title": "Пол",
|
||||
"select": "Выберите Ваш пол",
|
||||
"select": "Выберите ваш пол",
|
||||
"male": "Мужской",
|
||||
"female": "Женский"
|
||||
},
|
||||
@@ -46,7 +46,7 @@
|
||||
"next": "Дальше",
|
||||
"back": "Назад",
|
||||
"register": "Зарегистрироваться",
|
||||
"hasAccountNote": "У Вас уже есть аккаунт в Kotosoft ID? Войти можно <login>тут</login>."
|
||||
"hasAccountNote": "У вас уже есть аккаунт в Kotosoft ID? Войти можно <login>тут</login>."
|
||||
},
|
||||
"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": "Неправильный адрес почты или пароль",
|
||||
|
||||
Reference in New Issue
Block a user