refactor: migrate from raw pgx to GORM, unify ErrNoRows, cleanup auth
ci / build (push) Successful in 2m58s
ci / build (pull_request) Successful in 2m47s

This commit is contained in:
Mephimeow
2026-06-14 16:41:33 +00:00
parent 9da532e9dc
commit 2da484d781
19 changed files with 321 additions and 348 deletions
+23 -19
View File
@@ -12,18 +12,19 @@ import (
docs "gitea.d3m0k1d.ru/HellreigN/Control-plane/docs" docs "gitea.d3m0k1d.ru/HellreigN/Control-plane/docs"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/auth" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/auth"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/config" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/config"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/middleware"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/org" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/org"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3" "github.com/pressly/goose/v3"
"github.com/swaggo/files" swaggerFiles "github.com/swaggo/files"
"github.com/swaggo/gin-swagger" ginSwagger "github.com/swaggo/gin-swagger"
"gorm.io/driver/postgres"
"gorm.io/gorm"
) )
// @title AegisGuard API // @title AegisGuard API
// @version 1.0 // @version 1.0
// @description API for AegisGuard control plane // @description API для AegisGuard control plane
// @schemes http // @schemes http
// //
// @securityDefinitions.apikey Bearer // @securityDefinitions.apikey Bearer
@@ -40,27 +41,28 @@ func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
pool, err := pgxpool.New(ctx, cfg.DatabaseURL) gormDB, err := gorm.Open(postgres.Open(cfg.DatabaseURL), &gorm.Config{})
if err != nil { 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.Fatalf("failed to ping postgres: %v", err)
} }
log.Println("connected to postgres") log.Println("connected to postgres")
db := stdlib.OpenDBFromPool(pool) if err := goose.Up(sqlDB, "migrations"); err != nil {
defer db.Close()
if err := goose.Up(db, "migrations"); err != nil {
log.Fatalf("failed to run migrations: %v", err) log.Fatalf("failed to run migrations: %v", err)
} }
log.Println("migrations applied") log.Println("migrations applied")
repo := auth.NewRepository(pool) repo := auth.NewRepository(gormDB)
orgRepo := org.NewRepository(pool) orgRepo := org.NewRepository(gormDB)
svc := auth.NewService(repo, cfg.JWTSecret, cfg.JWTExpiration, cfg.JWTRefreshExpiration) svc := auth.NewService(repo, cfg.JWTSecret, cfg.JWTExpiration, cfg.JWTRefreshExpiration)
handler := auth.NewHandler(svc) handler := auth.NewHandler(svc)
@@ -68,7 +70,7 @@ func main() {
orgSvc := org.NewService(orgRepo) orgSvc := org.NewService(orgRepo)
orgHandler := org.NewHandler(orgSvc) orgHandler := org.NewHandler(orgSvc)
loginLimiter := auth.NewRateLimiter(10, time.Minute) loginLimiter := middleware.NewRateLimiter(10, time.Minute)
authMW := auth.AuthMiddleware([]byte(cfg.JWTSecret)) authMW := auth.AuthMiddleware([]byte(cfg.JWTSecret))
go func() { go func() {
@@ -117,8 +119,9 @@ func main() {
} }
srv := &http.Server{ srv := &http.Server{
Addr: ":" + cfg.ServerPort, Addr: ":" + cfg.ServerPort,
Handler: r, Handler: r,
ReadHeaderTimeout: 10 * time.Second,
} }
go func() { go func() {
@@ -141,7 +144,8 @@ func main() {
log.Fatalf("server forced to shutdown: %v", err) log.Fatalf("server forced to shutdown: %v", err)
} }
pool.Close() loginLimiter.Stop()
_ = sqlDB.Close()
log.Println("server stopped") log.Println("server stopped")
} }
+5 -1
View File
@@ -6,13 +6,14 @@ require (
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.12.0
github.com/golang-jwt/jwt/v5 v5.3.1 github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.7.4
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/pressly/goose/v3 v3.24.2 github.com/pressly/goose/v3 v3.24.2
github.com/swaggo/files v1.0.1 github.com/swaggo/files v1.0.1
github.com/swaggo/gin-swagger v1.6.1 github.com/swaggo/gin-swagger v1.6.1
github.com/swaggo/swag v1.16.6 github.com/swaggo/swag v1.16.6
golang.org/x/crypto v0.53.0 golang.org/x/crypto v0.53.0
gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.31.1
) )
require ( require (
@@ -36,7 +37,10 @@ require (
github.com/goccy/go-yaml v1.19.2 // indirect github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // 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/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/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
+8
View File
@@ -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/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 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= 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 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= 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.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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E= modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+9
View File
@@ -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
}
-108
View File
@@ -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` — 330 символов
- `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 <access_token>
```
## Формат 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` — внутренняя ошибка сервера
+10 -6
View File
@@ -29,12 +29,16 @@ func GenerateToken(userID, email string, secret []byte, expiration time.Duration
} }
func ValidateToken(tokenString string, secret []byte) (*Claims, error) { func ValidateToken(tokenString string, secret []byte) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) { token, err := jwt.ParseWithClaims(
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { tokenString,
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) &Claims{},
} func(t *jwt.Token) (interface{}, error) {
return secret, nil if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
}) return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return secret, nil
},
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+22 -38
View File
@@ -5,6 +5,7 @@ import (
"log" "log"
"net/http" "net/http"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/api"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -16,8 +17,8 @@ func NewHandler(service *Service) *Handler {
return &Handler{service: service} return &Handler{service: service}
} }
// @Summary Register epta // @Summary Register
// @Description Create user account with username, email, password // @Description Создание учетной записи пользователя с полями username, email, password
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -52,7 +53,7 @@ func (h *Handler) Register(c *gin.Context) {
} }
// @Summary Login // @Summary Login
// @Description Authenticate user with email and password, returns JWT token // @Description Аунтефикация пользователя с помощью email и password, возвращает JWT token
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -82,8 +83,8 @@ func (h *Handler) Login(c *gin.Context) {
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
} }
// @Summary Refresh epta token // @Summary Refresh token
// @Description Get a new access token using a refresh token // @Description Получение ново
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -113,8 +114,8 @@ func (h *Handler) Refresh(c *gin.Context) {
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
} }
// @Summary Logout epta // @Summary Logout
// @Description Invalidate a refresh token (logout) // @Description Аннулирует refresh token
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -143,8 +144,8 @@ func (h *Handler) Logout(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"}) c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"})
} }
// @Summary Get epta current user // @Summary Get current user
// @Description Get authenticated user's profile // @Description Получить профиль авторизованного пользователя
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -153,18 +154,12 @@ func (h *Handler) Logout(c *gin.Context) {
// @Failure 401 {object} ErrorResponse // @Failure 401 {object} ErrorResponse
// @Router /api/auth/me [get] // @Router /api/auth/me [get]
func (h *Handler) Me(c *gin.Context) { func (h *Handler) Me(c *gin.Context) {
rawUserID, exists := c.Get("user_id") userID := api.GetUserID(c)
if !exists { if userID == "" {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
return 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) user, err := h.service.GetUserByID(c.Request.Context(), userID)
if err != nil { if err != nil {
if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrInvalidUserID) { 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}) c.JSON(http.StatusOK, UserResponse{User: *user})
} }
// @Summary Change epta password // @Summary Change password
// @Description Change current user's password // @Description Изменить текущий password пользователя
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -191,18 +186,12 @@ func (h *Handler) Me(c *gin.Context) {
// @Failure 401 {object} ErrorResponse // @Failure 401 {object} ErrorResponse
// @Router /api/auth/password [put] // @Router /api/auth/password [put]
func (h *Handler) ChangePassword(c *gin.Context) { func (h *Handler) ChangePassword(c *gin.Context) {
rawUserID, exists := c.Get("user_id") userID := api.GetUserID(c)
if !exists { if userID == "" {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
return return
} }
userID, ok := rawUserID.(string)
if !ok {
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
return
}
var req PasswordChangeRequest var req PasswordChangeRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) 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 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()}) c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
return return
} }
@@ -226,8 +216,8 @@ func (h *Handler) ChangePassword(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "password changed successfully"}) c.JSON(http.StatusOK, gin.H{"message": "password changed successfully"})
} }
// @Summary Update epta profile // @Summary Update profile
// @Description Update current user's username // @Description Обновить username текущего пользователя
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -238,18 +228,12 @@ func (h *Handler) ChangePassword(c *gin.Context) {
// @Failure 401 {object} ErrorResponse // @Failure 401 {object} ErrorResponse
// @Router /api/auth/me [put] // @Router /api/auth/me [put]
func (h *Handler) UpdateProfile(c *gin.Context) { func (h *Handler) UpdateProfile(c *gin.Context) {
rawUserID, exists := c.Get("user_id") userID := api.GetUserID(c)
if !exists { if userID == "" {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
return return
} }
userID, ok := rawUserID.(string)
if !ok {
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
return
}
var req UpdateProfileRequest var req UpdateProfileRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
+12 -3
View File
@@ -11,19 +11,28 @@ func AuthMiddleware(jwtSecret []byte) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization") authHeader := c.GetHeader("Authorization")
if authHeader == "" { if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "authorization header required"}) c.AbortWithStatusJSON(
http.StatusUnauthorized,
ErrorResponse{Error: "authorization header required"},
)
return return
} }
parts := strings.SplitN(authHeader, " ", 2) parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { 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 return
} }
claims, err := ValidateToken(parts[1], jwtSecret) claims, err := ValidateToken(parts[1], jwtSecret)
if err != nil { if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid or expired token"}) c.AbortWithStatusJSON(
http.StatusUnauthorized,
ErrorResponse{Error: "invalid or expired token"},
)
return return
} }
+18 -16
View File
@@ -5,26 +5,26 @@ import (
) )
type User struct { type User struct {
ID string `json:"id"` ID string `gorm:"type:uuid;primaryKey" json:"id"`
Username string `json:"username"` Username string `gorm:"type:text;not null" json:"username"`
Email string `json:"email"` Email string `gorm:"type:text;not null;uniqueIndex" json:"email"`
PasswordHash string `json:"-"` PasswordHash string `gorm:"column:password_hash;type:text;not null" json:"-"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
} }
type RegisterRequest struct { type RegisterRequest struct {
Username string `json:"username" binding:"required,min=3,max=30" example:"john"` Username string `json:"username" binding:"required,min=3,max=30" example:"john"`
Email string `json:"email" binding:"required,email" example:"john@example.com"` Email string `json:"email" binding:"required,email" example:"john@example.com"`
Password string `json:"password" binding:"required,min=8" example:"Secret123!"` Password string `json:"password" binding:"required,min=8" example:"Secret123!"`
} }
type LoginRequest struct { type LoginRequest struct {
Email string `json:"email" binding:"required,email" example:"john@example.com"` Email string `json:"email" binding:"required,email" example:"john@example.com"`
Password string `json:"password" binding:"required" example:"secret123"` Password string `json:"password" binding:"required" example:"secret123"`
} }
type AuthResponse struct { type AuthResponse struct {
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."` Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."`
RefreshToken string `json:"refresh_token" example:"dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4="` RefreshToken string `json:"refresh_token" example:"dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4="`
User UserPublic `json:"user"` User UserPublic `json:"user"`
} }
@@ -38,13 +38,15 @@ type LogoutRequest struct {
} }
type RefreshTokenDoc struct { type RefreshTokenDoc struct {
ID string `json:"id"` ID string `gorm:"type:uuid;primaryKey" json:"id"`
UserID string `json:"user_id"` UserID string `gorm:"column:user_id;type:uuid;not null;index" json:"user_id"`
TokenHash string `json:"token_hash"` TokenHash string `gorm:"column:token_hash;type:text;not null;uniqueIndex" json:"token_hash"`
ExpiresAt time.Time `json:"expires_at"` ExpiresAt time.Time `gorm:"column:expires_at;type:timestamptz;not null" json:"expires_at"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
} }
func (RefreshTokenDoc) TableName() string { return "refresh_tokens" }
type UserPublic struct { type UserPublic struct {
ID string `json:"id"` ID string `json:"id"`
Username string `json:"username"` Username string `json:"username"`
@@ -66,7 +68,7 @@ type UserResponse struct {
} }
type PasswordChangeRequest 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!"` NewPassword string `json:"new_password" binding:"required,min=8" example:"NewSecret456!"`
} }
+49 -48
View File
@@ -5,33 +5,39 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "gorm.io/gorm"
"github.com/jackc/pgx/v5/pgxpool"
) )
type Repository struct { type UserRepository interface {
pool *pgxpool.Pool 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 { type Repository struct {
return &Repository{pool: pool} db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
} }
func (r *Repository) CreateUser(ctx context.Context, user *User) error { func (r *Repository) CreateUser(ctx context.Context, user *User) error {
user.ID = uuid.New().String() user.ID = uuid.New().String()
user.CreatedAt = time.Now().UTC() user.CreatedAt = time.Now().UTC()
_, err := r.pool.Exec(ctx, return r.db.WithContext(ctx).Create(user).Error
`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
} }
func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) { func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) {
var user User var user User
err := r.pool.QueryRow(ctx, err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error
`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)
if err != nil { if err != nil {
return nil, err 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) { func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) {
var user User var user User
err := r.pool.QueryRow(ctx, err := r.db.WithContext(ctx).Where("id = ?", id).First(&user).Error
`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)
if err != nil { if err != nil {
return nil, err 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 { func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error {
doc.ID = uuid.New().String() doc.ID = uuid.New().String()
doc.CreatedAt = time.Now().UTC() doc.CreatedAt = time.Now().UTC()
_, err := r.pool.Exec(ctx, return r.db.WithContext(ctx).Create(doc).Error
`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
} }
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 var doc RefreshTokenDoc
err := r.pool.QueryRow(ctx, err := r.db.WithContext(ctx).
`SELECT id, user_id, token_hash, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1 AND expires_at > NOW()`, hash, Where("token_hash = ? AND expires_at > NOW()", hash).
).Scan(&doc.ID, &doc.UserID, &doc.TokenHash, &doc.ExpiresAt, &doc.CreatedAt) First(&doc).
Error
if err != nil { if err != nil {
return nil, err 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 { func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error {
_, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE id = $1`, id) return r.db.WithContext(ctx).Where("id = ?", id).Delete(&RefreshTokenDoc{}).Error
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
} }
func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, 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) result := r.db.WithContext(ctx).Where("token_hash = ?", hash).Delete(&RefreshTokenDoc{})
if err != nil { if result.Error != nil {
return false, err 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
}
+41 -23
View File
@@ -11,30 +11,33 @@ import (
"time" "time"
"unicode" "unicode"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
var ( var (
ErrEmailExists = errors.New("email already registered") ErrEmailExists = errors.New("email already registered")
ErrInvalidCreds = errors.New("invalid email or password") ErrInvalidCreds = errors.New("invalid email or password")
ErrUserNotFound = errors.New("user not found") ErrUserNotFound = errors.New("user not found")
ErrInvalidUserID = errors.New("invalid user ID") ErrInvalidUserID = errors.New("invalid user ID")
ErrInvalidRefresh = errors.New("invalid refresh token") ErrInvalidRefresh = errors.New("invalid refresh token")
ErrRefreshExpired = errors.New("refresh token expired") ErrRefreshExpired = errors.New("refresh token expired")
ErrLogoutInvalid = errors.New("refresh token not found or already used") ErrLogoutInvalid = errors.New("refresh token not found or already used")
ErrWrongPassword = errors.New("current password is incorrect") ErrWrongPassword = errors.New("current password is incorrect")
ErrWeakPassword = errors.New("password must be at least 8 characters with uppercase, lowercase, and digit") ErrWeakPassword = errors.New(
ErrSamePassword = errors.New("new password must differ from current password") "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 { type Service struct {
repo *Repository repo UserRepository
jwtSecret []byte jwtSecret []byte
jwtExp time.Duration jwtExp time.Duration
refreshExp 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{ return &Service{
repo: repo, repo: repo,
jwtSecret: []byte(jwtSecret), jwtSecret: []byte(jwtSecret),
@@ -113,7 +116,7 @@ func (s *Service) Register(ctx context.Context, req RegisterRequest) (*AuthRespo
req.Email = strings.ToLower(req.Email) req.Email = strings.ToLower(req.Email)
existing, err := s.repo.FindByEmail(ctx, 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) return nil, fmt.Errorf("failed to check existing user: %w", err)
} }
if existing != nil { if existing != nil {
@@ -145,13 +148,16 @@ func (s *Service) Login(ctx context.Context, req LoginRequest) (*AuthResponse, e
req.Email = strings.ToLower(req.Email) req.Email = strings.ToLower(req.Email)
user, err := s.repo.FindByEmail(ctx, req.Email) user, err := s.repo.FindByEmail(ctx, req.Email)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) { if errors.Is(err, db.ErrNoRows) {
return nil, ErrInvalidCreds return nil, ErrInvalidCreds
} }
return nil, fmt.Errorf("failed to find user: %w", err) 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 return nil, ErrInvalidCreds
} }
@@ -163,7 +169,7 @@ func (s *Service) Refresh(ctx context.Context, rawRefresh string) (*AuthResponse
doc, err := s.repo.FindRefreshTokenByHash(ctx, hash) doc, err := s.repo.FindRefreshTokenByHash(ctx, hash)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) { if errors.Is(err, db.ErrNoRows) {
return nil, ErrInvalidRefresh return nil, ErrInvalidRefresh
} }
return nil, fmt.Errorf("failed to find refresh token: %w", err) 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) user, err := s.repo.FindByID(ctx, userID)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) { if errors.Is(err, db.ErrNoRows) {
return nil, ErrUserNotFound return nil, ErrUserNotFound
} }
return nil, fmt.Errorf("failed to find user: %w", err) 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 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 == "" { if userID == "" {
return ErrInvalidUserID return ErrInvalidUserID
} }
user, err := s.repo.FindByID(ctx, userID) user, err := s.repo.FindByID(ctx, userID)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) { if errors.Is(err, db.ErrNoRows) {
return ErrUserNotFound return ErrUserNotFound
} }
return fmt.Errorf("failed to find user: %w", err) 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 return ErrWrongPassword
} }
@@ -249,14 +262,18 @@ func (s *Service) ChangePassword(ctx context.Context, userID string, req Passwor
return nil 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 == "" { if userID == "" {
return nil, ErrInvalidUserID return nil, ErrInvalidUserID
} }
user, err := s.repo.FindByID(ctx, userID) user, err := s.repo.FindByID(ctx, userID)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) { if errors.Is(err, db.ErrNoRows) {
return nil, ErrUserNotFound return nil, ErrUserNotFound
} }
return nil, fmt.Errorf("failed to find user: %w", err) 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 { 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"))
} }
+10 -7
View File
@@ -10,11 +10,11 @@ import (
) )
type Config struct { type Config struct {
ServerPort string ServerPort string
DatabaseURL string DatabaseURL string
JWTSecret string JWTSecret string
JWTExpiration time.Duration JWTExpiration time.Duration
JWTRefreshExpiration time.Duration JWTRefreshExpiration time.Duration
} }
func Load() (*Config, error) { func Load() (*Config, error) {
@@ -23,8 +23,11 @@ func Load() (*Config, error) {
} }
cfg := &Config{ cfg := &Config{
ServerPort: getEnv("SERVER_PORT", "8080"), ServerPort: getEnv("SERVER_PORT", "8080"),
DatabaseURL: getEnv("DATABASE_URL", "postgres://localhost:5432/aegisguard?sslmode=disable"), DatabaseURL: getEnv(
"DATABASE_URL",
"postgres://localhost:5432/aegisguard?sslmode=disable",
),
JWTSecret: getEnv("JWT_SECRET", ""), JWTSecret: getEnv("JWT_SECRET", ""),
JWTExpiration: 24 * time.Hour, JWTExpiration: 24 * time.Hour,
JWTRefreshExpiration: 7 * 24 * time.Hour, JWTRefreshExpiration: 7 * 24 * time.Hour,
+5
View File
@@ -0,0 +1,5 @@
package db
import "gorm.io/gorm"
var ErrNoRows = gorm.ErrRecordNotFound
@@ -1,4 +1,4 @@
package auth package middleware
import ( import (
"net/http" "net/http"
@@ -18,6 +18,7 @@ type RateLimiter struct {
visitors map[string]*visitor visitors map[string]*visitor
rate int rate int
window time.Duration window time.Duration
done chan struct{}
} }
func NewRateLimiter(rate int, window time.Duration) *RateLimiter { 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), visitors: make(map[string]*visitor),
rate: rate, rate: rate,
window: window, window: window,
done: make(chan struct{}),
} }
go rl.cleanup() go rl.cleanup()
return rl return rl
} }
func (rl *RateLimiter) Stop() {
close(rl.done)
}
func (rl *RateLimiter) cleanup() { func (rl *RateLimiter) cleanup() {
ticker := time.NewTicker(10 * time.Minute) ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop() defer ticker.Stop()
for range ticker.C { for {
rl.mu.Lock() select {
now := time.Now() case <-rl.done:
for ip, v := range rl.visitors { return
if now.Sub(v.lastSeen) > rl.window*2 { case <-ticker.C:
delete(rl.visitors, ip) 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 { if v.count > rl.rate {
rl.mu.Unlock() 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() c.Abort()
return return
} }
+8 -2
View File
@@ -4,6 +4,7 @@ import (
"errors" "errors"
"log" "log"
"net/http" "net/http"
"strconv"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -76,16 +77,21 @@ func (h *Handler) GetByID(c *gin.Context) {
} }
// @Summary List organizations // @Summary List organizations
// @Description Get all organizations // @Description Get all organizations with pagination
// @Tags organizations // @Tags organizations
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param limit query int false "Page size (default 20)"
// @Param offset query int false "Offset (default 0)"
// @Success 200 {object} OrgListResponse // @Success 200 {object} OrgListResponse
// @Failure 500 {object} ErrorResponse // @Failure 500 {object} ErrorResponse
// @Router /api/organizations [get] // @Router /api/organizations [get]
func (h *Handler) List(c *gin.Context) { 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 { if err != nil {
log.Printf("list orgs error: %v", err) log.Printf("list orgs error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"}) c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
+8 -6
View File
@@ -3,16 +3,16 @@ package org
import "time" import "time"
type Organization struct { type Organization struct {
ID string `json:"id"` ID string `gorm:"type:uuid;primaryKey" json:"id"`
Name string `json:"name"` Name string `gorm:"type:text;not null" json:"name"`
Slug string `json:"slug"` Slug string `gorm:"type:text;not null;uniqueIndex" json:"slug"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
} }
type CreateOrgRequest struct { type CreateOrgRequest struct {
Name string `json:"name" binding:"required,min=2,max=100" example:"My Corp"` 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 { type UpdateOrgRequest struct {
@@ -26,6 +26,8 @@ type OrgResponse struct {
type OrgListResponse struct { type OrgListResponse struct {
Organizations []Organization `json:"organizations"` Organizations []Organization `json:"organizations"`
Total int `json:"total"` Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
} }
type ErrorResponse struct { type ErrorResponse struct {
+36 -42
View File
@@ -5,18 +5,24 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "gorm.io/gorm"
"github.com/jackc/pgx/v5/pgxpool"
) )
var ErrNoRows = pgx.ErrNoRows type OrgRepository interface {
Create(ctx context.Context, org *Organization) error
type Repository struct { FindByID(ctx context.Context, id string) (*Organization, error)
pool *pgxpool.Pool 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 { type Repository struct {
return &Repository{pool: pool} db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
} }
func (r *Repository) Create(ctx context.Context, org *Organization) error { 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() now := time.Now().UTC()
org.CreatedAt = now org.CreatedAt = now
org.UpdatedAt = now org.UpdatedAt = now
_, err := r.pool.Exec(ctx, return r.db.WithContext(ctx).Create(org).Error
`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
} }
func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) { func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) {
var org Organization var org Organization
err := r.pool.QueryRow(ctx, err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error
`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)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &org, nil return &org, nil
} }
func (r *Repository) FindAll(ctx context.Context) ([]Organization, error) { func (r *Repository) FindAll(ctx context.Context, limit, offset int) ([]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()
var orgs []Organization var orgs []Organization
for rows.Next() { err := r.db.WithContext(ctx).
var org Organization Order("created_at DESC").
if err := rows.Scan(&org.ID, &org.Name, &org.Slug, &org.CreatedAt, &org.UpdatedAt); err != nil { Limit(limit).
return nil, err Offset(offset).
} Find(&orgs).Error
orgs = append(orgs, org) return orgs, err
} }
return orgs, rows.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 { func (r *Repository) Update(ctx context.Context, org *Organization) error {
org.UpdatedAt = time.Now().UTC() return r.db.WithContext(ctx).Model(org).Update("name", org.Name).Error
_, err := r.pool.Exec(ctx,
`UPDATE organizations SET name = $1, updated_at = $2 WHERE id = $3`,
org.Name, org.UpdatedAt, org.ID,
)
return err
} }
func (r *Repository) Delete(ctx context.Context, id string) error { func (r *Repository) Delete(ctx context.Context, id string) (bool, error) {
_, err := r.pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id) result := r.db.WithContext(ctx).Delete(&Organization{}, "id = ?", id)
return err if result.Error != nil {
return false, result.Error
}
return result.RowsAffected > 0, nil
} }
+34 -18
View File
@@ -5,6 +5,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db"
) )
var ( var (
@@ -13,10 +15,10 @@ var (
) )
type Service struct { type Service struct {
repo *Repository repo OrgRepository
} }
func NewService(repo *Repository) *Service { func NewService(repo OrgRepository) *Service {
return &Service{repo: repo} 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) { func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error) {
org, err := s.repo.FindByID(ctx, id) org, err := s.repo.FindByID(ctx, id)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) { if errors.Is(err, db.ErrNoRows) {
return nil, ErrNotFound return nil, ErrNotFound
} }
return nil, fmt.Errorf("failed to find organization: %w", err) 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 return org, nil
} }
func (s *Service) List(ctx context.Context) (*OrgListResponse, error) { func (s *Service) List(ctx context.Context, limit, offset int) (*OrgListResponse, error) {
orgs, err := s.repo.FindAll(ctx) 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 { if err != nil {
return nil, fmt.Errorf("failed to list organizations: %w", err) 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{ return &OrgListResponse{
Organizations: orgs, Organizations: orgs,
Total: len(orgs), Total: total,
Limit: limit,
Offset: offset,
}, nil }, 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) org, err := s.repo.FindByID(ctx, id)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) { if errors.Is(err, db.ErrNoRows) {
return nil, ErrNotFound return nil, ErrNotFound
} }
return nil, fmt.Errorf("failed to find organization: %w", err) 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 { 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 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) return fmt.Errorf("failed to delete organization: %w", err)
} }
if !found {
return ErrNotFound
}
return nil return nil
} }
func isUniqueViolation(err error) bool { 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"))
} }
+3 -1
View File
@@ -1,4 +1,5 @@
CREATE TABLE IF NOT EXISTS users ( -- +goose Up
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
username TEXT NOT NULL, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, 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); 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 refresh_tokens;
DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS users;