diff --git a/cmd/backend/main.go b/cmd/backend/main.go index 9f753c7..d0092f4 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -12,18 +12,19 @@ import ( docs "gitea.d3m0k1d.ru/HellreigN/Control-plane/docs" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/auth" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/config" + "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/middleware" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/org" "github.com/gin-gonic/gin" - "github.com/jackc/pgx/v5/pgxpool" - "github.com/jackc/pgx/v5/stdlib" "github.com/pressly/goose/v3" - "github.com/swaggo/files" - "github.com/swaggo/gin-swagger" + swaggerFiles "github.com/swaggo/files" + ginSwagger "github.com/swaggo/gin-swagger" + "gorm.io/driver/postgres" + "gorm.io/gorm" ) // @title AegisGuard API // @version 1.0 -// @description API for AegisGuard control plane +// @description API для AegisGuard control plane // @schemes http // // @securityDefinitions.apikey Bearer @@ -40,27 +41,28 @@ func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - pool, err := pgxpool.New(ctx, cfg.DatabaseURL) + gormDB, err := gorm.Open(postgres.Open(cfg.DatabaseURL), &gorm.Config{}) if err != nil { - log.Fatalf("failed to create postgres pool: %v", err) + log.Fatalf("failed to connect to postgres: %v", err) } - defer pool.Close() - if err := pool.Ping(ctx); err != nil { + sqlDB, err := gormDB.DB() + if err != nil { + log.Fatalf("failed to get underlying sql.DB: %v", err) + } + + if err := sqlDB.PingContext(ctx); err != nil { log.Fatalf("failed to ping postgres: %v", err) } log.Println("connected to postgres") - db := stdlib.OpenDBFromPool(pool) - defer db.Close() - - if err := goose.Up(db, "migrations"); err != nil { + if err := goose.Up(sqlDB, "migrations"); err != nil { log.Fatalf("failed to run migrations: %v", err) } log.Println("migrations applied") - repo := auth.NewRepository(pool) - orgRepo := org.NewRepository(pool) + repo := auth.NewRepository(gormDB) + orgRepo := org.NewRepository(gormDB) svc := auth.NewService(repo, cfg.JWTSecret, cfg.JWTExpiration, cfg.JWTRefreshExpiration) handler := auth.NewHandler(svc) @@ -68,7 +70,7 @@ func main() { orgSvc := org.NewService(orgRepo) orgHandler := org.NewHandler(orgSvc) - loginLimiter := auth.NewRateLimiter(10, time.Minute) + loginLimiter := middleware.NewRateLimiter(10, time.Minute) authMW := auth.AuthMiddleware([]byte(cfg.JWTSecret)) go func() { @@ -117,8 +119,9 @@ func main() { } srv := &http.Server{ - Addr: ":" + cfg.ServerPort, - Handler: r, + Addr: ":" + cfg.ServerPort, + Handler: r, + ReadHeaderTimeout: 10 * time.Second, } go func() { @@ -141,7 +144,8 @@ func main() { log.Fatalf("server forced to shutdown: %v", err) } - pool.Close() + loginLimiter.Stop() + _ = sqlDB.Close() log.Println("server stopped") } diff --git a/go.mod b/go.mod index 58629d8..784c449 100644 --- a/go.mod +++ b/go.mod @@ -6,13 +6,14 @@ require ( github.com/gin-gonic/gin v1.12.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 - github.com/jackc/pgx/v5 v5.7.4 github.com/joho/godotenv v1.5.1 github.com/pressly/goose/v3 v3.24.2 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.1 github.com/swaggo/swag v1.16.6 golang.org/x/crypto v0.53.0 + gorm.io/driver/postgres v1.6.0 + gorm.io/gorm v1.31.1 ) require ( @@ -36,7 +37,10 @@ require ( github.com/goccy/go-yaml v1.19.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.7.4 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect diff --git a/go.sum b/go.sum index 66f623f..4cfb7c0 100644 --- a/go.sum +++ b/go.sum @@ -63,6 +63,10 @@ github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= @@ -203,6 +207,10 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg= +gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8= modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= diff --git a/internal/api/api.go b/internal/api/api.go new file mode 100644 index 0000000..b7a82d2 --- /dev/null +++ b/internal/api/api.go @@ -0,0 +1,9 @@ +package api + +import "github.com/gin-gonic/gin" + +func GetUserID(c *gin.Context) string { + raw, _ := c.Get("user_id") + id, _ := raw.(string) + return id +} diff --git a/internal/auth/JWT_README.md b/internal/auth/JWT_README.md deleted file mode 100644 index 46d9e2e..0000000 --- a/internal/auth/JWT_README.md +++ /dev/null @@ -1,108 +0,0 @@ -# JWT Аутентификация — AegisGuard API - -## Схема работы - -- **access_token** — JWT, живёт 24 часа. Передаётся в заголовке `Authorization: Bearer`. -- **refresh_token** — случайная строка, хранится в БД в виде хеша. Используется **один раз** (ротация): при запросе новой пары старый токен удаляется. -- Регистрация сразу возвращает токены — отдельный логин не нужен. - -## Эндпоинты - -### POST /api/auth/register - -Создание аккаунта. - -``` -Запрос: -{ "username": "john", "email": "john@example.com", "password": "Secret123" } - -Ответ 201: -{ - "token": "eyJhbGciOiJIUzI1NiIs...", - "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=", - "user": { - "id": "uuid", - "username": "john", - "email": "john@example.com", - "created_at": "2026-06-13T12:00:00Z" - } -} -``` - -- `username` — 3–30 символов -- `email` — валидный email -- `password` — минимум 8 символов, обязательно заглавная + строчная + цифра - -Ошибки: `400` (валидация), `409` (email уже занят). - -### POST /api/auth/login - -``` -Запрос: -{ "email": "john@example.com", "password": "Secret123" } - -Ответ 200: -{ "token": "...", "refresh_token": "...", "user": { ... } } -``` - -Rate limit: 10 попыток в минуту с одного IP (`429 Too Many Requests`). - -### POST /api/auth/refresh - -Обновить токены по refresh_token. Старый удаляется, выдаётся новая пара. - -``` -Запрос: -{ "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=" } - -Ответ 200: -{ "token": "...", "refresh_token": "...", "user": { ... } } -``` - -### POST /api/auth/logout - -Удалить refresh_token из БД. - -``` -Запрос: -{ "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=" } - -Ответ 200: -{ "message": "logged out successfully" } -``` - -## Заголовок авторизации - -``` -Authorization: Bearer -``` - -## Формат JWT - -```json -{ - "user_id": "uuid", - "email": "john@example.com", - "sub": "uuid", - "exp": 1718000000, - "iat": 1717913600 -} -``` - -- `user_id` — UUID пользователя -- `email` — Email пользователя -- `sub` — то же, что `user_id` -- `exp` — Unix-timestamp истечения токена -- `iat` — Unix-timestamp выпуска токена - -## Формат ошибок - -```json -{ "error": "описание" } -``` - -- `400` — ошибка валидации -- `401` — неверный email/пароль, токен протух или невалиден -- `409` — email уже зарегистрирован -- `429` — превышен лимит попыток логина -- `500` — внутренняя ошибка сервера diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 1ddc136..05d4639 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -29,12 +29,16 @@ func GenerateToken(userID, email string, secret []byte, expiration time.Duration } func ValidateToken(tokenString string, secret []byte) (*Claims, error) { - token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) { - if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) - } - return secret, nil - }) + token, err := jwt.ParseWithClaims( + tokenString, + &Claims{}, + func(t *jwt.Token) (interface{}, error) { + if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) + } + return secret, nil + }, + ) if err != nil { return nil, err } diff --git a/internal/auth/handler.go b/internal/auth/handler.go index 27a1dfe..7c2852b 100644 --- a/internal/auth/handler.go +++ b/internal/auth/handler.go @@ -5,6 +5,7 @@ import ( "log" "net/http" + "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/api" "github.com/gin-gonic/gin" ) @@ -16,8 +17,8 @@ func NewHandler(service *Service) *Handler { return &Handler{service: service} } -// @Summary Register epta -// @Description Create user account with username, email, password +// @Summary Register +// @Description Создание учетной записи пользователя с полями username, email, password // @Tags auth // @Accept json // @Produce json @@ -52,7 +53,7 @@ func (h *Handler) Register(c *gin.Context) { } // @Summary Login -// @Description Authenticate user with email and password, returns JWT token +// @Description Аунтефикация пользователя с помощью email и password, возвращает JWT token // @Tags auth // @Accept json // @Produce json @@ -82,8 +83,8 @@ func (h *Handler) Login(c *gin.Context) { c.JSON(http.StatusOK, resp) } -// @Summary Refresh epta token -// @Description Get a new access token using a refresh token +// @Summary Refresh token +// @Description Получение ново // @Tags auth // @Accept json // @Produce json @@ -113,8 +114,8 @@ func (h *Handler) Refresh(c *gin.Context) { c.JSON(http.StatusOK, resp) } -// @Summary Logout epta -// @Description Invalidate a refresh token (logout) +// @Summary Logout +// @Description Аннулирует refresh token // @Tags auth // @Accept json // @Produce json @@ -143,8 +144,8 @@ func (h *Handler) Logout(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"}) } -// @Summary Get epta current user -// @Description Get authenticated user's profile +// @Summary Get current user +// @Description Получить профиль авторизованного пользователя // @Tags auth // @Accept json // @Produce json @@ -153,18 +154,12 @@ func (h *Handler) Logout(c *gin.Context) { // @Failure 401 {object} ErrorResponse // @Router /api/auth/me [get] func (h *Handler) Me(c *gin.Context) { - rawUserID, exists := c.Get("user_id") - if !exists { + userID := api.GetUserID(c) + if userID == "" { c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) return } - userID, ok := rawUserID.(string) - if !ok { - c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"}) - return - } - user, err := h.service.GetUserByID(c.Request.Context(), userID) if err != nil { if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrInvalidUserID) { @@ -179,8 +174,8 @@ func (h *Handler) Me(c *gin.Context) { c.JSON(http.StatusOK, UserResponse{User: *user}) } -// @Summary Change epta password -// @Description Change current user's password +// @Summary Change password +// @Description Изменить текущий password пользователя // @Tags auth // @Accept json // @Produce json @@ -191,18 +186,12 @@ func (h *Handler) Me(c *gin.Context) { // @Failure 401 {object} ErrorResponse // @Router /api/auth/password [put] func (h *Handler) ChangePassword(c *gin.Context) { - rawUserID, exists := c.Get("user_id") - if !exists { + userID := api.GetUserID(c) + if userID == "" { c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) return } - userID, ok := rawUserID.(string) - if !ok { - c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"}) - return - } - var req PasswordChangeRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) @@ -210,7 +199,8 @@ func (h *Handler) ChangePassword(c *gin.Context) { } if err := h.service.ChangePassword(c.Request.Context(), userID, req); err != nil { - if errors.Is(err, ErrWrongPassword) || errors.Is(err, ErrSamePassword) || errors.Is(err, ErrWeakPassword) { + if errors.Is(err, ErrWrongPassword) || errors.Is(err, ErrSamePassword) || + errors.Is(err, ErrWeakPassword) { c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) return } @@ -226,8 +216,8 @@ func (h *Handler) ChangePassword(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "password changed successfully"}) } -// @Summary Update epta profile -// @Description Update current user's username +// @Summary Update profile +// @Description Обновить username текущего пользователя // @Tags auth // @Accept json // @Produce json @@ -238,18 +228,12 @@ func (h *Handler) ChangePassword(c *gin.Context) { // @Failure 401 {object} ErrorResponse // @Router /api/auth/me [put] func (h *Handler) UpdateProfile(c *gin.Context) { - rawUserID, exists := c.Get("user_id") - if !exists { + userID := api.GetUserID(c) + if userID == "" { c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) return } - userID, ok := rawUserID.(string) - if !ok { - c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"}) - return - } - var req UpdateProfileRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go index 5f0b24a..6856d87 100644 --- a/internal/auth/middleware.go +++ b/internal/auth/middleware.go @@ -11,19 +11,28 @@ func AuthMiddleware(jwtSecret []byte) gin.HandlerFunc { return func(c *gin.Context) { authHeader := c.GetHeader("Authorization") if authHeader == "" { - c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "authorization header required"}) + c.AbortWithStatusJSON( + http.StatusUnauthorized, + ErrorResponse{Error: "authorization header required"}, + ) return } parts := strings.SplitN(authHeader, " ", 2) if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { - c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid authorization header format"}) + c.AbortWithStatusJSON( + http.StatusUnauthorized, + ErrorResponse{Error: "invalid authorization header format"}, + ) return } claims, err := ValidateToken(parts[1], jwtSecret) if err != nil { - c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid or expired token"}) + c.AbortWithStatusJSON( + http.StatusUnauthorized, + ErrorResponse{Error: "invalid or expired token"}, + ) return } diff --git a/internal/auth/models.go b/internal/auth/models.go index 630b404..1cb8748 100644 --- a/internal/auth/models.go +++ b/internal/auth/models.go @@ -5,26 +5,26 @@ import ( ) type User struct { - ID string `json:"id"` - Username string `json:"username"` - Email string `json:"email"` - PasswordHash string `json:"-"` - CreatedAt time.Time `json:"created_at"` + ID string `gorm:"type:uuid;primaryKey" json:"id"` + Username string `gorm:"type:text;not null" json:"username"` + Email string `gorm:"type:text;not null;uniqueIndex" json:"email"` + PasswordHash string `gorm:"column:password_hash;type:text;not null" json:"-"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` } type RegisterRequest struct { Username string `json:"username" binding:"required,min=3,max=30" example:"john"` - Email string `json:"email" binding:"required,email" example:"john@example.com"` - Password string `json:"password" binding:"required,min=8" example:"Secret123!"` + Email string `json:"email" binding:"required,email" example:"john@example.com"` + Password string `json:"password" binding:"required,min=8" example:"Secret123!"` } type LoginRequest struct { - Email string `json:"email" binding:"required,email" example:"john@example.com"` - Password string `json:"password" binding:"required" example:"secret123"` + Email string `json:"email" binding:"required,email" example:"john@example.com"` + Password string `json:"password" binding:"required" example:"secret123"` } type AuthResponse struct { - Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."` + Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."` RefreshToken string `json:"refresh_token" example:"dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4="` User UserPublic `json:"user"` } @@ -38,13 +38,15 @@ type LogoutRequest struct { } type RefreshTokenDoc struct { - ID string `json:"id"` - UserID string `json:"user_id"` - TokenHash string `json:"token_hash"` - ExpiresAt time.Time `json:"expires_at"` - CreatedAt time.Time `json:"created_at"` + ID string `gorm:"type:uuid;primaryKey" json:"id"` + UserID string `gorm:"column:user_id;type:uuid;not null;index" json:"user_id"` + TokenHash string `gorm:"column:token_hash;type:text;not null;uniqueIndex" json:"token_hash"` + ExpiresAt time.Time `gorm:"column:expires_at;type:timestamptz;not null" json:"expires_at"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` } +func (RefreshTokenDoc) TableName() string { return "refresh_tokens" } + type UserPublic struct { ID string `json:"id"` Username string `json:"username"` @@ -66,7 +68,7 @@ type UserResponse struct { } type PasswordChangeRequest struct { - OldPassword string `json:"old_password" binding:"required" example:"Secret123!"` + OldPassword string `json:"old_password" binding:"required" example:"Secret123!"` NewPassword string `json:"new_password" binding:"required,min=8" example:"NewSecret456!"` } diff --git a/internal/auth/repository.go b/internal/auth/repository.go index 9449e7c..30c974a 100644 --- a/internal/auth/repository.go +++ b/internal/auth/repository.go @@ -5,33 +5,39 @@ import ( "time" "github.com/google/uuid" - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" + "gorm.io/gorm" ) -type Repository struct { - pool *pgxpool.Pool +type UserRepository interface { + CreateUser(ctx context.Context, user *User) error + FindByEmail(ctx context.Context, email string) (*User, error) + FindByID(ctx context.Context, id string) (*User, error) + CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error + FindRefreshTokenByHash(ctx context.Context, hash string) (*RefreshTokenDoc, error) + DeleteRefreshToken(ctx context.Context, id string) error + DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error) + UpdateUserUsername(ctx context.Context, id, username string) error + UpdateUserPassword(ctx context.Context, id, passwordHash string) error + DeleteExpiredRefreshTokens(ctx context.Context) error } -func NewRepository(pool *pgxpool.Pool) *Repository { - return &Repository{pool: pool} +type Repository struct { + db *gorm.DB +} + +func NewRepository(db *gorm.DB) *Repository { + return &Repository{db: db} } func (r *Repository) CreateUser(ctx context.Context, user *User) error { user.ID = uuid.New().String() user.CreatedAt = time.Now().UTC() - _, err := r.pool.Exec(ctx, - `INSERT INTO users (id, username, email, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`, - user.ID, user.Username, user.Email, user.PasswordHash, user.CreatedAt, - ) - return err + return r.db.WithContext(ctx).Create(user).Error } func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) { var user User - err := r.pool.QueryRow(ctx, - `SELECT id, username, email, password_hash, created_at FROM users WHERE email = $1`, email, - ).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt) + err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error if err != nil { return nil, err } @@ -40,9 +46,7 @@ func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, erro func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) { var user User - err := r.pool.QueryRow(ctx, - `SELECT id, username, email, password_hash, created_at FROM users WHERE id = $1`, id, - ).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt) + err := r.db.WithContext(ctx).Where("id = ?", id).First(&user).Error if err != nil { return nil, err } @@ -52,18 +56,18 @@ func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) { func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error { doc.ID = uuid.New().String() doc.CreatedAt = time.Now().UTC() - _, err := r.pool.Exec(ctx, - `INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at, created_at) VALUES ($1, $2, $3, $4, $5)`, - doc.ID, doc.UserID, doc.TokenHash, doc.ExpiresAt, doc.CreatedAt, - ) - return err + return r.db.WithContext(ctx).Create(doc).Error } -func (r *Repository) FindRefreshTokenByHash(ctx context.Context, hash string) (*RefreshTokenDoc, error) { +func (r *Repository) FindRefreshTokenByHash( + ctx context.Context, + hash string, +) (*RefreshTokenDoc, error) { var doc RefreshTokenDoc - err := r.pool.QueryRow(ctx, - `SELECT id, user_id, token_hash, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1 AND expires_at > NOW()`, hash, - ).Scan(&doc.ID, &doc.UserID, &doc.TokenHash, &doc.ExpiresAt, &doc.CreatedAt) + err := r.db.WithContext(ctx). + Where("token_hash = ? AND expires_at > NOW()", hash). + First(&doc). + Error if err != nil { return nil, err } @@ -71,31 +75,28 @@ func (r *Repository) FindRefreshTokenByHash(ctx context.Context, hash string) (* } func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error { - _, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE id = $1`, id) - return err -} - -func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error { - _, err := r.pool.Exec(ctx, `UPDATE users SET username = $1 WHERE id = $2`, username, id) - return err -} - -func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error { - _, err := r.pool.Exec(ctx, `UPDATE users SET password_hash = $1 WHERE id = $2`, passwordHash, id) - return err -} - -func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error { - _, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE expires_at <= NOW()`) - return err + return r.db.WithContext(ctx).Where("id = ?", id).Delete(&RefreshTokenDoc{}).Error } func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error) { - tag, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE token_hash = $1`, hash) - if err != nil { - return false, err + result := r.db.WithContext(ctx).Where("token_hash = ?", hash).Delete(&RefreshTokenDoc{}) + if result.Error != nil { + return false, result.Error } - return tag.RowsAffected() > 0, nil + return result.RowsAffected > 0, nil } -var ErrNoRows = pgx.ErrNoRows +func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error { + return r.db.WithContext(ctx).Model(&User{}).Where("id = ?", id). + Update("username", username).Error +} + +func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error { + return r.db.WithContext(ctx).Model(&User{}).Where("id = ?", id). + Update("password_hash", passwordHash).Error +} + +func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error { + return r.db.WithContext(ctx). + Where("expires_at <= NOW()").Delete(&RefreshTokenDoc{}).Error +} diff --git a/internal/auth/service.go b/internal/auth/service.go index c305fc4..e211c6e 100644 --- a/internal/auth/service.go +++ b/internal/auth/service.go @@ -11,30 +11,33 @@ import ( "time" "unicode" + "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db" "golang.org/x/crypto/bcrypt" ) var ( - ErrEmailExists = errors.New("email already registered") - ErrInvalidCreds = errors.New("invalid email or password") - ErrUserNotFound = errors.New("user not found") - ErrInvalidUserID = errors.New("invalid user ID") - ErrInvalidRefresh = errors.New("invalid refresh token") - ErrRefreshExpired = errors.New("refresh token expired") - ErrLogoutInvalid = errors.New("refresh token not found or already used") - ErrWrongPassword = errors.New("current password is incorrect") - ErrWeakPassword = errors.New("password must be at least 8 characters with uppercase, lowercase, and digit") - ErrSamePassword = errors.New("new password must differ from current password") + ErrEmailExists = errors.New("email already registered") + ErrInvalidCreds = errors.New("invalid email or password") + ErrUserNotFound = errors.New("user not found") + ErrInvalidUserID = errors.New("invalid user ID") + ErrInvalidRefresh = errors.New("invalid refresh token") + ErrRefreshExpired = errors.New("refresh token expired") + ErrLogoutInvalid = errors.New("refresh token not found or already used") + ErrWrongPassword = errors.New("current password is incorrect") + ErrWeakPassword = errors.New( + "password must be at least 8 characters with uppercase, lowercase, and digit", + ) + ErrSamePassword = errors.New("new password must differ from current password") ) type Service struct { - repo *Repository + repo UserRepository jwtSecret []byte jwtExp time.Duration refreshExp time.Duration } -func NewService(repo *Repository, jwtSecret string, jwtExp, refreshExp time.Duration) *Service { +func NewService(repo UserRepository, jwtSecret string, jwtExp, refreshExp time.Duration) *Service { return &Service{ repo: repo, jwtSecret: []byte(jwtSecret), @@ -113,7 +116,7 @@ func (s *Service) Register(ctx context.Context, req RegisterRequest) (*AuthRespo req.Email = strings.ToLower(req.Email) existing, err := s.repo.FindByEmail(ctx, req.Email) - if err != nil && !errors.Is(err, ErrNoRows) { + if err != nil && !errors.Is(err, db.ErrNoRows) { return nil, fmt.Errorf("failed to check existing user: %w", err) } if existing != nil { @@ -145,13 +148,16 @@ func (s *Service) Login(ctx context.Context, req LoginRequest) (*AuthResponse, e req.Email = strings.ToLower(req.Email) user, err := s.repo.FindByEmail(ctx, req.Email) if err != nil { - if errors.Is(err, ErrNoRows) { + if errors.Is(err, db.ErrNoRows) { return nil, ErrInvalidCreds } return nil, fmt.Errorf("failed to find user: %w", err) } - if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil { + if err := bcrypt.CompareHashAndPassword( + []byte(user.PasswordHash), + []byte(req.Password), + ); err != nil { return nil, ErrInvalidCreds } @@ -163,7 +169,7 @@ func (s *Service) Refresh(ctx context.Context, rawRefresh string) (*AuthResponse doc, err := s.repo.FindRefreshTokenByHash(ctx, hash) if err != nil { - if errors.Is(err, ErrNoRows) { + if errors.Is(err, db.ErrNoRows) { return nil, ErrInvalidRefresh } return nil, fmt.Errorf("failed to find refresh token: %w", err) @@ -202,7 +208,7 @@ func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic, user, err := s.repo.FindByID(ctx, userID) if err != nil { - if errors.Is(err, ErrNoRows) { + if errors.Is(err, db.ErrNoRows) { return nil, ErrUserNotFound } return nil, fmt.Errorf("failed to find user: %w", err) @@ -212,20 +218,27 @@ func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic, return &public, nil } -func (s *Service) ChangePassword(ctx context.Context, userID string, req PasswordChangeRequest) error { +func (s *Service) ChangePassword( + ctx context.Context, + userID string, + req PasswordChangeRequest, +) error { if userID == "" { return ErrInvalidUserID } user, err := s.repo.FindByID(ctx, userID) if err != nil { - if errors.Is(err, ErrNoRows) { + if errors.Is(err, db.ErrNoRows) { return ErrUserNotFound } return fmt.Errorf("failed to find user: %w", err) } - if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.OldPassword)); err != nil { + if err := bcrypt.CompareHashAndPassword( + []byte(user.PasswordHash), + []byte(req.OldPassword), + ); err != nil { return ErrWrongPassword } @@ -249,14 +262,18 @@ func (s *Service) ChangePassword(ctx context.Context, userID string, req Passwor return nil } -func (s *Service) UpdateProfile(ctx context.Context, userID string, req UpdateProfileRequest) (*UserPublic, error) { +func (s *Service) UpdateProfile( + ctx context.Context, + userID string, + req UpdateProfileRequest, +) (*UserPublic, error) { if userID == "" { return nil, ErrInvalidUserID } user, err := s.repo.FindByID(ctx, userID) if err != nil { - if errors.Is(err, ErrNoRows) { + if errors.Is(err, db.ErrNoRows) { return nil, ErrUserNotFound } return nil, fmt.Errorf("failed to find user: %w", err) @@ -272,5 +289,6 @@ func (s *Service) UpdateProfile(ctx context.Context, userID string, req UpdatePr } func isPGUniqueViolation(err error) bool { - return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505")) + return err != nil && + (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505")) } diff --git a/internal/config/config.go b/internal/config/config.go index 7ab9b41..839b85a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -10,11 +10,11 @@ import ( ) type Config struct { - ServerPort string - DatabaseURL string - JWTSecret string - JWTExpiration time.Duration - JWTRefreshExpiration time.Duration + ServerPort string + DatabaseURL string + JWTSecret string + JWTExpiration time.Duration + JWTRefreshExpiration time.Duration } func Load() (*Config, error) { @@ -23,8 +23,11 @@ func Load() (*Config, error) { } cfg := &Config{ - ServerPort: getEnv("SERVER_PORT", "8080"), - DatabaseURL: getEnv("DATABASE_URL", "postgres://localhost:5432/aegisguard?sslmode=disable"), + ServerPort: getEnv("SERVER_PORT", "8080"), + DatabaseURL: getEnv( + "DATABASE_URL", + "postgres://localhost:5432/aegisguard?sslmode=disable", + ), JWTSecret: getEnv("JWT_SECRET", ""), JWTExpiration: 24 * time.Hour, JWTRefreshExpiration: 7 * 24 * time.Hour, diff --git a/internal/db/errors.go b/internal/db/errors.go new file mode 100644 index 0000000..6a033de --- /dev/null +++ b/internal/db/errors.go @@ -0,0 +1,5 @@ +package db + +import "gorm.io/gorm" + +var ErrNoRows = gorm.ErrRecordNotFound diff --git a/internal/auth/ratelimit.go b/internal/middleware/ratelimit.go similarity index 69% rename from internal/auth/ratelimit.go rename to internal/middleware/ratelimit.go index 3d9af86..aa96baf 100644 --- a/internal/auth/ratelimit.go +++ b/internal/middleware/ratelimit.go @@ -1,4 +1,4 @@ -package auth +package middleware import ( "net/http" @@ -18,6 +18,7 @@ type RateLimiter struct { visitors map[string]*visitor rate int window time.Duration + done chan struct{} } func NewRateLimiter(rate int, window time.Duration) *RateLimiter { @@ -25,24 +26,33 @@ func NewRateLimiter(rate int, window time.Duration) *RateLimiter { visitors: make(map[string]*visitor), rate: rate, window: window, + done: make(chan struct{}), } - go rl.cleanup() return rl } +func (rl *RateLimiter) Stop() { + close(rl.done) +} + func (rl *RateLimiter) cleanup() { ticker := time.NewTicker(10 * time.Minute) defer ticker.Stop() - for range ticker.C { - rl.mu.Lock() - now := time.Now() - for ip, v := range rl.visitors { - if now.Sub(v.lastSeen) > rl.window*2 { - delete(rl.visitors, ip) + for { + select { + case <-rl.done: + return + case <-ticker.C: + rl.mu.Lock() + now := time.Now() + for ip, v := range rl.visitors { + if now.Sub(v.lastSeen) > rl.window*2 { + delete(rl.visitors, ip) + } } + rl.mu.Unlock() } - rl.mu.Unlock() } } @@ -66,7 +76,7 @@ func (rl *RateLimiter) Middleware() gin.HandlerFunc { if v.count > rl.rate { rl.mu.Unlock() - c.JSON(http.StatusTooManyRequests, ErrorResponse{Error: "too many requests, try again later"}) + c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many requests, try again later"}) c.Abort() return } diff --git a/internal/org/handler.go b/internal/org/handler.go index 0c88e26..deff358 100644 --- a/internal/org/handler.go +++ b/internal/org/handler.go @@ -4,6 +4,7 @@ import ( "errors" "log" "net/http" + "strconv" "github.com/gin-gonic/gin" ) @@ -76,16 +77,21 @@ func (h *Handler) GetByID(c *gin.Context) { } // @Summary List organizations -// @Description Get all organizations +// @Description Get all organizations with pagination // @Tags organizations // @Accept json // @Produce json // @Security Bearer +// @Param limit query int false "Page size (default 20)" +// @Param offset query int false "Offset (default 0)" // @Success 200 {object} OrgListResponse // @Failure 500 {object} ErrorResponse // @Router /api/organizations [get] func (h *Handler) List(c *gin.Context) { - resp, err := h.service.List(c.Request.Context()) + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) + offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0")) + + resp, err := h.service.List(c.Request.Context(), limit, offset) if err != nil { log.Printf("list orgs error: %v", err) c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"}) diff --git a/internal/org/models.go b/internal/org/models.go index 3c811d4..ed75aa0 100644 --- a/internal/org/models.go +++ b/internal/org/models.go @@ -3,16 +3,16 @@ package org import "time" type Organization struct { - ID string `json:"id"` - Name string `json:"name"` - Slug string `json:"slug"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `gorm:"type:uuid;primaryKey" json:"id"` + Name string `gorm:"type:text;not null" json:"name"` + Slug string `gorm:"type:text;not null;uniqueIndex" json:"slug"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` } type CreateOrgRequest struct { Name string `json:"name" binding:"required,min=2,max=100" example:"My Corp"` - Slug string `json:"slug" binding:"required,min=2,max=50" example:"my-corp"` + Slug string `json:"slug" binding:"required,min=2,max=50" example:"my-corp"` } type UpdateOrgRequest struct { @@ -26,6 +26,8 @@ type OrgResponse struct { type OrgListResponse struct { Organizations []Organization `json:"organizations"` Total int `json:"total"` + Limit int `json:"limit"` + Offset int `json:"offset"` } type ErrorResponse struct { diff --git a/internal/org/repository.go b/internal/org/repository.go index 61f3245..ea7554e 100644 --- a/internal/org/repository.go +++ b/internal/org/repository.go @@ -5,18 +5,24 @@ import ( "time" "github.com/google/uuid" - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" + "gorm.io/gorm" ) -var ErrNoRows = pgx.ErrNoRows - -type Repository struct { - pool *pgxpool.Pool +type OrgRepository interface { + Create(ctx context.Context, org *Organization) error + FindByID(ctx context.Context, id string) (*Organization, error) + FindAll(ctx context.Context, limit, offset int) ([]Organization, error) + Count(ctx context.Context) (int, error) + Update(ctx context.Context, org *Organization) error + Delete(ctx context.Context, id string) (bool, error) } -func NewRepository(pool *pgxpool.Pool) *Repository { - return &Repository{pool: pool} +type Repository struct { + db *gorm.DB +} + +func NewRepository(db *gorm.DB) *Repository { + return &Repository{db: db} } func (r *Repository) Create(ctx context.Context, org *Organization) error { @@ -24,54 +30,42 @@ func (r *Repository) Create(ctx context.Context, org *Organization) error { now := time.Now().UTC() org.CreatedAt = now org.UpdatedAt = now - _, err := r.pool.Exec(ctx, - `INSERT INTO organizations (id, name, slug, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)`, - org.ID, org.Name, org.Slug, org.CreatedAt, org.UpdatedAt, - ) - return err + return r.db.WithContext(ctx).Create(org).Error } func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) { var org Organization - err := r.pool.QueryRow(ctx, - `SELECT id, name, slug, created_at, updated_at FROM organizations WHERE id = $1`, id, - ).Scan(&org.ID, &org.Name, &org.Slug, &org.CreatedAt, &org.UpdatedAt) + err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error if err != nil { return nil, err } return &org, nil } -func (r *Repository) FindAll(ctx context.Context) ([]Organization, error) { - rows, err := r.pool.Query(ctx, - `SELECT id, name, slug, created_at, updated_at FROM organizations ORDER BY created_at DESC`, - ) - if err != nil { - return nil, err - } - defer rows.Close() - +func (r *Repository) FindAll(ctx context.Context, limit, offset int) ([]Organization, error) { var orgs []Organization - for rows.Next() { - var org Organization - if err := rows.Scan(&org.ID, &org.Name, &org.Slug, &org.CreatedAt, &org.UpdatedAt); err != nil { - return nil, err - } - orgs = append(orgs, org) - } - return orgs, rows.Err() + err := r.db.WithContext(ctx). + Order("created_at DESC"). + Limit(limit). + Offset(offset). + Find(&orgs).Error + return orgs, err +} + +func (r *Repository) Count(ctx context.Context) (int, error) { + var total int64 + err := r.db.WithContext(ctx).Model(&Organization{}).Count(&total).Error + return int(total), err } func (r *Repository) Update(ctx context.Context, org *Organization) error { - org.UpdatedAt = time.Now().UTC() - _, err := r.pool.Exec(ctx, - `UPDATE organizations SET name = $1, updated_at = $2 WHERE id = $3`, - org.Name, org.UpdatedAt, org.ID, - ) - return err + return r.db.WithContext(ctx).Model(org).Update("name", org.Name).Error } -func (r *Repository) Delete(ctx context.Context, id string) error { - _, err := r.pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id) - return err +func (r *Repository) Delete(ctx context.Context, id string) (bool, error) { + result := r.db.WithContext(ctx).Delete(&Organization{}, "id = ?", id) + if result.Error != nil { + return false, result.Error + } + return result.RowsAffected > 0, nil } diff --git a/internal/org/service.go b/internal/org/service.go index 8348941..3e63b7d 100644 --- a/internal/org/service.go +++ b/internal/org/service.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" "strings" + + "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db" ) var ( @@ -13,10 +15,10 @@ var ( ) type Service struct { - repo *Repository + repo OrgRepository } -func NewService(repo *Repository) *Service { +func NewService(repo OrgRepository) *Service { return &Service{repo: repo} } @@ -41,7 +43,7 @@ func (s *Service) Create(ctx context.Context, req CreateOrgRequest) (*Organizati func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error) { org, err := s.repo.FindByID(ctx, id) if err != nil { - if errors.Is(err, ErrNoRows) { + if errors.Is(err, db.ErrNoRows) { return nil, ErrNotFound } return nil, fmt.Errorf("failed to find organization: %w", err) @@ -49,8 +51,20 @@ func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error) return org, nil } -func (s *Service) List(ctx context.Context) (*OrgListResponse, error) { - orgs, err := s.repo.FindAll(ctx) +func (s *Service) List(ctx context.Context, limit, offset int) (*OrgListResponse, error) { + if limit <= 0 { + limit = 20 + } + if offset < 0 { + offset = 0 + } + + total, err := s.repo.Count(ctx) + if err != nil { + return nil, fmt.Errorf("failed to count organizations: %w", err) + } + + orgs, err := s.repo.FindAll(ctx, limit, offset) if err != nil { return nil, fmt.Errorf("failed to list organizations: %w", err) } @@ -59,14 +73,20 @@ func (s *Service) List(ctx context.Context) (*OrgListResponse, error) { } return &OrgListResponse{ Organizations: orgs, - Total: len(orgs), + Total: total, + Limit: limit, + Offset: offset, }, nil } -func (s *Service) Update(ctx context.Context, id string, req UpdateOrgRequest) (*Organization, error) { +func (s *Service) Update( + ctx context.Context, + id string, + req UpdateOrgRequest, +) (*Organization, error) { org, err := s.repo.FindByID(ctx, id) if err != nil { - if errors.Is(err, ErrNoRows) { + if errors.Is(err, db.ErrNoRows) { return nil, ErrNotFound } return nil, fmt.Errorf("failed to find organization: %w", err) @@ -82,21 +102,17 @@ func (s *Service) Update(ctx context.Context, id string, req UpdateOrgRequest) ( } func (s *Service) Delete(ctx context.Context, id string) error { - org, err := s.repo.FindByID(ctx, id) + found, err := s.repo.Delete(ctx, id) if err != nil { - if errors.Is(err, ErrNoRows) { - return ErrNotFound - } - return fmt.Errorf("failed to find organization: %w", err) - } - - if err := s.repo.Delete(ctx, org.ID); err != nil { return fmt.Errorf("failed to delete organization: %w", err) } - + if !found { + return ErrNotFound + } return nil } func isUniqueViolation(err error) bool { - return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505")) + return err != nil && + (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505")) } diff --git a/migrations/00001_init.sql b/migrations/00001_init.sql index 1e55553..428ae67 100644 --- a/migrations/00001_init.sql +++ b/migrations/00001_init.sql @@ -1,4 +1,5 @@ -CREATE TABLE IF NOT EXISTS users ( +-- +goose Up + CREATE TABLE IF NOT EXISTS users ( id UUID PRIMARY KEY, username TEXT NOT NULL, email TEXT NOT NULL UNIQUE, @@ -16,5 +17,6 @@ CREATE TABLE IF NOT EXISTS refresh_tokens ( CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON refresh_tokens(expires_at); +-- +goose Down DROP TABLE IF EXISTS refresh_tokens; DROP TABLE IF EXISTS users;