new version
This commit is contained in:
+3
-2
@@ -10,12 +10,10 @@ services:
|
||||
REDIS_URL: ${REDIS_URL}
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
JWT_EXPIRATION_HOURS: ${JWT_EXPIRATION_HOURS:-24h}
|
||||
|
||||
CLIENT_ID: ${CLIENT_ID}
|
||||
CLIENT_SECRET: ${CLIENT_SECRET}
|
||||
CLIENT_NAME: ${CLIENT_NAME}
|
||||
CLIENT_REDIRECT_URIS: ${CLIENT_REDIRECT_URIS}
|
||||
|
||||
VIRTUAL_HOST: ${API_DOMAIN}
|
||||
VIRTUAL_PORT: 8080
|
||||
LETSENCRYPT_HOST: ${API_DOMAIN}
|
||||
@@ -25,6 +23,7 @@ services:
|
||||
networks:
|
||||
- kotosoft_id_network
|
||||
- proxy
|
||||
- eu_net
|
||||
|
||||
kotosoft_id_frontend:
|
||||
image: localhost:5000/kotosoft_id_frontend:latest
|
||||
@@ -50,4 +49,6 @@ networks:
|
||||
kotosoft_id_network:
|
||||
driver: bridge
|
||||
proxy:
|
||||
external: true
|
||||
eu_net:
|
||||
external: true
|
||||
@@ -34,10 +34,22 @@ func NewRouter(
|
||||
middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn),
|
||||
oauth.SessionLogin,
|
||||
)
|
||||
o.POST("/session/attach", oauth.SessionAttach)
|
||||
o.POST("/session/approve", oauth.SessionApprove)
|
||||
o.POST("/token", oauth.Token)
|
||||
o.POST("/revoke", oauth.Revoke)
|
||||
o.POST("/session/attach",
|
||||
middleware.RateLimit(limiter, services.TokenRateLimit, middleware.IPKeyFn("session_attach")),
|
||||
oauth.SessionAttach,
|
||||
)
|
||||
o.POST("/session/approve",
|
||||
middleware.RateLimit(limiter, services.TokenRateLimit, middleware.IPKeyFn("session_approve")),
|
||||
oauth.SessionApprove,
|
||||
)
|
||||
o.POST("/token",
|
||||
middleware.RateLimit(limiter, services.TokenRateLimit, middleware.TokenKeyFn),
|
||||
oauth.Token,
|
||||
)
|
||||
o.POST("/revoke",
|
||||
middleware.RateLimit(limiter, services.RevokeRateLimit, middleware.RevokeKeyFn),
|
||||
oauth.Revoke,
|
||||
)
|
||||
|
||||
o.POST("/introspect", positions.Introspect)
|
||||
}
|
||||
@@ -49,7 +61,10 @@ func NewRouter(
|
||||
middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")),
|
||||
auth.Register,
|
||||
)
|
||||
a.POST("/refresh", auth.Refresh)
|
||||
a.POST("/refresh",
|
||||
middleware.RateLimit(limiter, services.RefreshRateLimit, middleware.RefreshKeyFn),
|
||||
auth.Refresh,
|
||||
)
|
||||
|
||||
me := api.Group("/me")
|
||||
me.GET("", authMiddleware(svc, repo, "profile:read"), auth.Profile)
|
||||
|
||||
@@ -41,6 +41,18 @@ func IPKeyFn(prefix string) func(c *gin.Context) string {
|
||||
}
|
||||
}
|
||||
|
||||
func TokenKeyFn(c *gin.Context) string {
|
||||
return "token:" + c.ClientIP()
|
||||
}
|
||||
|
||||
func RevokeKeyFn(c *gin.Context) string {
|
||||
return "revoke:" + c.ClientIP()
|
||||
}
|
||||
|
||||
func RefreshKeyFn(c *gin.Context) string {
|
||||
return "refresh:" + c.ClientIP()
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
if n < 0 {
|
||||
return "0"
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
type OAuthClient struct {
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
ClientID string `db:"client_id" json:"client_id"`
|
||||
ClientSecret string `db:"client_secret" json:"client_secret"`
|
||||
ClientSecret string `db:"client_secret" json:"-"`
|
||||
Name string `db:"name" json:"name"`
|
||||
RedirectURIs json.RawMessage `db:"redirect_uris" json:"redirect_uris"`
|
||||
GrantTypes json.RawMessage `db:"grant_types" json:"grant_types"`
|
||||
|
||||
@@ -211,24 +211,32 @@ func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.U
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.PositionLocalized
|
||||
var positions []posRow
|
||||
for rows.Next() {
|
||||
var p models.PositionLocalized
|
||||
var positionID uuid.UUID
|
||||
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
|
||||
var r posRow
|
||||
if err := rows.Scan(&r.id, &r.p.Code, &r.p.Name, &r.p.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
perms, err := r.GetPositionPermissions(ctx, positionID, locale)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Permissions = perms
|
||||
if p.Permissions == nil {
|
||||
p.Permissions = []models.Permission{}
|
||||
}
|
||||
result = append(result, p)
|
||||
positions = append(positions, r)
|
||||
}
|
||||
return result, rows.Err()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
permMap, err := r.getPositionPermissionsBatch(ctx, positionIDs(positions), locale)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]models.PositionLocalized, len(positions))
|
||||
for i, pos := range positions {
|
||||
pos.p.Permissions = permMap[pos.id]
|
||||
if pos.p.Permissions == nil {
|
||||
pos.p.Permissions = []models.Permission{}
|
||||
}
|
||||
result[i] = pos.p
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) {
|
||||
@@ -246,24 +254,32 @@ func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.PositionLocalized
|
||||
var positions []posRow
|
||||
for rows.Next() {
|
||||
var p models.PositionLocalized
|
||||
var positionID uuid.UUID
|
||||
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
|
||||
var r posRow
|
||||
if err := rows.Scan(&r.id, &r.p.Code, &r.p.Name, &r.p.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
perms, err := r.GetPositionPermissions(ctx, positionID, locale)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Permissions = perms
|
||||
if p.Permissions == nil {
|
||||
p.Permissions = []models.Permission{}
|
||||
}
|
||||
result = append(result, p)
|
||||
positions = append(positions, r)
|
||||
}
|
||||
return result, rows.Err()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
permMap, err := r.getPositionPermissionsBatch(ctx, positionIDs(positions), locale)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]models.PositionLocalized, len(positions))
|
||||
for i, pos := range positions {
|
||||
pos.p.Permissions = permMap[pos.id]
|
||||
if pos.p.Permissions == nil {
|
||||
pos.p.Permissions = []models.Permission{}
|
||||
}
|
||||
result[i] = pos.p
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetUsersWithPositions(ctx context.Context, locale string) ([]models.UserWithPositions, error) {
|
||||
@@ -295,7 +311,57 @@ func (r *PositionRepository) GetUsersWithPositions(ctx context.Context, locale s
|
||||
|
||||
result = append(result, u)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
type posRow struct {
|
||||
id uuid.UUID
|
||||
p models.PositionLocalized
|
||||
}
|
||||
|
||||
func (pr posRow) getID() uuid.UUID { return pr.id }
|
||||
|
||||
func positionIDs(items []posRow) []uuid.UUID {
|
||||
ids := make([]uuid.UUID, len(items))
|
||||
for i, item := range items {
|
||||
ids[i] = item.id
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func (r *PositionRepository) getPositionPermissionsBatch(ctx context.Context, pIDs []uuid.UUID, locale string) (map[uuid.UUID][]models.Permission, error) {
|
||||
if len(pIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT pp.position_id,
|
||||
p.id, p.code,
|
||||
COALESCE(pl.name, pe.name, p.code) AS name,
|
||||
COALESCE(pl.description, pe.description, p.description, '') AS description,
|
||||
p.created_at
|
||||
FROM position_permissions pp
|
||||
JOIN permissions p ON pp.permission_id = p.id
|
||||
LEFT JOIN permission_translations pl
|
||||
ON pl.permission_id = p.id AND pl.locale = $2
|
||||
LEFT JOIN permission_translations pe
|
||||
ON pe.permission_id = p.id AND pe.locale = 'en'
|
||||
WHERE pp.position_id = ANY($1)
|
||||
ORDER BY pp.position_id, p.code
|
||||
`, pIDs, strings.ToLower(locale))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[uuid.UUID][]models.Permission)
|
||||
for rows.Next() {
|
||||
var positionID uuid.UUID
|
||||
var perm models.Permission
|
||||
if err := rows.Scan(&positionID, &perm.ID, &perm.Code, &perm.Name, &perm.Description, &perm.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[positionID] = append(result[positionID], perm)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
|
||||
@@ -88,10 +88,7 @@ func redirectURIMatches(redirectURIsJSON json.RawMessage, redirectURI string) bo
|
||||
}
|
||||
|
||||
func verifyClientSecret(stored, provided string) bool {
|
||||
if stored == "" {
|
||||
return true
|
||||
}
|
||||
if provided == "" {
|
||||
if stored == "" || provided == "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(stored, "$2") {
|
||||
|
||||
@@ -268,7 +268,9 @@ func (s *Service) RevokeToken(ctx context.Context, auth ClientAuth, rawToken str
|
||||
return nil
|
||||
}
|
||||
|
||||
_ = s.oauth.DeleteRefreshTokenByID(ctx, row.ID)
|
||||
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
|
||||
return models.ErrInternal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,23 @@ var (
|
||||
Max: 5,
|
||||
Window: time.Hour,
|
||||
}
|
||||
|
||||
TokenRateLimit = RateLimitConfig{
|
||||
Max: 20,
|
||||
Window: time.Minute,
|
||||
BlockFor: 5 * time.Minute,
|
||||
}
|
||||
|
||||
RevokeRateLimit = RateLimitConfig{
|
||||
Max: 30,
|
||||
Window: time.Minute,
|
||||
}
|
||||
|
||||
RefreshRateLimit = RateLimitConfig{
|
||||
Max: 30,
|
||||
Window: time.Minute,
|
||||
BlockFor: 5 * time.Minute,
|
||||
}
|
||||
)
|
||||
|
||||
type RateLimiter struct {
|
||||
@@ -42,7 +59,7 @@ func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig
|
||||
if cfg.BlockFor > 0 {
|
||||
blocked, err := r.redis.Exists(ctx, blockKey).Result()
|
||||
if err != nil {
|
||||
return true, 0, nil
|
||||
return false, 0, fmt.Errorf("rate limiter: %w", err)
|
||||
}
|
||||
if blocked > 0 {
|
||||
return false, 0, nil
|
||||
@@ -53,7 +70,7 @@ func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig
|
||||
incrCmd := pipe.Incr(ctx, counterKey)
|
||||
pipe.Expire(ctx, counterKey, cfg.Window)
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return true, 0, nil
|
||||
return false, 0, fmt.Errorf("rate limiter: %w", err)
|
||||
}
|
||||
|
||||
count := int(incrCmd.Val())
|
||||
|
||||
@@ -42,19 +42,15 @@ CREATE TABLE IF NOT EXISTS public.authorization_codes (
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_code_hash
|
||||
ON public.authorization_codes (code_hash);
|
||||
|
||||
ON public.authorization_codes (code_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_expires_at
|
||||
ON public.authorization_codes (expires_at);
|
||||
|
||||
ON public.authorization_codes (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_consumed_at
|
||||
ON public.authorization_codes (consumed_at);
|
||||
|
||||
ON public.authorization_codes (consumed_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_user_id
|
||||
ON public.authorization_codes(user_id);
|
||||
|
||||
ON public.authorization_codes (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_authorization_codes_client_id
|
||||
ON public.authorization_codes(client_id);
|
||||
ON public.authorization_codes (client_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.refresh_tokens (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -67,16 +63,13 @@ CREATE TABLE IF NOT EXISTS public.refresh_tokens (
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_token_hash
|
||||
ON public.refresh_tokens (token_hash);
|
||||
|
||||
ON public.refresh_tokens (token_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at
|
||||
ON public.refresh_tokens (expires_at);
|
||||
|
||||
ON public.refresh_tokens (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user_id
|
||||
ON public.refresh_tokens(user_id);
|
||||
|
||||
ON public.refresh_tokens (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_client_id
|
||||
ON public.refresh_tokens(client_id);
|
||||
ON public.refresh_tokens (client_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.user_consents (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -91,18 +84,51 @@ CREATE TABLE IF NOT EXISTS public.user_consents (
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS unique_active_consent
|
||||
ON public.user_consents (user_id, client_id)
|
||||
WHERE revoked_at IS NULL;
|
||||
|
||||
ON public.user_consents (user_id, client_id)
|
||||
WHERE revoked_at IS NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_user_consents_user_id
|
||||
ON public.user_consents(user_id);
|
||||
|
||||
ON public.user_consents (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_consents_client_id
|
||||
ON public.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;
|
||||
ON public.user_consents (revoked_at)
|
||||
WHERE revoked_at IS NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.regions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
code char(2) NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.region_translations (
|
||||
region_id uuid NOT NULL REFERENCES public.regions(id) ON DELETE CASCADE,
|
||||
locale text NOT NULL,
|
||||
name text NOT NULL,
|
||||
PRIMARY KEY (region_id, locale)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_region_translations_region_id
|
||||
ON public.region_translations (region_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.citizenship_applications (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL UNIQUE REFERENCES public.users(id) ON DELETE CASCADE,
|
||||
status text NOT NULL DEFAULT 'pending',
|
||||
region_id uuid REFERENCES public.regions(id),
|
||||
reviewed_by uuid REFERENCES public.users(id),
|
||||
reviewed_at timestamptz,
|
||||
reject_reason text,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.citizens (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL UNIQUE REFERENCES public.users(id),
|
||||
application_id uuid NOT NULL REFERENCES public.citizenship_applications(id),
|
||||
number text NOT NULL UNIQUE,
|
||||
issued_at timestamptz NOT NULL DEFAULT now(),
|
||||
region_id uuid REFERENCES public.regions(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.positions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -120,10 +146,9 @@ CREATE TABLE IF NOT EXISTS public.position_translations (
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_position_translations_position_id
|
||||
ON public.position_translations (position_id);
|
||||
|
||||
ON public.position_translations (position_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_position_translations_locale
|
||||
ON public.position_translations (locale);
|
||||
ON public.position_translations (locale);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.permissions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -140,36 +165,72 @@ CREATE TABLE IF NOT EXISTS public.permission_translations (
|
||||
PRIMARY KEY (permission_id, locale)
|
||||
);
|
||||
|
||||
CREATE TABLE citizenship_applications (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
status text NOT NULL DEFAULT 'pending',
|
||||
region_id uuid REFERENCES regions(id),
|
||||
reviewed_by uuid REFERENCES users(id),
|
||||
reviewed_at timestamptz,
|
||||
reject_reason text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
);
|
||||
|
||||
CREATE TABLE citizens (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL UNIQUE REFERENCES users(id),
|
||||
application_id uuid NOT NULL REFERENCES citizenship_applications(id),
|
||||
number text NOT NULL UNIQUE,
|
||||
issued_at timestamptz NOT NULL DEFAULT now(),
|
||||
region_id uuid REFERENCES regions(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_permission_translations_permission_id
|
||||
ON public.permission_translations (permission_id);
|
||||
|
||||
ON public.permission_translations (permission_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_permission_translations_locale
|
||||
ON public.permission_translations (locale);
|
||||
ON public.permission_translations (locale);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.position_permissions (
|
||||
position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE,
|
||||
permission_id uuid NOT NULL REFERENCES public.permissions(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (position_id, permission_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_position_permissions_position_id
|
||||
ON public.position_permissions (position_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_position_permissions_permission_id
|
||||
ON public.position_permissions (permission_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.user_positions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
|
||||
position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE,
|
||||
valid_from timestamptz NOT NULL DEFAULT now(),
|
||||
valid_to timestamptz,
|
||||
assigned_by uuid REFERENCES public.users(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_positions_user_id
|
||||
ON public.user_positions (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_positions_position_id
|
||||
ON public.user_positions (position_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_positions_unique_active
|
||||
ON public.user_positions (user_id, position_id)
|
||||
WHERE valid_to IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_permissions_code
|
||||
ON public.permissions (code);
|
||||
CREATE INDEX IF NOT EXISTS idx_users_is_admin
|
||||
ON public.users (is_admin)
|
||||
WHERE is_admin = TRUE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.set_updated_at()
|
||||
RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS users_updated_at ON public.users;
|
||||
CREATE TRIGGER users_updated_at
|
||||
BEFORE UPDATE ON public.users
|
||||
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
DROP TRIGGER IF EXISTS oauth_clients_updated_at ON public.oauth_clients;
|
||||
CREATE TRIGGER oauth_clients_updated_at
|
||||
BEFORE UPDATE ON public.oauth_clients
|
||||
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
DROP TRIGGER IF EXISTS positions_updated_at ON public.positions;
|
||||
CREATE TRIGGER positions_updated_at
|
||||
BEFORE UPDATE ON public.positions
|
||||
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
INSERT INTO public.permissions (code, description) VALUES
|
||||
('positions.manage', 'Create and edit positions'),
|
||||
('positions.assign', 'Assign positions to users'),
|
||||
('positions.revoke', 'Revoke positions from users')
|
||||
('positions.assign', 'Assign positions to users'),
|
||||
('positions.revoke', 'Revoke positions from users')
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO public.permission_translations (permission_id, locale, name, description)
|
||||
@@ -218,105 +279,23 @@ ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO public.position_translations (position_id, locale, name, description)
|
||||
SELECT id, 'en', 'Kotosoft ID Staff', 'Default staff position for Kotosoft ID operators'
|
||||
FROM public.positions
|
||||
WHERE code = 'kotosoft_id_staff'
|
||||
FROM public.positions WHERE code = 'kotosoft_id_staff'
|
||||
ON CONFLICT (position_id, locale) DO NOTHING;
|
||||
|
||||
INSERT INTO public.position_translations (position_id, locale, name, description)
|
||||
SELECT id, 'ru', 'Сотрудник Kotosoft ID', 'Базовая должность сотрудника Kotosoft ID'
|
||||
FROM public.positions
|
||||
WHERE code = 'kotosoft_id_staff'
|
||||
FROM public.positions WHERE code = 'kotosoft_id_staff'
|
||||
ON CONFLICT (position_id, locale) DO NOTHING;
|
||||
|
||||
INSERT INTO public.position_translations (position_id, locale, name, description)
|
||||
SELECT id, 'it', 'Operatore Kotosoft ID', 'Posizione predefinita per operatori Kotosoft ID'
|
||||
FROM public.positions
|
||||
WHERE code = 'kotosoft_id_staff'
|
||||
FROM public.positions WHERE code = 'kotosoft_id_staff'
|
||||
ON CONFLICT (position_id, locale) DO NOTHING;
|
||||
|
||||
INSERT INTO public.position_permissions (position_id, permission_id)
|
||||
SELECT p.id, perm.id
|
||||
FROM public.positions p
|
||||
JOIN public.permissions perm ON perm.code IN ('positions.manage', 'positions.assign', 'positions.revoke')
|
||||
JOIN public.permissions perm
|
||||
ON perm.code IN ('positions.manage', 'positions.assign', 'positions.revoke')
|
||||
WHERE p.code = 'kotosoft_id_staff'
|
||||
ON CONFLICT (position_id, permission_id) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.position_permissions (
|
||||
position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE,
|
||||
permission_id uuid NOT NULL REFERENCES public.permissions(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (position_id, permission_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_position_permissions_position_id
|
||||
ON public.position_permissions (position_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_position_permissions_permission_id
|
||||
ON public.position_permissions (permission_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.user_positions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
|
||||
position_id uuid NOT NULL REFERENCES public.positions(id) ON DELETE CASCADE,
|
||||
valid_from timestamptz NOT NULL DEFAULT now(),
|
||||
valid_to timestamptz,
|
||||
assigned_by uuid REFERENCES public.users(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_positions_user_id
|
||||
ON public.user_positions(user_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_positions_position_id
|
||||
ON public.user_positions(position_id);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_positions_unique_active
|
||||
ON public.user_positions (user_id, position_id)
|
||||
WHERE valid_to IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_permissions_code
|
||||
ON public.permissions (code);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_users_is_admin
|
||||
ON public.users (is_admin)
|
||||
WHERE is_admin = TRUE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.set_updated_at()
|
||||
RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS users_updated_at ON public.users;
|
||||
CREATE TRIGGER users_updated_at
|
||||
BEFORE UPDATE ON public.users
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
DROP TRIGGER IF EXISTS oauth_clients_updated_at ON public.oauth_clients;
|
||||
CREATE TRIGGER oauth_clients_updated_at
|
||||
BEFORE UPDATE ON public.oauth_clients
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
DROP TRIGGER IF EXISTS positions_updated_at ON public.positions;
|
||||
CREATE TRIGGER positions_updated_at
|
||||
BEFORE UPDATE ON public.positions
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.regions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
code char(2) NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.region_translations (
|
||||
region_id uuid NOT NULL REFERENCES public.regions(id) ON DELETE CASCADE,
|
||||
locale text NOT NULL,
|
||||
name text NOT NULL,
|
||||
PRIMARY KEY (region_id, locale)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_region_translations_region_id
|
||||
ON public.region_translations (region_id);
|
||||
ON CONFLICT (position_id, permission_id) DO NOTHING;
|
||||
@@ -3,7 +3,7 @@
|
||||
import Header from "@/components/header";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import type { AdminUser, Consent, Document, Permission, Position, User } from "@/types";
|
||||
import type { AdminUser, Citizen, Consent, Permission, Position, User } from "@/types";
|
||||
import { AppWindowMacIcon, BriefcaseBusinessIcon, FileUserIcon, LogOutIcon, ShieldIcon, UserIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -13,11 +13,9 @@ import Profile from "./items/profile";
|
||||
import Applications from "./items/applications";
|
||||
import Positions from "./items/positions";
|
||||
import Admin from "./items/admin";
|
||||
import Documents from "./items/documents";
|
||||
|
||||
interface Props {
|
||||
userData: User | null;
|
||||
documentsData: Document[] | null;
|
||||
consentsData: Consent[] | null;
|
||||
permissionsData: Permission[] | null;
|
||||
positionsData: Position[] | null;
|
||||
@@ -30,7 +28,6 @@ interface Props {
|
||||
|
||||
export default function MeClient({
|
||||
userData,
|
||||
documentsData,
|
||||
consentsData,
|
||||
permissionsData,
|
||||
positionsData,
|
||||
@@ -45,7 +42,6 @@ export default function MeClient({
|
||||
const hydratedRef = useRef(false)
|
||||
|
||||
const [user, setUser] = useState(userData);
|
||||
const [documents, setDocuments] = useState(documentsData);
|
||||
const [consents, setConsents] = useState(consentsData);
|
||||
const [permissions, setPermissions] = useState(permissionsData);
|
||||
const [positions, setPositions] = useState(positionsData);
|
||||
@@ -55,7 +51,6 @@ export default function MeClient({
|
||||
|
||||
const baseItems = useMemo(() => [
|
||||
{ name: t("items.profile.title"), icon: <UserIcon />, component: <Profile user={user} setUser={setUser} /> },
|
||||
{ name: "Documents", icon: <FileUserIcon/>, component: <Documents documents={documents} /> },
|
||||
{ name: t("items.applications.title"), icon: <AppWindowMacIcon />, component: <Applications consents={consents} setConsents={setConsents} /> },
|
||||
{ name: t("items.positions.title"), icon: <BriefcaseBusinessIcon />, component: <Positions /> },
|
||||
], [t, user, consents])
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import type { Document } from "@/types";
|
||||
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 {
|
||||
documents: Document[] | null;
|
||||
}
|
||||
|
||||
export default function Documents({ documents }: Props) {
|
||||
const t = useTranslations("MePage.items.applications");
|
||||
|
||||
const locale = useLocale();
|
||||
|
||||
return (
|
||||
<div className="w-full lg:max-w-sm flex flex-col gap-4">
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl">Documents</h1>
|
||||
<p className="text-sm text-muted-foreground">There you can find all of your documents issued by the European Federation</p>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import MeComponent from "./component";
|
||||
import { fetchConsents } from "@/actions/consents";
|
||||
import { fetchAllPositions, fetchAllPermissions, fetchAdminUsers, fetchMyPositions } from "@/actions/positions";
|
||||
import { getLocale } from "next-intl/server";
|
||||
import { Document } from "@/types";
|
||||
|
||||
export default async function Me() {
|
||||
const locale = await getLocale();
|
||||
@@ -14,8 +13,6 @@ export default async function Me() {
|
||||
redirect("/api/auth/initiate");
|
||||
}
|
||||
|
||||
const documents: Document[] = [];
|
||||
|
||||
const [consents, myPositions] = await Promise.all([
|
||||
fetchConsents(),
|
||||
fetchMyPositions(locale),
|
||||
@@ -35,7 +32,6 @@ export default async function Me() {
|
||||
return (
|
||||
<MeComponent
|
||||
userData={user}
|
||||
documentsData={documents}
|
||||
consentsData={consents}
|
||||
permissionsData={permissions}
|
||||
positionsData={positions}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { getRequestConfig } from "next-intl/server";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
|
||||
const VALID_LOCALES = ["en", "ru", "it"];
|
||||
const DEFAULT_LOCALE = "en";
|
||||
|
||||
export default getRequestConfig(async () => {
|
||||
const store = await cookies();
|
||||
const locale = store.get("locale")?.value || 'en';
|
||||
|
||||
const raw = store.get("locale")?.value;
|
||||
const locale = VALID_LOCALES.includes(raw || "") ? raw! : DEFAULT_LOCALE;
|
||||
|
||||
return {
|
||||
locale,
|
||||
messages: (await import(`../messages/${locale}.json`)).default
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
import type { NextConfig } from "next";
|
||||
import createNextIntlPlugin from "next-intl/plugin";
|
||||
|
||||
const nextConfig: NextConfig = {};
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
headers: async () => [
|
||||
{
|
||||
source: "/(.*)",
|
||||
headers: [
|
||||
{ key: "X-Frame-Options", value: "DENY" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "X-XSS-Protection", value: "1; mode=block" },
|
||||
{ key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
|
||||
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const withNextIntl = createNextIntlPlugin();
|
||||
export default withNextIntl(nextConfig);
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -86,43 +86,24 @@ export interface FieldTemplate {
|
||||
generated?: boolean;
|
||||
}
|
||||
|
||||
export interface DocumentType {
|
||||
type CitizenshipApplicationStatus = "pending" | "rejected" | "approved"
|
||||
|
||||
export interface CitizenshipApplication {
|
||||
id: string;
|
||||
code: string;
|
||||
color: string;
|
||||
fields: FieldTemplate[];
|
||||
user_id: string;
|
||||
status: CitizenshipApplicationStatus;
|
||||
region_id: string;
|
||||
reviewed_by?: string;
|
||||
reviewed_at?: string;
|
||||
reject_reason?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export type DocumentApplicationStatus = "pending" | "approved" | "rejected"
|
||||
|
||||
export interface DocumentApplication {
|
||||
export interface Citizen {
|
||||
id: string;
|
||||
userId: string;
|
||||
documentTypeId: string;
|
||||
documentType: DocumentType;
|
||||
status: DocumentApplicationStatus;
|
||||
reviewedBy?: string;
|
||||
reviewedAt?: string;
|
||||
rejectReason?: string;
|
||||
data: Record<string, string>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type DocumentStatus = "active" | "revoked"
|
||||
|
||||
export interface Document {
|
||||
id: string;
|
||||
userId: string;
|
||||
documentTypeId: string;
|
||||
documentType: DocumentType;
|
||||
applicationId: string;
|
||||
user_id: string;
|
||||
application_id: string;
|
||||
number: string;
|
||||
issuedAt: string;
|
||||
revokedAt?: string | null;
|
||||
revokedBy?: string | null;
|
||||
photo_url?: string | null;
|
||||
data: Record<string, string>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
issued_at: string;
|
||||
region_id: string;
|
||||
}
|
||||
Reference in New Issue
Block a user