diff --git a/kotosoft-id-backend/cmd/main.go b/kotosoft-id-backend/cmd/main.go index 0213573..03cc854 100644 --- a/kotosoft-id-backend/cmd/main.go +++ b/kotosoft-id-backend/cmd/main.go @@ -35,6 +35,7 @@ func main() { userRepo := repositories.NewUserRepository(postgres.Pool) oauthRepo := repositories.NewOAuthRepository(postgres.Pool) + positionRepo := repositories.NewPositionRepository(postgres.Pool) if err := seedClient(context.Background(), oauthRepo, cfg.Client); err != nil { log.Fatalf("seed client: %v", err) @@ -43,6 +44,7 @@ func main() { svc := services.New( userRepo, oauthRepo, + positionRepo, redis.Client, services.TokenConfig{ AccessTTL: cfg.JWT.TTL, @@ -55,8 +57,9 @@ func main() { authHandler := handlers.NewAuthHandler(svc) oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL) consentHandler := handlers.NewConsentHandler(svc) + positionsHandler := handlers.NewPositionsHandler(svc) - router := http.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo, limiter) + router := http.NewRouter(authHandler, oauthHandler, consentHandler, positionsHandler, svc, oauthRepo, limiter) log.Printf("starting server on %s", cfg.Server.Addr) if err := router.Run(cfg.Server.Addr); err != nil { diff --git a/kotosoft-id-backend/internal/handlers/oauth.go b/kotosoft-id-backend/internal/handlers/oauth.go index 5b9971a..7d073b9 100644 --- a/kotosoft-id-backend/internal/handlers/oauth.go +++ b/kotosoft-id-backend/internal/handlers/oauth.go @@ -71,7 +71,7 @@ func (h *OAuthHandler) SessionLogin(c *gin.Context) { return } - c.Status(http.StatusOK) + c.JSON(http.StatusOK, gin.H{}) } func (h *OAuthHandler) SessionAttach(c *gin.Context) { diff --git a/kotosoft-id-backend/internal/handlers/positions.go b/kotosoft-id-backend/internal/handlers/positions.go new file mode 100644 index 0000000..55f7ada --- /dev/null +++ b/kotosoft-id-backend/internal/handlers/positions.go @@ -0,0 +1,117 @@ +package handlers + +import ( + "net/http" + + "github.com/dusiburg/kotosoft-id/internal/models" + "github.com/dusiburg/kotosoft-id/internal/services" + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +type PositionsHandler struct { + svc *services.Service +} + +func NewPositionsHandler(svc *services.Service) *PositionsHandler { + return &PositionsHandler{svc: svc} +} + +func localeFromRequest(c *gin.Context) string { + if l := c.GetHeader("X-Locale"); l != "" { + return l + } + if l := c.GetHeader("Accept-Language"); l != "" { + return l + } + return "ru" +} + +func userIDFromContext(c *gin.Context) (uuid.UUID, bool) { + v, ok := c.Get("user_id") + if !ok { + return uuid.Nil, false + } + id, ok := v.(uuid.UUID) + return id, ok +} + +func (h *PositionsHandler) GetMyPositions(c *gin.Context) { + userID, ok := userIDFromContext(c) + if !ok { + c.Error(models.ErrUnauthorized) + return + } + + positions, err := h.svc.GetUserPositions(c.Request.Context(), userID, localeFromRequest(c)) + if err != nil { + c.Error(models.ErrInternal) + return + } + + c.JSON(http.StatusOK, positions) +} + +type upsertPositionRequest struct { + Code string `json:"code" binding:"required"` + Name string `json:"name" binding:"required"` + Description *string `json:"description"` +} + +func (h *PositionsHandler) ListPositions(c *gin.Context) { + userID, ok := userIDFromContext(c) + if !ok { + c.Error(models.ErrUnauthorized) + return + } + + isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID) + if err != nil { + c.Error(models.ErrInternal) + return + } + if !isAdmin { + c.Error(models.ErrForbidden) + return + } + + positions, err := h.svc.GetAllPositions(c.Request.Context(), localeFromRequest(c)) + if err != nil { + c.Error(models.ErrInternal) + return + } + + c.JSON(http.StatusOK, positions) +} + +func (h *PositionsHandler) UpsertPosition(c *gin.Context) { + userID, ok := userIDFromContext(c) + if !ok { + c.Error(models.ErrUnauthorized) + return + } + + isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID) + if err != nil { + c.Error(models.ErrInternal) + return + } + if !isAdmin { + c.Error(models.ErrForbidden) + return + } + + var req upsertPositionRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.Error(models.ErrBadRequest) + return + } + + if err := h.svc.UpsertPositionForLocale(c.Request.Context(), req.Code, localeFromRequest(c), req.Name, req.Description); err != nil { + c.Error(models.ErrInternal) + return + } + + c.Status(http.StatusNoContent) +} + diff --git a/kotosoft-id-backend/internal/http/router.go b/kotosoft-id-backend/internal/http/router.go index 842f2d1..4c5a652 100644 --- a/kotosoft-id-backend/internal/http/router.go +++ b/kotosoft-id-backend/internal/http/router.go @@ -12,7 +12,7 @@ import ( "github.com/google/uuid" ) -func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, svc *services.Service, repo *repositories.OAuthRepository, limiter *services.RateLimiter) *gin.Engine { +func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, positions *handlers.PositionsHandler, svc *services.Service, repo *repositories.OAuthRepository, limiter *services.RateLimiter) *gin.Engine { r := gin.Default() r.Use(errorMiddleware()) @@ -39,6 +39,11 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile) me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents) me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess) + me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions) + + admin := api.Group("/admin") + admin.GET("/positions", authMiddleware(svc, repo), positions.ListPositions) + admin.POST("/positions", authMiddleware(svc, repo), positions.UpsertPosition) } return r diff --git a/kotosoft-id-backend/internal/middleware/ratelimiter.go b/kotosoft-id-backend/internal/middleware/ratelimiter.go index 451d4d0..3b636b4 100644 --- a/kotosoft-id-backend/internal/middleware/ratelimiter.go +++ b/kotosoft-id-backend/internal/middleware/ratelimiter.go @@ -32,14 +32,6 @@ func RateLimit( } func LoginKeyFn(c *gin.Context) string { - var body struct { - Email string `json:"email"` - } - - _ = c.ShouldBindBodyWithJSON(&body) - if body.Email != "" { - return "login:" + c.ClientIP() + ":" + body.Email - } return "login:" + c.ClientIP() } diff --git a/kotosoft-id-backend/internal/models/position.go b/kotosoft-id-backend/internal/models/position.go new file mode 100644 index 0000000..dec793d --- /dev/null +++ b/kotosoft-id-backend/internal/models/position.go @@ -0,0 +1,35 @@ +package models + +import ( + "time" + + "github.com/google/uuid" +) + +type Position struct { + ID uuid.UUID `db:"id" json:"id"` + Code string `db:"code" json:"code"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + UpdatedAt time.Time `db:"updated_at" json:"updated_at"` +} + +type PositionTranslation struct { + PositionID uuid.UUID `db:"position_id" json:"position_id"` + Locale string `db:"locale" json:"locale"` + Name string `db:"name" json:"name"` + Description *string `db:"description" json:"description,omitempty"` +} + +type UserPosition struct { + ID uuid.UUID `db:"id" json:"id"` + UserID uuid.UUID `db:"user_id" json:"user_id"` + PositionID uuid.UUID `db:"position_id" json:"position_id"` + ValidFrom time.Time `db:"valid_from" json:"valid_from"` + ValidTo *time.Time `db:"valid_to" json:"valid_to,omitempty"` +} + +type PositionLocalized struct { + Code string `json:"code"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` +} diff --git a/kotosoft-id-backend/internal/repositories/positions.go b/kotosoft-id-backend/internal/repositories/positions.go new file mode 100644 index 0000000..fe2b11b --- /dev/null +++ b/kotosoft-id-backend/internal/repositories/positions.go @@ -0,0 +1,128 @@ +package repositories + +import ( + "context" + "strings" + + "github.com/dusiburg/kotosoft-id/internal/models" + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" +) + +type PositionRepository struct { + db *pgxpool.Pool +} + +func NewPositionRepository(db *pgxpool.Pool) *PositionRepository { + return &PositionRepository{db: db} +} + +func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error) { + rows, err := r.db.Query(ctx, ` + SELECT p.code, + COALESCE(pt.name, p.code) AS name, pt.description + FROM user_positions up + JOIN positions p ON up.position_id = p.id + LEFT JOIN position_translations pt + ON pt.position_id = p.id + AND pt.locale = $2 + WHERE up.user_id = $1 + AND (up.valid_to IS NULL OR up.valid_to > now()) + ORDER BY name + `, userID, strings.ToLower(locale)) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []models.PositionLocalized + for rows.Next() { + var p models.PositionLocalized + if err := rows.Scan(&p.Code, &p.Name, &p.Description); err != nil { + return nil, err + } + result = append(result, p) + } + return result, rows.Err() +} + +func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) { + rows, err := r.db.Query(ctx, ` + SELECT p.code, + COALESCE(pt.name, p.code) AS name, pt.description + FROM positions p + LEFT JOIN position_translations pt + ON pt.position_id = p.id + AND pt.locale = $1 + ORDER BY name + `, strings.ToLower(locale)) + + if err != nil { + return nil, err + } + + defer rows.Close() + + var result []models.PositionLocalized + for rows.Next() { + var p models.PositionLocalized + if err := rows.Scan(&p.Code, &p.Name, &p.Description); err != nil { + return nil, err + } + result = append(result, p) + } + return result, rows.Err() +} + +func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error { + tx, err := r.db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + + var positionID uuid.UUID + err = tx.QueryRow(ctx, ` + INSERT INTO positions (code) + VALUES ($1) + ON CONFLICT (code) DO UPDATE + SET updated_at = now() + RETURNING id + `, code).Scan(&positionID) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, ` + INSERT INTO position_translations (position_id, locale, name, description) + VALUES ($1, $2, $3, $4) + ON CONFLICT (position_id, locale) DO UPDATE + SET name = EXCLUDED.name, + description = EXCLUDED.description + `, positionID, strings.ToLower(locale), name, description) + + if err != nil { + return err + } + + return tx.Commit(ctx) +} + +func (r *PositionRepository) UserHasPosition(ctx context.Context, userID uuid.UUID, code string) (bool, error) { + var exists bool + err := r.db.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 + FROM user_positions up + JOIN positions p ON up.position_id = p.id + WHERE up.user_id = $1 + AND p.code = $2 + AND (up.valid_to IS NULL OR up.valid_to > now()) + ) + `, userID, code).Scan(&exists) + + if err != nil { + return false, err + } + return exists, nil +} diff --git a/kotosoft-id-backend/internal/services/oauth.go b/kotosoft-id-backend/internal/services/oauth.go index 7ba8845..4a960de 100644 --- a/kotosoft-id-backend/internal/services/oauth.go +++ b/kotosoft-id-backend/internal/services/oauth.go @@ -3,6 +3,7 @@ package services import ( "context" "encoding/json" + "fmt" "net/url" "strings" "time" @@ -100,7 +101,12 @@ func (s *Service) SessionLogin(ctx context.Context, token, email, password strin } user, err := s.users.GetUserByEmail(ctx, email) - if err != nil || bcryptCompare(user.PasswordHash, password) != nil { + compareErr := error(nil) + if err == nil { + compareErr = bcryptCompare(user.PasswordHash, password) + } + + if err != nil || compareErr != nil { return "", ErrAccessDenied } @@ -321,6 +327,9 @@ func (s *Service) issuePair(ctx context.Context, user *models.User, clientID uui return nil, models.ErrInternal } + // Track issued access tokens per user and client to support revocation. + _ = s.redis.SAdd(ctx, fmt.Sprintf("user_client_tokens:%s:%s", user.ID, clientID), accessToken).Err() + _, err = s.oauth.CreateRefreshToken(ctx, models.RefreshTokenRow{ TokenHash: sha256Hex(rawRefresh), UserID: user.ID, diff --git a/kotosoft-id-backend/internal/services/positions.go b/kotosoft-id-backend/internal/services/positions.go new file mode 100644 index 0000000..b64fba1 --- /dev/null +++ b/kotosoft-id-backend/internal/services/positions.go @@ -0,0 +1,35 @@ +package services + +import ( + "context" + + "github.com/dusiburg/kotosoft-id/internal/models" + "github.com/google/uuid" +) + +const adminPositionCode = "PRESIDENT" + +func (s *Service) GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error) { + if locale == "" { + locale = "en" + } + return s.positions.GetUserPositions(ctx, userID, locale) +} + +func (s *Service) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) { + if locale == "" { + locale = "en" + } + return s.positions.GetAllPositions(ctx, locale) +} + +func (s *Service) UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error { + if locale == "" { + locale = "en" + } + return s.positions.UpsertPositionForLocale(ctx, code, locale, name, description) +} + +func (s *Service) UserIsPositionsAdmin(ctx context.Context, userID uuid.UUID) (bool, error) { + return s.positions.UserHasPosition(ctx, userID, adminPositionCode) +} diff --git a/kotosoft-id-backend/internal/services/ratelimiter.go b/kotosoft-id-backend/internal/services/ratelimiter.go index b166bed..706053e 100644 --- a/kotosoft-id-backend/internal/services/ratelimiter.go +++ b/kotosoft-id-backend/internal/services/ratelimiter.go @@ -57,10 +57,7 @@ func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig } count := int(incrCmd.Val()) - remaining := cfg.Max - count - if remaining < 0 { - remaining = 0 - } + remaining := max(cfg.Max-count, 0) if count > cfg.Max { if cfg.BlockFor > 0 { diff --git a/kotosoft-id-backend/internal/services/service.go b/kotosoft-id-backend/internal/services/service.go index dce369c..b1951e0 100644 --- a/kotosoft-id-backend/internal/services/service.go +++ b/kotosoft-id-backend/internal/services/service.go @@ -45,6 +45,13 @@ type OAuthRepo interface { RevokeConsent(ctx context.Context, userID, clientID uuid.UUID, revokedBy *uuid.UUID) error } +type PositionRepo interface { + GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error) + GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) + UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error + UserHasPosition(ctx context.Context, userID uuid.UUID, code string) (bool, error) +} + type TokenConfig struct { AccessTTL time.Duration RefreshTTL time.Duration @@ -56,23 +63,26 @@ type ClientAuth struct { } type Service struct { - users UserRepo - oauth OAuthRepo - redis *redis.Client - tokens TokenConfig + users UserRepo + oauth OAuthRepo + positions PositionRepo + redis *redis.Client + tokens TokenConfig } func New( users UserRepo, oauth OAuthRepo, + positions PositionRepo, rdb *redis.Client, tokenCfg TokenConfig, ) *Service { return &Service{ - users: users, - oauth: oauth, - redis: rdb, - tokens: tokenCfg, + users: users, + oauth: oauth, + positions: positions, + redis: rdb, + tokens: tokenCfg, } } diff --git a/kotosoft-id-backend/migrations/migrations.sql b/kotosoft-id-backend/migrations/migrations.sql index e143068..7e15818 100644 --- a/kotosoft-id-backend/migrations/migrations.sql +++ b/kotosoft-id-backend/migrations/migrations.sql @@ -85,4 +85,32 @@ WHERE revoked_at IS NULL; CREATE INDEX IF NOT EXISTS idx_user_consents_user_id ON public.user_consents(user_id); CREATE INDEX IF NOT EXISTS idx_user_consents_client_id ON public.user_consents(client_id); -CREATE INDEX IF NOT EXISTS idx_user_consents_revoked ON public.user_consents(revoked_at) WHERE revoked_at IS NOT NULL; \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_user_consents_revoked ON public.user_consents(revoked_at) WHERE revoked_at IS NOT NULL; + +CREATE TABLE IF NOT EXISTS public.positions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + code text NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS public.position_translations ( + position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE, + locale text NOT NULL, + name text NOT NULL, + description text, + PRIMARY KEY (position_id, locale) +); + +CREATE TABLE IF NOT EXISTS public.user_positions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE, + position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE, + valid_from timestamptz NOT NULL DEFAULT now(), + valid_to timestamptz, + CONSTRAINT user_positions_unique_active UNIQUE (user_id, position_id) + DEFERRABLE INITIALLY IMMEDIATE +); + +CREATE INDEX IF NOT EXISTS idx_user_positions_user_id ON public.user_positions(user_id); +CREATE INDEX IF NOT EXISTS idx_user_positions_position_id ON public.user_positions(position_id); \ No newline at end of file diff --git a/kotosoft-id-frontend/actions/auth.ts b/kotosoft-id-frontend/actions/auth.ts index 7aae35f..351f8c5 100644 --- a/kotosoft-id-frontend/actions/auth.ts +++ b/kotosoft-id-frontend/actions/auth.ts @@ -92,7 +92,7 @@ export async function SessionLogin( if (data.redirect_url) return { success: true, redirectURL: data.redirect_url }; return { success: true }; - } catch { + } catch (error) { return { success: false, message: t("serverError") }; } } diff --git a/kotosoft-id-frontend/actions/consents.ts b/kotosoft-id-frontend/actions/consents.ts index 974ce0e..41ffc7d 100644 --- a/kotosoft-id-frontend/actions/consents.ts +++ b/kotosoft-id-frontend/actions/consents.ts @@ -19,7 +19,7 @@ export async function getConsents() { if (!response.ok) return [] const consents = await response.json() as Consent[] - consents.forEach((consent: Consent) => { + consents?.forEach((consent: Consent) => { consent.isRevokable = consent.client_id !== process.env.CLIENT_ID }) diff --git a/kotosoft-id-frontend/actions/positions.ts b/kotosoft-id-frontend/actions/positions.ts new file mode 100644 index 0000000..577be5b --- /dev/null +++ b/kotosoft-id-frontend/actions/positions.ts @@ -0,0 +1,68 @@ +"use server" + +import type { Position } from "@/types" +import { cookies } from "next/headers" + +export async function getMyPositions(): Promise { + const store = await cookies() + const accessToken = store.get("access_token")?.value + if (!accessToken) return [] + + const response = await fetch( + `${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/positions`, + { + headers: { + Authorization: `Bearer ${accessToken}`, + }, + cache: "no-store", + } + ) + + if (!response.ok) return [] + return (await response.json()) as Position[] +} + +export async function listAllPositions(): Promise { + const store = await cookies() + const accessToken = store.get("access_token")?.value + if (!accessToken) return null + + const response = await fetch( + `${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, + { + headers: { + Authorization: `Bearer ${accessToken}`, + }, + cache: "no-store", + } + ) + + if (response.status === 403) return null + if (!response.ok) return null + return (await response.json()) as Position[] +} + +export async function upsertPosition(code: string, name: string, description?: string | null): Promise<{ success: boolean }> { + const store = await cookies() + const accessToken = store.get("access_token")?.value + if (!accessToken) return { success: false } + + const response = await fetch( + `${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, + { + method: "POST", + headers: { + Authorization: `Bearer ${accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ code, name, ...(description ? { description } : {}) }), + } + ) + + if (!response.ok) { + return { success: false } + } + + return { success: true } +} + diff --git a/kotosoft-id-frontend/app/api/auth/initiate/route.ts b/kotosoft-id-frontend/app/api/auth/initiate/route.ts index 2d1a6e7..4d882c6 100644 --- a/kotosoft-id-frontend/app/api/auth/initiate/route.ts +++ b/kotosoft-id-frontend/app/api/auth/initiate/route.ts @@ -15,7 +15,7 @@ export async function GET() { const params = new URLSearchParams({ client_id: process.env.CLIENT_ID!, redirect_uri: `${process.env.PUBLIC_URL}/api/callback`, - scope: "profile:read profile:edit profile:consent:read", + scope: "profile:read profile:edit profile:consent:read profile:consent:delete", response_type: "code", code_challenge: challenge, code_challenge_method: "S256", diff --git a/kotosoft-id-frontend/app/me/component.tsx b/kotosoft-id-frontend/app/me/component.tsx index 44edb50..aea541f 100644 --- a/kotosoft-id-frontend/app/me/component.tsx +++ b/kotosoft-id-frontend/app/me/component.tsx @@ -10,6 +10,7 @@ import { useState } from "react"; import { Logout } from "@/actions/auth"; import Profile from "./items/profile"; import Applications from "./items/applications"; +import Positions from "./items/positions"; interface Props { userData: User | null; @@ -26,7 +27,7 @@ export default function MeClient({ userData, consentsData }: Props) { const items = [ {"name": t("items.profile.title"), "icon": , "component": }, {"name": t("items.applications.title"), "icon": , "component": }, - {"name": t("items.positions.title"), "icon": }, + {"name": t("items.positions.title"), "icon": , "component": }, ] return ( diff --git a/kotosoft-id-frontend/app/me/items/applications.tsx b/kotosoft-id-frontend/app/me/items/applications.tsx index 49866b7..e4510db 100644 --- a/kotosoft-id-frontend/app/me/items/applications.tsx +++ b/kotosoft-id-frontend/app/me/items/applications.tsx @@ -2,13 +2,16 @@ import { useLocale, useTranslations } from "next-intl"; import type { Consent } from "@/types"; -import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item" +import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"; import { Button } from "@/components/ui/button"; +import { Spinner } from "@/components/ui/spinner"; import { localeMap } from "@/types"; import { enUS } from "date-fns/locale"; import { format } from "date-fns"; import { revokeConsent } from "@/actions/consents"; import { useState } from "react"; +import { toast } from "sonner"; +import { Check, X } from "lucide-react"; interface Props { consents: Consent[] | null; @@ -18,16 +21,29 @@ interface Props { export default function Applications({ consents, setConsents }: Props) { const t = useTranslations("MePage.items.applications"); const [list, setList] = useState(consents); + const [revokingId, setRevokingId] = useState(null); const locale = useLocale(); const dateLocale = localeMap[locale as keyof typeof localeMap] ?? enUS; const handleRevoke = async (clientId: string) => { - const result = await revokeConsent(clientId); - if (result.success) { - const updated = list?.filter(c => c.client_id !== clientId) ?? []; - setList(updated); - setConsents(updated); + if (revokingId) return; + setRevokingId(clientId); + + try { + const result = await revokeConsent(clientId); + if (result.success) { + const updated = list?.filter((c) => c.client_id !== clientId) ?? []; + setList(updated); + setConsents(updated); + toast(t("successfullyRevoked"), { icon: }); + } else { + toast(t("revocationError"), { icon: }); + } + } catch { + toast(t("revocationError"), { icon: }); + } finally { + setRevokingId(null); } }; @@ -40,18 +56,23 @@ export default function Applications({ consents, setConsents }: Props) { {consent.client_name} - {t("authorized")} {format(consent.authorized_at, "PPP", { locale: dateLocale })} + + {t("authorized")}{" "} + {format(consent.authorized_at, "PPP", { locale: dateLocale })} + ))} + {list == null &&

{t("noConsents")}

} ); diff --git a/kotosoft-id-frontend/app/me/items/positions.tsx b/kotosoft-id-frontend/app/me/items/positions.tsx new file mode 100644 index 0000000..1cfcb0e --- /dev/null +++ b/kotosoft-id-frontend/app/me/items/positions.tsx @@ -0,0 +1,144 @@ +"use client" + +import { useEffect, useState } from "react" +import { useTranslations } from "next-intl" +import type { Position } from "@/types" +import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field" +import { Spinner } from "@/components/ui/spinner" +import { listAllPositions, upsertPosition, getMyPositions } from "@/actions/positions" +import { toast } from "sonner" +import { Check, X } from "lucide-react" + +export default function Positions() { + const t = useTranslations("MePage.items.positions") + + const [positions, setPositions] = useState(null) + const [isAdmin, setIsAdmin] = useState(null) + const [loading, setLoading] = useState(true) + + const [code, setCode] = useState("") + const [name, setName] = useState("") + const [description, setDescription] = useState("") + const [saving, setSaving] = useState(false) + const [formError, setFormError] = useState(null) + + useEffect(() => { + const load = async () => { + setLoading(true) + try { + const [own, all] = await Promise.all([getMyPositions(), listAllPositions()]) + setPositions(all ?? own) + setIsAdmin(all !== null) + } finally { + setLoading(false) + } + } + void load() + }, []) + + const handleSave = async () => { + setFormError(null) + if (!code || !name) { + setFormError(t("form.required")) + return + } + + setSaving(true) + try { + const result = await upsertPosition(code, name, description || undefined) + if (!result.success) { + toast(t("form.saveError"), { icon: }) + return + } + + const updated = await listAllPositions() + if (updated) setPositions(updated) + + toast(t("form.saved"), { icon: }) + setCode("") + setName("") + setDescription("") + } finally { + setSaving(false) + } + } + + return ( +
+

{t("title")}

+ + {loading && ( +
+ + {t("loading")} +
+ )} + + {!loading && ( + <> +
+ {positions?.map((position) => ( + + + {position.name} + + {position.description || t("noDescription")} + + + + ))} + {(!positions || positions.length === 0) && ( +

{t("empty")}

+ )} +
+ + {isAdmin && ( +
+

{t("form.title")}

+ + + {t("form.code")} + setCode(e.target.value.toUpperCase())} + disabled={saving} + /> + + + {t("form.name")} + setName(e.target.value)} + disabled={saving} + /> + + + {t("form.description")} + setDescription(e.target.value)} + disabled={saving} + /> + + {formError && {formError}} + + + + +
+ )} + + )} +
+ ) +} + diff --git a/kotosoft-id-frontend/app/me/items/profile.tsx b/kotosoft-id-frontend/app/me/items/profile.tsx index 8164e00..edf1bb2 100644 --- a/kotosoft-id-frontend/app/me/items/profile.tsx +++ b/kotosoft-id-frontend/app/me/items/profile.tsx @@ -1,6 +1,5 @@ "use client" -import { useState } from "react"; import { useTranslations } from "next-intl"; import { useForm, Controller, SubmitHandler } from "react-hook-form"; import type { User } from "@/types"; @@ -10,6 +9,8 @@ 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 { toast } from "sonner"; +import { Check, X } from "lucide-react"; interface Props { user: User | null; @@ -24,7 +25,6 @@ interface FormData { export default function Profile({ user, setUser }: Props) { const t = useTranslations("MePage.items.profile"); - const [error, setError] = useState(null); const { register, handleSubmit, control, formState: { errors, isSubmitting } } = useForm({ defaultValues: { @@ -35,15 +35,16 @@ export default function Profile({ user, setUser }: Props) { }); const onSubmit: SubmitHandler = async (data) => { - setError(null); - try { const response = await UpdateUser(data.first_name, data.second_name, data.birth_date); - if (response == null) setError(t("form.updateError")) - else setUser(response) + if (response == null) toast(t("form.updateError"), { icon: }) + else { + setUser(response) + toast(t("form.successfullyUpdated"), { icon: }) + } } catch { - setError(t("form.updateError")) + toast(t("form.updateError"), { icon: }) } }; @@ -106,7 +107,6 @@ export default function Profile({ user, setUser }: Props) { {isSubmitting && } {t("form.save")} - {error && {error}} diff --git a/kotosoft-id-frontend/app/register/page.tsx b/kotosoft-id-frontend/app/register/page.tsx index 0330795..d97a013 100644 --- a/kotosoft-id-frontend/app/register/page.tsx +++ b/kotosoft-id-frontend/app/register/page.tsx @@ -14,7 +14,6 @@ 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 { toast } from "sonner"; interface FormData { email: string; @@ -41,7 +40,6 @@ export default function RegisterPage() { return; } - toast(t("registeredSuccessfully"), { icon: }) router.push(`/login`); }; diff --git a/kotosoft-id-frontend/messages/en.json b/kotosoft-id-frontend/messages/en.json index d334c8b..d78f910 100644 --- a/kotosoft-id-frontend/messages/en.json +++ b/kotosoft-id-frontend/messages/en.json @@ -77,10 +77,25 @@ "applications": { "title": "Applications", "authorized": "Autorized on", - "revoke": "Revoke" + "revoke": "Revoke", + "successfullyRevoked": "Access successfully revoked!", + "revocationError": "Failed to revoke access" }, "positions": { - "title": "Positions" + "title": "Positions", + "loading": "Loading positions…", + "empty": "You don't have any positions yet.", + "noDescription": "No description", + "form": { + "title": "Manage positions", + "code": "Code", + "name": "Name", + "description": "Description", + "save": "Save", + "required": "Please fill in all required fields", + "saved": "Position saved successfully", + "saveError": "Failed to save position" + } }, "logout": "Logout" } diff --git a/kotosoft-id-frontend/messages/it.json b/kotosoft-id-frontend/messages/it.json index 6084820..072eb82 100644 --- a/kotosoft-id-frontend/messages/it.json +++ b/kotosoft-id-frontend/messages/it.json @@ -77,10 +77,25 @@ "applications": { "title": "Applicazioni", "authorized": "Autorizzato il", - "revoke": "Revoca" + "revoke": "Revoca", + "successfullyRevoked": "Accesso all'applicazione revocato con successo!", + "revocationError": "Impossibile revocare l'accesso all'applicazione" }, "positions": { - "title": "Posizioni" + "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" + } }, "logout": "Esci" } diff --git a/kotosoft-id-frontend/messages/ru.json b/kotosoft-id-frontend/messages/ru.json index f0caeae..923462b 100644 --- a/kotosoft-id-frontend/messages/ru.json +++ b/kotosoft-id-frontend/messages/ru.json @@ -77,10 +77,25 @@ "applications": { "title": "Приложения", "authorized": "Авторизировано", - "revoke": "Отозвать" + "revoke": "Отозвать", + "successfullyRevoked": "Доступ приложения успешно отозван!", + "revocationError": "Не удалось отозвать доступ приложения" }, "positions": { - "title": "Должности" + "title": "Должности", + "loading": "Загружаем должности…", + "empty": "У вас пока нет назначенных должностей.", + "noDescription": "Без описания", + "form": { + "title": "Управление должностями", + "code": "Код должности", + "name": "Название", + "description": "Описание", + "save": "Сохранить", + "required": "Заполните обязательные поля", + "saved": "Должность успешно сохранена", + "saveError": "Не удалось сохранить должность" + } }, "logout": "Выйти" } diff --git a/kotosoft-id-frontend/types.ts b/kotosoft-id-frontend/types.ts index 416c0d3..25e966a 100644 --- a/kotosoft-id-frontend/types.ts +++ b/kotosoft-id-frontend/types.ts @@ -31,6 +31,11 @@ export interface Consent { isRevokable: boolean } +export interface Position { + code: string + name: string + description?: string | null +} export const localeMap = { ru,