fix
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
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);
|
||||
Reference in New Issue
Block a user