Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff355ad1d9 | |||
| 2da484d781 | |||
| 9da532e9dc | |||
| 9d2f69898a | |||
| 35ddfc938c | |||
| 57ce3dea5f | |||
| 56ab583223 | |||
| f1308b3be7 | |||
| a822d8c3b6 | |||
| 321cba3f9b | |||
| ea645860cf |
@@ -26,4 +26,4 @@ jobs:
|
||||
- name: Run tests
|
||||
run: go test ./...
|
||||
- name: Build
|
||||
run: go build -o backend ./cmd/main.go
|
||||
run: go build ./cmd/backend
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
PHONY: docs
|
||||
|
||||
docs:
|
||||
swag init -g cmd/main.go --output docs/
|
||||
swag init -g cmd/backend/main.go --output docs/
|
||||
|
||||
@@ -14,22 +14,25 @@ import (
|
||||
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/config"
|
||||
"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. Позволяет управлять пользователями и организациями.
|
||||
// @description Все защищённые эндпоинты требуют заголовок `Authorization: Bearer <token>`.
|
||||
// @description Токен получается при регистрации или входе.
|
||||
// @schemes http
|
||||
// @BasePath /api/v1
|
||||
//
|
||||
// @securityDefinitions.apikey Bearer
|
||||
// @in header
|
||||
// @name Authorization
|
||||
// @description Type "Bearer" followed by a space and the JWT token.
|
||||
// @description Введите `Bearer <token>`, где token — access_token из ответа /auth/login или /auth/register
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load()
|
||||
@@ -40,27 +43,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 +72,6 @@ func main() {
|
||||
orgSvc := org.NewService(orgRepo)
|
||||
orgHandler := org.NewHandler(orgSvc)
|
||||
|
||||
loginLimiter := auth.NewRateLimiter(10, time.Minute)
|
||||
authMW := auth.AuthMiddleware([]byte(cfg.JWTSecret))
|
||||
|
||||
go func() {
|
||||
@@ -89,17 +92,18 @@ func main() {
|
||||
|
||||
docs.SwaggerInfo.Title = "AegisGuard API"
|
||||
docs.SwaggerInfo.Version = "1.0"
|
||||
docs.SwaggerInfo.Description = "API for AegisGuard"
|
||||
docs.SwaggerInfo.Description = "API системы управления AegisGuard. Позволяет управлять пользователями и организациями."
|
||||
docs.SwaggerInfo.Schemes = []string{"http"}
|
||||
docs.SwaggerInfo.BasePath = "/api/v1"
|
||||
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
r.GET("/health", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
api := r.Group("/api/auth")
|
||||
api := r.Group("/api/v1/auth")
|
||||
{
|
||||
api.POST("/register", handler.Register)
|
||||
api.POST("/login", loginLimiter.Middleware(), handler.Login)
|
||||
api.POST("/login", handler.Login)
|
||||
api.POST("/refresh", handler.Refresh)
|
||||
api.POST("/logout", handler.Logout)
|
||||
api.GET("/me", authMW, handler.Me)
|
||||
@@ -107,7 +111,7 @@ func main() {
|
||||
api.PUT("/password", authMW, handler.ChangePassword)
|
||||
}
|
||||
|
||||
orgs := r.Group("/api/organizations", authMW)
|
||||
orgs := r.Group("/api/v1/organizations", authMW)
|
||||
{
|
||||
orgs.POST("", orgHandler.Create)
|
||||
orgs.GET("", orgHandler.List)
|
||||
@@ -117,8 +121,9 @@ func main() {
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + cfg.ServerPort,
|
||||
Handler: r,
|
||||
Addr: ":" + cfg.ServerPort,
|
||||
Handler: r,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
go func() {
|
||||
@@ -141,7 +146,7 @@ func main() {
|
||||
log.Fatalf("server forced to shutdown: %v", err)
|
||||
}
|
||||
|
||||
pool.Close()
|
||||
_ = sqlDB.Close()
|
||||
|
||||
log.Println("server stopped")
|
||||
}
|
||||
+98
-78
@@ -15,9 +15,9 @@ const docTemplate = `{
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/api/auth/login": {
|
||||
"/api/v1/auth/login": {
|
||||
"post": {
|
||||
"description": "Authenticate user with email and password, returns JWT token",
|
||||
"description": "Аутентификация по email и паролю. Возвращает access_token (JWT) и refresh_token.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -27,10 +27,10 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Login",
|
||||
"summary": "Вход",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Login credentials",
|
||||
"description": "Email и пароль",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -41,19 +41,19 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Успешный вход, токены в ответе",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.AuthResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Неверный email или пароль",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -61,9 +61,9 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/logout": {
|
||||
"/api/v1/auth/logout": {
|
||||
"post": {
|
||||
"description": "Invalidate a refresh token (logout)",
|
||||
"description": "Аннулирование refresh_token. После выхода повторное использование того же refresh_token вернёт 401.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -73,10 +73,10 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Logout",
|
||||
"summary": "Выход",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Refresh token to invalidate",
|
||||
"description": "Refresh_token для аннулирования",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -87,7 +87,7 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "{\"message\": \"logged out successfully\"}",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -96,13 +96,13 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Не указан refresh_token",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Refresh_token не найден или уже аннулирован",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -110,14 +110,14 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/me": {
|
||||
"/api/v1/auth/me": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Get authenticated user's profile",
|
||||
"description": "Получение профиля текущего авторизованного пользователя.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -127,16 +127,16 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Get current user",
|
||||
"summary": "Профиль пользователя",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Данные пользователя",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.UserResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Токен не указан или недействителен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -149,7 +149,7 @@ const docTemplate = `{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Update current user's username",
|
||||
"description": "Обновление username текущего пользователя.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -159,10 +159,10 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Update profile",
|
||||
"summary": "Обновление профиля",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Profile update",
|
||||
"description": "Новый username",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -173,19 +173,19 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Обновлённый профиль",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.UserResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации: username от 3 до 30 символов",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Токен не указан или недействителен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -193,14 +193,14 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/password": {
|
||||
"/api/v1/auth/password": {
|
||||
"put": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Change current user's password",
|
||||
"description": "Изменение пароля текущего пользователя. Требуется указать старый и новый пароль.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -210,10 +210,10 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Change password",
|
||||
"summary": "Смена пароля",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Password change details",
|
||||
"description": "Старый и новый пароль",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -224,7 +224,7 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "{\"message\": \"password changed successfully\"}",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -233,13 +233,13 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации: неверный старый пароль, слабый новый или совпадают",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Токен не указан или недействителен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -247,9 +247,9 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/refresh": {
|
||||
"/api/v1/auth/refresh": {
|
||||
"post": {
|
||||
"description": "Get a new access token using a refresh token",
|
||||
"description": "Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация).\nЕсли refresh_token истёк или уже был использован — придёт 401.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -259,10 +259,10 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Refresh token",
|
||||
"summary": "Обновление токенов",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Refresh token",
|
||||
"description": "Действительный refresh_token",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -273,19 +273,19 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Новая пара токенов",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.AuthResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Не указан refresh_token",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Refresh_token недействителен или истёк",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -293,9 +293,9 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/register": {
|
||||
"/api/v1/auth/register": {
|
||||
"post": {
|
||||
"description": "Create user account with username, email, password",
|
||||
"description": "Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -305,10 +305,10 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Register",
|
||||
"summary": "Регистрация",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Registration details",
|
||||
"description": "Данные для регистрации",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -319,19 +319,19 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"description": "Пользователь создан, токены в ответе",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.AuthResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей (некорректный email, слабый пароль)",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"description": "Email уже зарегистрирован",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -339,14 +339,14 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/organizations": {
|
||||
"/api/v1/organizations": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Get all organizations",
|
||||
"description": "Получение списка всех организаций с пагинацией.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -356,16 +356,30 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "List organizations",
|
||||
"summary": "Список организаций",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Количество записей на странице (по умолчанию 20)",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Смещение от начала списка (по умолчанию 0)",
|
||||
"name": "offset",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Список организаций",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgListResponse"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"description": "Внутренняя ошибка сервера",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -378,7 +392,7 @@ const docTemplate = `{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Create a new organization",
|
||||
"description": "Создание новой организации. slug используется в URL и должен быть уникальным.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -388,10 +402,10 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Create organization",
|
||||
"summary": "Создание организации",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Organization details",
|
||||
"description": "Название и slug организации",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -402,19 +416,19 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"description": "Организация создана",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"description": "Slug уже занят",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -422,14 +436,14 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/organizations/{id}": {
|
||||
"/api/v1/organizations/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Get organization details",
|
||||
"description": "Получение информации об организации по её ID.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -439,11 +453,11 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Get organization by ID",
|
||||
"summary": "Получить организацию",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Organization ID",
|
||||
"description": "UUID организации",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
@@ -451,13 +465,13 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Данные организации",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgResponse"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Not Found",
|
||||
"description": "Организация не найдена",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -470,7 +484,7 @@ const docTemplate = `{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Update organization name",
|
||||
"description": "Обновление названия организации. slug изменить нельзя.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -480,17 +494,17 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Update organization",
|
||||
"summary": "Обновление организации",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Organization ID",
|
||||
"description": "UUID организации",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "New organization details",
|
||||
"description": "Новое название организации",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -501,19 +515,19 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Обновлённая организация",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Not Found",
|
||||
"description": "Организация не найдена",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -526,7 +540,7 @@ const docTemplate = `{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Delete an organization",
|
||||
"description": "Безвозвратное удаление организации по её ID.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -536,11 +550,11 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Delete organization",
|
||||
"summary": "Удаление организации",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Organization ID",
|
||||
"description": "UUID организации",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
@@ -548,7 +562,7 @@ const docTemplate = `{
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "{\"message\": \"organization deleted\"}",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -557,7 +571,7 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Not Found",
|
||||
"description": "Организация не найдена",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -747,6 +761,12 @@ const docTemplate = `{
|
||||
"org.OrgListResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
},
|
||||
"organizations": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -803,7 +823,7 @@ const docTemplate = `{
|
||||
},
|
||||
"securityDefinitions": {
|
||||
"Bearer": {
|
||||
"description": "Type \"Bearer\" followed by a space and the JWT token.",
|
||||
"description": "Введите ` + "`" + `Bearer \u003ctoken\u003e` + "`" + `, где token — access_token из ответа /auth/login или /auth/register",
|
||||
"type": "apiKey",
|
||||
"name": "Authorization",
|
||||
"in": "header"
|
||||
@@ -815,10 +835,10 @@ const docTemplate = `{
|
||||
var SwaggerInfo = &swag.Spec{
|
||||
Version: "1.0",
|
||||
Host: "",
|
||||
BasePath: "",
|
||||
BasePath: "/api/v1",
|
||||
Schemes: []string{"http"},
|
||||
Title: "AegisGuard API",
|
||||
Description: "API for AegisGuard control plane",
|
||||
Description: "API системы управления AegisGuard. Позволяет управлять пользователями и организациями.\nВсе защищённые эндпоинты требуют заголовок `Authorization: Bearer <token>`.\nТокен получается при регистрации или входе.",
|
||||
InfoInstanceName: "swagger",
|
||||
SwaggerTemplate: docTemplate,
|
||||
LeftDelim: "{{",
|
||||
|
||||
+98
-77
@@ -4,15 +4,16 @@
|
||||
],
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "API for AegisGuard control plane",
|
||||
"description": "API системы управления AegisGuard. Позволяет управлять пользователями и организациями.\nВсе защищённые эндпоинты требуют заголовок `Authorization: Bearer \u003ctoken\u003e`.\nТокен получается при регистрации или входе.",
|
||||
"title": "AegisGuard API",
|
||||
"contact": {},
|
||||
"version": "1.0"
|
||||
},
|
||||
"basePath": "/api/v1",
|
||||
"paths": {
|
||||
"/api/auth/login": {
|
||||
"/api/v1/auth/login": {
|
||||
"post": {
|
||||
"description": "Authenticate user with email and password, returns JWT token",
|
||||
"description": "Аутентификация по email и паролю. Возвращает access_token (JWT) и refresh_token.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -22,10 +23,10 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Login",
|
||||
"summary": "Вход",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Login credentials",
|
||||
"description": "Email и пароль",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -36,19 +37,19 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Успешный вход, токены в ответе",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.AuthResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Неверный email или пароль",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -56,9 +57,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/logout": {
|
||||
"/api/v1/auth/logout": {
|
||||
"post": {
|
||||
"description": "Invalidate a refresh token (logout)",
|
||||
"description": "Аннулирование refresh_token. После выхода повторное использование того же refresh_token вернёт 401.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -68,10 +69,10 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Logout",
|
||||
"summary": "Выход",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Refresh token to invalidate",
|
||||
"description": "Refresh_token для аннулирования",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -82,7 +83,7 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "{\"message\": \"logged out successfully\"}",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -91,13 +92,13 @@
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Не указан refresh_token",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Refresh_token не найден или уже аннулирован",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -105,14 +106,14 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/me": {
|
||||
"/api/v1/auth/me": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Get authenticated user's profile",
|
||||
"description": "Получение профиля текущего авторизованного пользователя.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -122,16 +123,16 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Get current user",
|
||||
"summary": "Профиль пользователя",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Данные пользователя",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.UserResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Токен не указан или недействителен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -144,7 +145,7 @@
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Update current user's username",
|
||||
"description": "Обновление username текущего пользователя.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -154,10 +155,10 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Update profile",
|
||||
"summary": "Обновление профиля",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Profile update",
|
||||
"description": "Новый username",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -168,19 +169,19 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Обновлённый профиль",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.UserResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации: username от 3 до 30 символов",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Токен не указан или недействителен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -188,14 +189,14 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/password": {
|
||||
"/api/v1/auth/password": {
|
||||
"put": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Change current user's password",
|
||||
"description": "Изменение пароля текущего пользователя. Требуется указать старый и новый пароль.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -205,10 +206,10 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Change password",
|
||||
"summary": "Смена пароля",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Password change details",
|
||||
"description": "Старый и новый пароль",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -219,7 +220,7 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "{\"message\": \"password changed successfully\"}",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -228,13 +229,13 @@
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации: неверный старый пароль, слабый новый или совпадают",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Токен не указан или недействителен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -242,9 +243,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/refresh": {
|
||||
"/api/v1/auth/refresh": {
|
||||
"post": {
|
||||
"description": "Get a new access token using a refresh token",
|
||||
"description": "Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация).\nЕсли refresh_token истёк или уже был использован — придёт 401.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -254,10 +255,10 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Refresh token",
|
||||
"summary": "Обновление токенов",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Refresh token",
|
||||
"description": "Действительный refresh_token",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -268,19 +269,19 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Новая пара токенов",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.AuthResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Не указан refresh_token",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"description": "Refresh_token недействителен или истёк",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -288,9 +289,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/auth/register": {
|
||||
"/api/v1/auth/register": {
|
||||
"post": {
|
||||
"description": "Create user account with username, email, password",
|
||||
"description": "Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -300,10 +301,10 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Register",
|
||||
"summary": "Регистрация",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Registration details",
|
||||
"description": "Данные для регистрации",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -314,19 +315,19 @@
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"description": "Пользователь создан, токены в ответе",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.AuthResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей (некорректный email, слабый пароль)",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"description": "Email уже зарегистрирован",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/auth.ErrorResponse"
|
||||
}
|
||||
@@ -334,14 +335,14 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/organizations": {
|
||||
"/api/v1/organizations": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Get all organizations",
|
||||
"description": "Получение списка всех организаций с пагинацией.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -351,16 +352,30 @@
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "List organizations",
|
||||
"summary": "Список организаций",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Количество записей на странице (по умолчанию 20)",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Смещение от начала списка (по умолчанию 0)",
|
||||
"name": "offset",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Список организаций",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgListResponse"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"description": "Внутренняя ошибка сервера",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -373,7 +388,7 @@
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Create a new organization",
|
||||
"description": "Создание новой организации. slug используется в URL и должен быть уникальным.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -383,10 +398,10 @@
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Create organization",
|
||||
"summary": "Создание организации",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Organization details",
|
||||
"description": "Название и slug организации",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -397,19 +412,19 @@
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"description": "Организация создана",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"description": "Slug уже занят",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -417,14 +432,14 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/organizations/{id}": {
|
||||
"/api/v1/organizations/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Get organization details",
|
||||
"description": "Получение информации об организации по её ID.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -434,11 +449,11 @@
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Get organization by ID",
|
||||
"summary": "Получить организацию",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Organization ID",
|
||||
"description": "UUID организации",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
@@ -446,13 +461,13 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Данные организации",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgResponse"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Not Found",
|
||||
"description": "Организация не найдена",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -465,7 +480,7 @@
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Update organization name",
|
||||
"description": "Обновление названия организации. slug изменить нельзя.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -475,17 +490,17 @@
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Update organization",
|
||||
"summary": "Обновление организации",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Organization ID",
|
||||
"description": "UUID организации",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "New organization details",
|
||||
"description": "Новое название организации",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -496,19 +511,19 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "Обновлённая организация",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.OrgResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"description": "Ошибка валидации полей",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Not Found",
|
||||
"description": "Организация не найдена",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -521,7 +536,7 @@
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "Delete an organization",
|
||||
"description": "Безвозвратное удаление организации по её ID.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -531,11 +546,11 @@
|
||||
"tags": [
|
||||
"organizations"
|
||||
],
|
||||
"summary": "Delete organization",
|
||||
"summary": "Удаление организации",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Organization ID",
|
||||
"description": "UUID организации",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
@@ -543,7 +558,7 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"description": "{\"message\": \"organization deleted\"}",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -552,7 +567,7 @@
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Not Found",
|
||||
"description": "Организация не найдена",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/org.ErrorResponse"
|
||||
}
|
||||
@@ -742,6 +757,12 @@
|
||||
"org.OrgListResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
},
|
||||
"organizations": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -798,7 +819,7 @@
|
||||
},
|
||||
"securityDefinitions": {
|
||||
"Bearer": {
|
||||
"description": "Type \"Bearer\" followed by a space and the JWT token.",
|
||||
"description": "Введите `Bearer \u003ctoken\u003e`, где token — access_token из ответа /auth/login или /auth/register",
|
||||
"type": "apiKey",
|
||||
"name": "Authorization",
|
||||
"in": "header"
|
||||
|
||||
+119
-77
@@ -1,3 +1,4 @@
|
||||
basePath: /api/v1
|
||||
definitions:
|
||||
auth.AuthResponse:
|
||||
properties:
|
||||
@@ -125,6 +126,10 @@ definitions:
|
||||
type: object
|
||||
org.OrgListResponse:
|
||||
properties:
|
||||
limit:
|
||||
type: integer
|
||||
offset:
|
||||
type: integer
|
||||
organizations:
|
||||
items:
|
||||
$ref: '#/definitions/org.Organization'
|
||||
@@ -162,17 +167,21 @@ definitions:
|
||||
type: object
|
||||
info:
|
||||
contact: {}
|
||||
description: API for AegisGuard control plane
|
||||
description: |-
|
||||
API системы управления AegisGuard. Позволяет управлять пользователями и организациями.
|
||||
Все защищённые эндпоинты требуют заголовок `Authorization: Bearer <token>`.
|
||||
Токен получается при регистрации или входе.
|
||||
title: AegisGuard API
|
||||
version: "1.0"
|
||||
paths:
|
||||
/api/auth/login:
|
||||
/api/v1/auth/login:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Authenticate user with email and password, returns JWT token
|
||||
description: Аутентификация по email и паролю. Возвращает access_token (JWT)
|
||||
и refresh_token.
|
||||
parameters:
|
||||
- description: Login credentials
|
||||
- description: Email и пароль
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -182,27 +191,28 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: Успешный вход, токены в ответе
|
||||
schema:
|
||||
$ref: '#/definitions/auth.AuthResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: Ошибка валидации полей
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
description: Неверный email или пароль
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
summary: Login
|
||||
summary: Вход
|
||||
tags:
|
||||
- auth
|
||||
/api/auth/logout:
|
||||
/api/v1/auth/logout:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Invalidate a refresh token (logout)
|
||||
description: Аннулирование refresh_token. После выхода повторное использование
|
||||
того же refresh_token вернёт 401.
|
||||
parameters:
|
||||
- description: Refresh token to invalidate
|
||||
- description: Refresh_token для аннулирования
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -212,49 +222,53 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: '{"message": "logged out successfully"}'
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: Не указан refresh_token
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
description: Refresh_token не найден или уже аннулирован
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
summary: Logout
|
||||
summary: Выход
|
||||
tags:
|
||||
- auth
|
||||
/api/auth/me:
|
||||
/api/v1/auth/me:
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Get authenticated user's profile
|
||||
description: |-
|
||||
Получение профиля текущего авторизованного пользователя.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: Данные пользователя
|
||||
schema:
|
||||
$ref: '#/definitions/auth.UserResponse'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
description: Токен не указан или недействителен
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get current user
|
||||
summary: Профиль пользователя
|
||||
tags:
|
||||
- auth
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Update current user's username
|
||||
description: |-
|
||||
Обновление username текущего пользователя.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
parameters:
|
||||
- description: Profile update
|
||||
- description: Новый username
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -264,29 +278,32 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: Обновлённый профиль
|
||||
schema:
|
||||
$ref: '#/definitions/auth.UserResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: 'Ошибка валидации: username от 3 до 30 символов'
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
description: Токен не указан или недействителен
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Update profile
|
||||
summary: Обновление профиля
|
||||
tags:
|
||||
- auth
|
||||
/api/auth/password:
|
||||
/api/v1/auth/password:
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Change current user's password
|
||||
description: |-
|
||||
Изменение пароля текущего пользователя. Требуется указать старый и новый пароль.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
|
||||
parameters:
|
||||
- description: Password change details
|
||||
- description: Старый и новый пароль
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -296,31 +313,34 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: '{"message": "password changed successfully"}'
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: 'Ошибка валидации: неверный старый пароль, слабый новый или
|
||||
совпадают'
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
description: Токен не указан или недействителен
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Change password
|
||||
summary: Смена пароля
|
||||
tags:
|
||||
- auth
|
||||
/api/auth/refresh:
|
||||
/api/v1/auth/refresh:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Get a new access token using a refresh token
|
||||
description: |-
|
||||
Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация).
|
||||
Если refresh_token истёк или уже был использован — придёт 401.
|
||||
parameters:
|
||||
- description: Refresh token
|
||||
- description: Действительный refresh_token
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -330,27 +350,29 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: Новая пара токенов
|
||||
schema:
|
||||
$ref: '#/definitions/auth.AuthResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: Не указан refresh_token
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
description: Refresh_token недействителен или истёк
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
summary: Refresh token
|
||||
summary: Обновление токенов
|
||||
tags:
|
||||
- auth
|
||||
/api/auth/register:
|
||||
/api/v1/auth/register:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Create user account with username, email, password
|
||||
description: |-
|
||||
Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token.
|
||||
Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
|
||||
parameters:
|
||||
- description: Registration details
|
||||
- description: Данные для регистрации
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -360,47 +382,60 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"201":
|
||||
description: Created
|
||||
description: Пользователь создан, токены в ответе
|
||||
schema:
|
||||
$ref: '#/definitions/auth.AuthResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: Ошибка валидации полей (некорректный email, слабый пароль)
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
"409":
|
||||
description: Conflict
|
||||
description: Email уже зарегистрирован
|
||||
schema:
|
||||
$ref: '#/definitions/auth.ErrorResponse'
|
||||
summary: Register
|
||||
summary: Регистрация
|
||||
tags:
|
||||
- auth
|
||||
/api/organizations:
|
||||
/api/v1/organizations:
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Get all organizations
|
||||
description: |-
|
||||
Получение списка всех организаций с пагинацией.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
parameters:
|
||||
- description: Количество записей на странице (по умолчанию 20)
|
||||
in: query
|
||||
name: limit
|
||||
type: integer
|
||||
- description: Смещение от начала списка (по умолчанию 0)
|
||||
in: query
|
||||
name: offset
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: Список организаций
|
||||
schema:
|
||||
$ref: '#/definitions/org.OrgListResponse'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
description: Внутренняя ошибка сервера
|
||||
schema:
|
||||
$ref: '#/definitions/org.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: List organizations
|
||||
summary: Список организаций
|
||||
tags:
|
||||
- organizations
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Create a new organization
|
||||
description: |-
|
||||
Создание новой организации. slug используется в URL и должен быть уникальным.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
parameters:
|
||||
- description: Organization details
|
||||
- description: Название и slug организации
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -410,29 +445,31 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"201":
|
||||
description: Created
|
||||
description: Организация создана
|
||||
schema:
|
||||
$ref: '#/definitions/org.OrgResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: Ошибка валидации полей
|
||||
schema:
|
||||
$ref: '#/definitions/org.ErrorResponse'
|
||||
"409":
|
||||
description: Conflict
|
||||
description: Slug уже занят
|
||||
schema:
|
||||
$ref: '#/definitions/org.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Create organization
|
||||
summary: Создание организации
|
||||
tags:
|
||||
- organizations
|
||||
/api/organizations/{id}:
|
||||
/api/v1/organizations/{id}:
|
||||
delete:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Delete an organization
|
||||
description: |-
|
||||
Безвозвратное удаление организации по её ID.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
parameters:
|
||||
- description: Organization ID
|
||||
- description: UUID организации
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
@@ -441,26 +478,28 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: '{"message": "organization deleted"}'
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
"404":
|
||||
description: Not Found
|
||||
description: Организация не найдена
|
||||
schema:
|
||||
$ref: '#/definitions/org.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Delete organization
|
||||
summary: Удаление организации
|
||||
tags:
|
||||
- organizations
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Get organization details
|
||||
description: |-
|
||||
Получение информации об организации по её ID.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
parameters:
|
||||
- description: Organization ID
|
||||
- description: UUID организации
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
@@ -469,29 +508,31 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: Данные организации
|
||||
schema:
|
||||
$ref: '#/definitions/org.OrgResponse'
|
||||
"404":
|
||||
description: Not Found
|
||||
description: Организация не найдена
|
||||
schema:
|
||||
$ref: '#/definitions/org.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get organization by ID
|
||||
summary: Получить организацию
|
||||
tags:
|
||||
- organizations
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Update organization name
|
||||
description: |-
|
||||
Обновление названия организации. slug изменить нельзя.
|
||||
**Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
parameters:
|
||||
- description: Organization ID
|
||||
- description: UUID организации
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: string
|
||||
- description: New organization details
|
||||
- description: Новое название организации
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
@@ -501,27 +542,28 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: Обновлённая организация
|
||||
schema:
|
||||
$ref: '#/definitions/org.OrgResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
description: Ошибка валидации полей
|
||||
schema:
|
||||
$ref: '#/definitions/org.ErrorResponse'
|
||||
"404":
|
||||
description: Not Found
|
||||
description: Организация не найдена
|
||||
schema:
|
||||
$ref: '#/definitions/org.ErrorResponse'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Update organization
|
||||
summary: Обновление организации
|
||||
tags:
|
||||
- organizations
|
||||
schemes:
|
||||
- http
|
||||
securityDefinitions:
|
||||
Bearer:
|
||||
description: Type "Bearer" followed by a space and the JWT token.
|
||||
description: Введите `Bearer <token>`, где token — access_token из ответа /auth/login
|
||||
или /auth/register
|
||||
in: header
|
||||
name: Authorization
|
||||
type: apiKey
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 <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
@@ -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
|
||||
}
|
||||
|
||||
+62
-72
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/api"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -16,16 +17,17 @@ func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// @Summary Register epta
|
||||
// @Description Create user account with username, email, password
|
||||
// @Summary Регистрация
|
||||
// @Description Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token.
|
||||
// @Description Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body RegisterRequest true "Registration details"
|
||||
// @Success 201 {object} AuthResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 409 {object} ErrorResponse
|
||||
// @Router /api/auth/register [post]
|
||||
// @Param request body RegisterRequest true "Данные для регистрации"
|
||||
// @Success 201 {object} AuthResponse "Пользователь создан, токены в ответе"
|
||||
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей (некорректный email, слабый пароль)"
|
||||
// @Failure 409 {object} ErrorResponse "Email уже зарегистрирован"
|
||||
// @Router /api/v1/auth/register [post]
|
||||
func (h *Handler) Register(c *gin.Context) {
|
||||
var req RegisterRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -51,16 +53,16 @@ func (h *Handler) Register(c *gin.Context) {
|
||||
c.JSON(http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
// @Summary Login
|
||||
// @Description Authenticate user with email and password, returns JWT token
|
||||
// @Summary Вход
|
||||
// @Description Аутентификация по email и паролю. Возвращает access_token (JWT) и refresh_token.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body LoginRequest true "Login credentials"
|
||||
// @Success 200 {object} AuthResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/login [post]
|
||||
// @Param request body LoginRequest true "Email и пароль"
|
||||
// @Success 200 {object} AuthResponse "Успешный вход, токены в ответе"
|
||||
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей"
|
||||
// @Failure 401 {object} ErrorResponse "Неверный email или пароль"
|
||||
// @Router /api/v1/auth/login [post]
|
||||
func (h *Handler) Login(c *gin.Context) {
|
||||
var req LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -82,16 +84,17 @@ 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 Обновление токенов
|
||||
// @Description Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация).
|
||||
// @Description Если refresh_token истёк или уже был использован — придёт 401.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body RefreshRequest true "Refresh token"
|
||||
// @Success 200 {object} AuthResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/refresh [post]
|
||||
// @Param request body RefreshRequest true "Действительный refresh_token"
|
||||
// @Success 200 {object} AuthResponse "Новая пара токенов"
|
||||
// @Failure 400 {object} ErrorResponse "Не указан refresh_token"
|
||||
// @Failure 401 {object} ErrorResponse "Refresh_token недействителен или истёк"
|
||||
// @Router /api/v1/auth/refresh [post]
|
||||
func (h *Handler) Refresh(c *gin.Context) {
|
||||
var req RefreshRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -113,16 +116,16 @@ func (h *Handler) Refresh(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// @Summary Logout epta
|
||||
// @Description Invalidate a refresh token (logout)
|
||||
// @Summary Выход
|
||||
// @Description Аннулирование refresh_token. После выхода повторное использование того же refresh_token вернёт 401.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body LogoutRequest true "Refresh token to invalidate"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/logout [post]
|
||||
// @Param request body LogoutRequest true "Refresh_token для аннулирования"
|
||||
// @Success 200 {object} map[string]string "{"message": "logged out successfully"}"
|
||||
// @Failure 400 {object} ErrorResponse "Не указан refresh_token"
|
||||
// @Failure 401 {object} ErrorResponse "Refresh_token не найден или уже аннулирован"
|
||||
// @Router /api/v1/auth/logout [post]
|
||||
func (h *Handler) Logout(c *gin.Context) {
|
||||
var req LogoutRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -143,28 +146,23 @@ 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 Профиль пользователя
|
||||
// @Description Получение профиля текущего авторизованного пользователя.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} UserResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/me [get]
|
||||
// @Success 200 {object} UserResponse "Данные пользователя"
|
||||
// @Failure 401 {object} ErrorResponse "Токен не указан или недействителен"
|
||||
// @Router /api/v1/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,30 +177,26 @@ 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 Смена пароля
|
||||
// @Description Изменение пароля текущего пользователя. Требуется указать старый и новый пароль.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Description Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body PasswordChangeRequest true "Password change details"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/password [put]
|
||||
// @Param request body PasswordChangeRequest true "Старый и новый пароль"
|
||||
// @Success 200 {object} map[string]string "{"message": "password changed successfully"}"
|
||||
// @Failure 400 {object} ErrorResponse "Ошибка валидации: неверный старый пароль, слабый новый или совпадают"
|
||||
// @Failure 401 {object} ErrorResponse "Токен не указан или недействителен"
|
||||
// @Router /api/v1/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 +204,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,30 +221,25 @@ 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 Обновление профиля
|
||||
// @Description Обновление username текущего пользователя.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body UpdateProfileRequest true "Profile update"
|
||||
// @Success 200 {object} UserResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/me [put]
|
||||
// @Param request body UpdateProfileRequest true "Новый username"
|
||||
// @Success 200 {object} UserResponse "Обновлённый профиль"
|
||||
// @Failure 400 {object} ErrorResponse "Ошибка валидации: username от 3 до 30 символов"
|
||||
// @Failure 401 {object} ErrorResponse "Токен не указан или недействителен"
|
||||
// @Router /api/v1/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()})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
+18
-16
@@ -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!"`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type visitor struct {
|
||||
count int
|
||||
lastSeen time.Time
|
||||
}
|
||||
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
visitors map[string]*visitor
|
||||
rate int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func NewRateLimiter(rate int, window time.Duration) *RateLimiter {
|
||||
rl := &RateLimiter{
|
||||
visitors: make(map[string]*visitor),
|
||||
rate: rate,
|
||||
window: window,
|
||||
}
|
||||
|
||||
go rl.cleanup()
|
||||
return rl
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
rl.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (rl *RateLimiter) Middleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
|
||||
rl.mu.Lock()
|
||||
v, exists := rl.visitors[ip]
|
||||
now := time.Now()
|
||||
|
||||
if !exists || now.Sub(v.lastSeen) > rl.window {
|
||||
rl.visitors[ip] = &visitor{count: 1, lastSeen: now}
|
||||
rl.mu.Unlock()
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
v.count++
|
||||
v.lastSeen = now
|
||||
|
||||
if v.count > rl.rate {
|
||||
rl.mu.Unlock()
|
||||
c.JSON(http.StatusTooManyRequests, ErrorResponse{Error: "too many requests, try again later"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
rl.mu.Unlock()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
+49
-48
@@ -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
|
||||
}
|
||||
|
||||
+41
-23
@@ -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"))
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package db
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
var ErrNoRows = gorm.ErrRecordNotFound
|
||||
+44
-33
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -16,17 +17,18 @@ func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// @Summary Create organization
|
||||
// @Description Create a new organization
|
||||
// @Summary Создание организации
|
||||
// @Description Создание новой организации. slug используется в URL и должен быть уникальным.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Tags organizations
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body CreateOrgRequest true "Organization details"
|
||||
// @Success 201 {object} OrgResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 409 {object} ErrorResponse
|
||||
// @Router /api/organizations [post]
|
||||
// @Param request body CreateOrgRequest true "Название и slug организации"
|
||||
// @Success 201 {object} OrgResponse "Организация создана"
|
||||
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей"
|
||||
// @Failure 409 {object} ErrorResponse "Slug уже занят"
|
||||
// @Router /api/v1/organizations [post]
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
var req CreateOrgRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -48,16 +50,17 @@ func (h *Handler) Create(c *gin.Context) {
|
||||
c.JSON(http.StatusCreated, OrgResponse{Organization: *org})
|
||||
}
|
||||
|
||||
// @Summary Get organization by ID
|
||||
// @Description Get organization details
|
||||
// @Summary Получить организацию
|
||||
// @Description Получение информации об организации по её ID.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Tags organizations
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "Organization ID"
|
||||
// @Success 200 {object} OrgResponse
|
||||
// @Failure 404 {object} ErrorResponse
|
||||
// @Router /api/organizations/{id} [get]
|
||||
// @Param id path string true "UUID организации"
|
||||
// @Success 200 {object} OrgResponse "Данные организации"
|
||||
// @Failure 404 {object} ErrorResponse "Организация не найдена"
|
||||
// @Router /api/v1/organizations/{id} [get]
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
@@ -75,17 +78,23 @@ func (h *Handler) GetByID(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, OrgResponse{Organization: *org})
|
||||
}
|
||||
|
||||
// @Summary List organizations
|
||||
// @Description Get all organizations
|
||||
// @Summary Список организаций
|
||||
// @Description Получение списка всех организаций с пагинацией.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Tags organizations
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} OrgListResponse
|
||||
// @Failure 500 {object} ErrorResponse
|
||||
// @Router /api/organizations [get]
|
||||
// @Param limit query int false "Количество записей на странице (по умолчанию 20)"
|
||||
// @Param offset query int false "Смещение от начала списка (по умолчанию 0)"
|
||||
// @Success 200 {object} OrgListResponse "Список организаций"
|
||||
// @Failure 500 {object} ErrorResponse "Внутренняя ошибка сервера"
|
||||
// @Router /api/v1/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"})
|
||||
@@ -95,18 +104,19 @@ func (h *Handler) List(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// @Summary Update organization
|
||||
// @Description Update organization name
|
||||
// @Summary Обновление организации
|
||||
// @Description Обновление названия организации. slug изменить нельзя.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Tags organizations
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "Organization ID"
|
||||
// @Param request body UpdateOrgRequest true "New organization details"
|
||||
// @Success 200 {object} OrgResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 404 {object} ErrorResponse
|
||||
// @Router /api/organizations/{id} [put]
|
||||
// @Param id path string true "UUID организации"
|
||||
// @Param request body UpdateOrgRequest true "Новое название организации"
|
||||
// @Success 200 {object} OrgResponse "Обновлённая организация"
|
||||
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей"
|
||||
// @Failure 404 {object} ErrorResponse "Организация не найдена"
|
||||
// @Router /api/v1/organizations/{id} [put]
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
@@ -130,16 +140,17 @@ func (h *Handler) Update(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, OrgResponse{Organization: *org})
|
||||
}
|
||||
|
||||
// @Summary Delete organization
|
||||
// @Description Delete an organization
|
||||
// @Summary Удаление организации
|
||||
// @Description Безвозвратное удаление организации по её ID.
|
||||
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
|
||||
// @Tags organizations
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "Organization ID"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Failure 404 {object} ErrorResponse
|
||||
// @Router /api/organizations/{id} [delete]
|
||||
// @Param id path string true "UUID организации"
|
||||
// @Success 200 {object} map[string]string "{"message": "organization deleted"}"
|
||||
// @Failure 404 {object} ErrorResponse "Организация не найдена"
|
||||
// @Router /api/v1/organizations/{id} [delete]
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+36
-42
@@ -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
|
||||
}
|
||||
|
||||
+34
-18
@@ -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"))
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user