Compare commits

..

7 Commits

Author SHA1 Message Date
d3m0k1d e4c86fab5d chore: add dockerfile and ci
ci / build (push) Failing after 4m31s
ci / build (pull_request) Failing after 2m42s
2026-06-14 00:34:37 +03:00
Mephimeow 93cd169616 added readme 2026-06-13 18:38:20 +00:00
Mephimeow fe15c04168 added some govno to postgres 2026-06-13 18:31:22 +00:00
Mephimeow 17ffe35f5c postgres 2026-06-13 17:30:14 +00:00
Mephimeow a26cd891e4 added logout 2026-06-12 10:18:04 +00:00
Mephimeow 130d5d5e3d added refresh tocken 2026-06-12 10:01:21 +00:00
Mephimeow 8c3e4b7a5a JWT proto with login & registration 2026-06-12 09:12:18 +00:00
24 changed files with 712 additions and 693 deletions
+1 -1
View File
@@ -26,4 +26,4 @@ jobs:
- name: Run tests - name: Run tests
run: go test ./... run: go test ./...
- name: Build - name: Build
run: go build ./cmd/backend run: go build -o backend ./cmd/main.go
+1 -1
View File
@@ -1,4 +1,4 @@
PHONY: docs PHONY: docs
docs: docs:
swag init -g cmd/backend/main.go --output docs/ swag init -g cmd/main.go --output docs/
+24 -29
View File
@@ -14,25 +14,22 @@ import (
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/config" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/config"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/org" "gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/org"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3" "github.com/pressly/goose/v3"
swaggerFiles "github.com/swaggo/files" "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger"
"gorm.io/driver/postgres"
"gorm.io/gorm"
) )
// @title AegisGuard API // @title AegisGuard API
// @version 1.0 // @version 1.0
// @description API системы управления AegisGuard. Позволяет управлять пользователями и организациями. // @description API for AegisGuard control plane
// @description Все защищённые эндпоинты требуют заголовок `Authorization: Bearer <token>`.
// @description Токен получается при регистрации или входе.
// @schemes http // @schemes http
// @BasePath /api/v1
// //
// @securityDefinitions.apikey Bearer // @securityDefinitions.apikey Bearer
// @in header // @in header
// @name Authorization // @name Authorization
// @description Введите `Bearer <token>`, где token — access_token из ответа /auth/login или /auth/register // @description Type "Bearer" followed by a space and the JWT token.
func main() { func main() {
cfg, err := config.Load() cfg, err := config.Load()
@@ -43,28 +40,27 @@ func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
gormDB, err := gorm.Open(postgres.Open(cfg.DatabaseURL), &gorm.Config{}) pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil { if err != nil {
log.Fatalf("failed to connect to postgres: %v", err) log.Fatalf("failed to create postgres pool: %v", err)
} }
defer pool.Close()
sqlDB, err := gormDB.DB() if err := pool.Ping(ctx); err != nil {
if err != nil {
log.Fatalf("failed to get underlying sql.DB: %v", err)
}
if err := sqlDB.PingContext(ctx); err != nil {
log.Fatalf("failed to ping postgres: %v", err) log.Fatalf("failed to ping postgres: %v", err)
} }
log.Println("connected to postgres") log.Println("connected to postgres")
if err := goose.Up(sqlDB, "migrations"); err != nil { db := stdlib.OpenDBFromPool(pool)
defer db.Close()
if err := goose.Up(db, "migrations"); err != nil {
log.Fatalf("failed to run migrations: %v", err) log.Fatalf("failed to run migrations: %v", err)
} }
log.Println("migrations applied") log.Println("migrations applied")
repo := auth.NewRepository(gormDB) repo := auth.NewRepository(pool)
orgRepo := org.NewRepository(gormDB) orgRepo := org.NewRepository(pool)
svc := auth.NewService(repo, cfg.JWTSecret, cfg.JWTExpiration, cfg.JWTRefreshExpiration) svc := auth.NewService(repo, cfg.JWTSecret, cfg.JWTExpiration, cfg.JWTRefreshExpiration)
handler := auth.NewHandler(svc) handler := auth.NewHandler(svc)
@@ -72,6 +68,7 @@ func main() {
orgSvc := org.NewService(orgRepo) orgSvc := org.NewService(orgRepo)
orgHandler := org.NewHandler(orgSvc) orgHandler := org.NewHandler(orgSvc)
loginLimiter := auth.NewRateLimiter(10, time.Minute)
authMW := auth.AuthMiddleware([]byte(cfg.JWTSecret)) authMW := auth.AuthMiddleware([]byte(cfg.JWTSecret))
go func() { go func() {
@@ -92,18 +89,17 @@ func main() {
docs.SwaggerInfo.Title = "AegisGuard API" docs.SwaggerInfo.Title = "AegisGuard API"
docs.SwaggerInfo.Version = "1.0" docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Description = "API системы управления AegisGuard. Позволяет управлять пользователями и организациями." docs.SwaggerInfo.Description = "API for AegisGuard"
docs.SwaggerInfo.Schemes = []string{"http"} docs.SwaggerInfo.Schemes = []string{"http"}
docs.SwaggerInfo.BasePath = "/api/v1"
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.GET("/health", func(c *gin.Context) { r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok"}) c.JSON(200, gin.H{"status": "ok"})
}) })
api := r.Group("/api/v1/auth") api := r.Group("/api/auth")
{ {
api.POST("/register", handler.Register) api.POST("/register", handler.Register)
api.POST("/login", handler.Login) api.POST("/login", loginLimiter.Middleware(), handler.Login)
api.POST("/refresh", handler.Refresh) api.POST("/refresh", handler.Refresh)
api.POST("/logout", handler.Logout) api.POST("/logout", handler.Logout)
api.GET("/me", authMW, handler.Me) api.GET("/me", authMW, handler.Me)
@@ -111,7 +107,7 @@ func main() {
api.PUT("/password", authMW, handler.ChangePassword) api.PUT("/password", authMW, handler.ChangePassword)
} }
orgs := r.Group("/api/v1/organizations", authMW) orgs := r.Group("/api/organizations", authMW)
{ {
orgs.POST("", orgHandler.Create) orgs.POST("", orgHandler.Create)
orgs.GET("", orgHandler.List) orgs.GET("", orgHandler.List)
@@ -121,9 +117,8 @@ func main() {
} }
srv := &http.Server{ srv := &http.Server{
Addr: ":" + cfg.ServerPort, Addr: ":" + cfg.ServerPort,
Handler: r, Handler: r,
ReadHeaderTimeout: 10 * time.Second,
} }
go func() { go func() {
@@ -146,7 +141,7 @@ func main() {
log.Fatalf("server forced to shutdown: %v", err) log.Fatalf("server forced to shutdown: %v", err)
} }
_ = sqlDB.Close() pool.Close()
log.Println("server stopped") log.Println("server stopped")
} }
+78 -98
View File
@@ -15,9 +15,9 @@ const docTemplate = `{
"host": "{{.Host}}", "host": "{{.Host}}",
"basePath": "{{.BasePath}}", "basePath": "{{.BasePath}}",
"paths": { "paths": {
"/api/v1/auth/login": { "/api/auth/login": {
"post": { "post": {
"description": "Аутентификация по email и паролю. Возвращает access_token (JWT) и refresh_token.", "description": "Authenticate user with email and password, returns JWT token",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -27,10 +27,10 @@ const docTemplate = `{
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Вход", "summary": "Login",
"parameters": [ "parameters": [
{ {
"description": "Email и пароль", "description": "Login credentials",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -41,19 +41,19 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Успешный вход, токены в ответе", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.AuthResponse" "$ref": "#/definitions/auth.AuthResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Неверный email или пароль", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -61,9 +61,9 @@ const docTemplate = `{
} }
} }
}, },
"/api/v1/auth/logout": { "/api/auth/logout": {
"post": { "post": {
"description": "Аннулирование refresh_token. После выхода повторное использование того же refresh_token вернёт 401.", "description": "Invalidate a refresh token (logout)",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -73,10 +73,10 @@ const docTemplate = `{
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Выход", "summary": "Logout",
"parameters": [ "parameters": [
{ {
"description": "Refresh_token для аннулирования", "description": "Refresh token to invalidate",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -87,7 +87,7 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "{\"message\": \"logged out successfully\"}", "description": "OK",
"schema": { "schema": {
"type": "object", "type": "object",
"additionalProperties": { "additionalProperties": {
@@ -96,13 +96,13 @@ const docTemplate = `{
} }
}, },
"400": { "400": {
"description": "Не указан refresh_token", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Refresh_token не найден или уже аннулирован", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -110,14 +110,14 @@ const docTemplate = `{
} }
} }
}, },
"/api/v1/auth/me": { "/api/auth/me": {
"get": { "get": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Получение профиля текущего авторизованного пользователя.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.", "description": "Get authenticated user's profile",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -127,16 +127,16 @@ const docTemplate = `{
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Профиль пользователя", "summary": "Get current user",
"responses": { "responses": {
"200": { "200": {
"description": "Данные пользователя", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.UserResponse" "$ref": "#/definitions/auth.UserResponse"
} }
}, },
"401": { "401": {
"description": "Токен не указан или недействителен", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -149,7 +149,7 @@ const docTemplate = `{
"Bearer": [] "Bearer": []
} }
], ],
"description": "Обновление username текущего пользователя.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.", "description": "Update current user's username",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -159,10 +159,10 @@ const docTemplate = `{
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Обновление профиля", "summary": "Update profile",
"parameters": [ "parameters": [
{ {
"description": "Новый username", "description": "Profile update",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -173,19 +173,19 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Обновлённый профиль", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.UserResponse" "$ref": "#/definitions/auth.UserResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации: username от 3 до 30 символов", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Токен не указан или недействителен", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -193,14 +193,14 @@ const docTemplate = `{
} }
} }
}, },
"/api/v1/auth/password": { "/api/auth/password": {
"put": { "put": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Изменение пароля текущего пользователя. Требуется указать старый и новый пароль.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.", "description": "Change current user's password",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -210,10 +210,10 @@ const docTemplate = `{
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Смена пароля", "summary": "Change password",
"parameters": [ "parameters": [
{ {
"description": "Старый и новый пароль", "description": "Password change details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -224,7 +224,7 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "{\"message\": \"password changed successfully\"}", "description": "OK",
"schema": { "schema": {
"type": "object", "type": "object",
"additionalProperties": { "additionalProperties": {
@@ -233,13 +233,13 @@ const docTemplate = `{
} }
}, },
"400": { "400": {
"description": "Ошибка валидации: неверный старый пароль, слабый новый или совпадают", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Токен не указан или недействителен", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -247,9 +247,9 @@ const docTemplate = `{
} }
} }
}, },
"/api/v1/auth/refresh": { "/api/auth/refresh": {
"post": { "post": {
"description": "Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация).\nЕсли refresh_token истёк или уже был использован — придёт 401.", "description": "Get a new access token using a refresh token",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -259,10 +259,10 @@ const docTemplate = `{
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Обновление токенов", "summary": "Refresh token",
"parameters": [ "parameters": [
{ {
"description": "Действительный refresh_token", "description": "Refresh token",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -273,19 +273,19 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Новая пара токенов", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.AuthResponse" "$ref": "#/definitions/auth.AuthResponse"
} }
}, },
"400": { "400": {
"description": "Не указан refresh_token", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Refresh_token недействителен или истёк", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -293,9 +293,9 @@ const docTemplate = `{
} }
} }
}, },
"/api/v1/auth/register": { "/api/auth/register": {
"post": { "post": {
"description": "Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.", "description": "Create user account with username, email, password",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -305,10 +305,10 @@ const docTemplate = `{
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Регистрация", "summary": "Register",
"parameters": [ "parameters": [
{ {
"description": "Данные для регистрации", "description": "Registration details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -319,19 +319,19 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"201": { "201": {
"description": "Пользователь создан, токены в ответе", "description": "Created",
"schema": { "schema": {
"$ref": "#/definitions/auth.AuthResponse" "$ref": "#/definitions/auth.AuthResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей (некорректный email, слабый пароль)", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"409": { "409": {
"description": "Email уже зарегистрирован", "description": "Conflict",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -339,14 +339,14 @@ const docTemplate = `{
} }
} }
}, },
"/api/v1/organizations": { "/api/organizations": {
"get": { "get": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Получение списка всех организаций с пагинацией.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.", "description": "Get all organizations",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -356,30 +356,16 @@ const docTemplate = `{
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Список организаций", "summary": "List organizations",
"parameters": [
{
"type": "integer",
"description": "Количество записей на странице (по умолчанию 20)",
"name": "limit",
"in": "query"
},
{
"type": "integer",
"description": "Смещение от начала списка (по умолчанию 0)",
"name": "offset",
"in": "query"
}
],
"responses": { "responses": {
"200": { "200": {
"description": "Список организаций", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgListResponse" "$ref": "#/definitions/org.OrgListResponse"
} }
}, },
"500": { "500": {
"description": "Внутренняя ошибка сервера", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -392,7 +378,7 @@ const docTemplate = `{
"Bearer": [] "Bearer": []
} }
], ],
"description": "Создание новой организации. slug используется в URL и должен быть уникальным.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.", "description": "Create a new organization",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -402,10 +388,10 @@ const docTemplate = `{
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Создание организации", "summary": "Create organization",
"parameters": [ "parameters": [
{ {
"description": "Название и slug организации", "description": "Organization details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -416,19 +402,19 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"201": { "201": {
"description": "Организация создана", "description": "Created",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgResponse" "$ref": "#/definitions/org.OrgResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
}, },
"409": { "409": {
"description": "Slug уже занят", "description": "Conflict",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -436,14 +422,14 @@ const docTemplate = `{
} }
} }
}, },
"/api/v1/organizations/{id}": { "/api/organizations/{id}": {
"get": { "get": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Получение информации об организации по её ID.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.", "description": "Get organization details",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -453,11 +439,11 @@ const docTemplate = `{
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Получить организацию", "summary": "Get organization by ID",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
"description": "UUID организации", "description": "Organization ID",
"name": "id", "name": "id",
"in": "path", "in": "path",
"required": true "required": true
@@ -465,13 +451,13 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Данные организации", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgResponse" "$ref": "#/definitions/org.OrgResponse"
} }
}, },
"404": { "404": {
"description": "Организация не найдена", "description": "Not Found",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -484,7 +470,7 @@ const docTemplate = `{
"Bearer": [] "Bearer": []
} }
], ],
"description": "Обновление названия организации. slug изменить нельзя.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.", "description": "Update organization name",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -494,17 +480,17 @@ const docTemplate = `{
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Обновление организации", "summary": "Update organization",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
"description": "UUID организации", "description": "Organization ID",
"name": "id", "name": "id",
"in": "path", "in": "path",
"required": true "required": true
}, },
{ {
"description": "Новое название организации", "description": "New organization details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -515,19 +501,19 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Обновлённая организация", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgResponse" "$ref": "#/definitions/org.OrgResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
}, },
"404": { "404": {
"description": "Организация не найдена", "description": "Not Found",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -540,7 +526,7 @@ const docTemplate = `{
"Bearer": [] "Bearer": []
} }
], ],
"description": "Безвозвратное удаление организации по её ID.\n**Требуется:** заголовок ` + "`" + `Authorization: Bearer \u003ctoken\u003e` + "`" + `.", "description": "Delete an organization",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -550,11 +536,11 @@ const docTemplate = `{
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Удаление организации", "summary": "Delete organization",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
"description": "UUID организации", "description": "Organization ID",
"name": "id", "name": "id",
"in": "path", "in": "path",
"required": true "required": true
@@ -562,7 +548,7 @@ const docTemplate = `{
], ],
"responses": { "responses": {
"200": { "200": {
"description": "{\"message\": \"organization deleted\"}", "description": "OK",
"schema": { "schema": {
"type": "object", "type": "object",
"additionalProperties": { "additionalProperties": {
@@ -571,7 +557,7 @@ const docTemplate = `{
} }
}, },
"404": { "404": {
"description": "Организация не найдена", "description": "Not Found",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -761,12 +747,6 @@ const docTemplate = `{
"org.OrgListResponse": { "org.OrgListResponse": {
"type": "object", "type": "object",
"properties": { "properties": {
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"organizations": { "organizations": {
"type": "array", "type": "array",
"items": { "items": {
@@ -823,7 +803,7 @@ const docTemplate = `{
}, },
"securityDefinitions": { "securityDefinitions": {
"Bearer": { "Bearer": {
"description": "Введите ` + "`" + `Bearer \u003ctoken\u003e` + "`" + `, где token — access_token из ответа /auth/login или /auth/register", "description": "Type \"Bearer\" followed by a space and the JWT token.",
"type": "apiKey", "type": "apiKey",
"name": "Authorization", "name": "Authorization",
"in": "header" "in": "header"
@@ -835,10 +815,10 @@ const docTemplate = `{
var SwaggerInfo = &swag.Spec{ var SwaggerInfo = &swag.Spec{
Version: "1.0", Version: "1.0",
Host: "", Host: "",
BasePath: "/api/v1", BasePath: "",
Schemes: []string{"http"}, Schemes: []string{"http"},
Title: "AegisGuard API", Title: "AegisGuard API",
Description: "API системы управления AegisGuard. Позволяет управлять пользователями и организациями.\nВсе защищённые эндпоинты требуют заголовок `Authorization: Bearer <token>`.\nТокен получается при регистрации или входе.", Description: "API for AegisGuard control plane",
InfoInstanceName: "swagger", InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate, SwaggerTemplate: docTemplate,
LeftDelim: "{{", LeftDelim: "{{",
+77 -98
View File
@@ -4,16 +4,15 @@
], ],
"swagger": "2.0", "swagger": "2.0",
"info": { "info": {
"description": "API системы управления AegisGuard. Позволяет управлять пользователями и организациями.\nВсе защищённые эндпоинты требуют заголовок `Authorization: Bearer \u003ctoken\u003e`.\nТокен получается при регистрации или входе.", "description": "API for AegisGuard control plane",
"title": "AegisGuard API", "title": "AegisGuard API",
"contact": {}, "contact": {},
"version": "1.0" "version": "1.0"
}, },
"basePath": "/api/v1",
"paths": { "paths": {
"/api/v1/auth/login": { "/api/auth/login": {
"post": { "post": {
"description": "Аутентификация по email и паролю. Возвращает access_token (JWT) и refresh_token.", "description": "Authenticate user with email and password, returns JWT token",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -23,10 +22,10 @@
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Вход", "summary": "Login",
"parameters": [ "parameters": [
{ {
"description": "Email и пароль", "description": "Login credentials",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -37,19 +36,19 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Успешный вход, токены в ответе", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.AuthResponse" "$ref": "#/definitions/auth.AuthResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Неверный email или пароль", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -57,9 +56,9 @@
} }
} }
}, },
"/api/v1/auth/logout": { "/api/auth/logout": {
"post": { "post": {
"description": "Аннулирование refresh_token. После выхода повторное использование того же refresh_token вернёт 401.", "description": "Invalidate a refresh token (logout)",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -69,10 +68,10 @@
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Выход", "summary": "Logout",
"parameters": [ "parameters": [
{ {
"description": "Refresh_token для аннулирования", "description": "Refresh token to invalidate",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -83,7 +82,7 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "{\"message\": \"logged out successfully\"}", "description": "OK",
"schema": { "schema": {
"type": "object", "type": "object",
"additionalProperties": { "additionalProperties": {
@@ -92,13 +91,13 @@
} }
}, },
"400": { "400": {
"description": "Не указан refresh_token", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Refresh_token не найден или уже аннулирован", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -106,14 +105,14 @@
} }
} }
}, },
"/api/v1/auth/me": { "/api/auth/me": {
"get": { "get": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Получение профиля текущего авторизованного пользователя.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.", "description": "Get authenticated user's profile",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -123,16 +122,16 @@
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Профиль пользователя", "summary": "Get current user",
"responses": { "responses": {
"200": { "200": {
"description": "Данные пользователя", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.UserResponse" "$ref": "#/definitions/auth.UserResponse"
} }
}, },
"401": { "401": {
"description": "Токен не указан или недействителен", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -145,7 +144,7 @@
"Bearer": [] "Bearer": []
} }
], ],
"description": "Обновление username текущего пользователя.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.", "description": "Update current user's username",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -155,10 +154,10 @@
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Обновление профиля", "summary": "Update profile",
"parameters": [ "parameters": [
{ {
"description": "Новый username", "description": "Profile update",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -169,19 +168,19 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Обновлённый профиль", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.UserResponse" "$ref": "#/definitions/auth.UserResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации: username от 3 до 30 символов", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Токен не указан или недействителен", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -189,14 +188,14 @@
} }
} }
}, },
"/api/v1/auth/password": { "/api/auth/password": {
"put": { "put": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Изменение пароля текущего пользователя. Требуется указать старый и новый пароль.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.", "description": "Change current user's password",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -206,10 +205,10 @@
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Смена пароля", "summary": "Change password",
"parameters": [ "parameters": [
{ {
"description": "Старый и новый пароль", "description": "Password change details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -220,7 +219,7 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "{\"message\": \"password changed successfully\"}", "description": "OK",
"schema": { "schema": {
"type": "object", "type": "object",
"additionalProperties": { "additionalProperties": {
@@ -229,13 +228,13 @@
} }
}, },
"400": { "400": {
"description": "Ошибка валидации: неверный старый пароль, слабый новый или совпадают", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Токен не указан или недействителен", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -243,9 +242,9 @@
} }
} }
}, },
"/api/v1/auth/refresh": { "/api/auth/refresh": {
"post": { "post": {
"description": "Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация).\nЕсли refresh_token истёк или уже был использован — придёт 401.", "description": "Get a new access token using a refresh token",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -255,10 +254,10 @@
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Обновление токенов", "summary": "Refresh token",
"parameters": [ "parameters": [
{ {
"description": "Действительный refresh_token", "description": "Refresh token",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -269,19 +268,19 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Новая пара токенов", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/auth.AuthResponse" "$ref": "#/definitions/auth.AuthResponse"
} }
}, },
"400": { "400": {
"description": "Не указан refresh_token", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"401": { "401": {
"description": "Refresh_token недействителен или истёк", "description": "Unauthorized",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -289,9 +288,9 @@
} }
} }
}, },
"/api/v1/auth/register": { "/api/auth/register": {
"post": { "post": {
"description": "Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token.\nПароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.", "description": "Create user account with username, email, password",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -301,10 +300,10 @@
"tags": [ "tags": [
"auth" "auth"
], ],
"summary": "Регистрация", "summary": "Register",
"parameters": [ "parameters": [
{ {
"description": "Данные для регистрации", "description": "Registration details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -315,19 +314,19 @@
], ],
"responses": { "responses": {
"201": { "201": {
"description": "Пользователь создан, токены в ответе", "description": "Created",
"schema": { "schema": {
"$ref": "#/definitions/auth.AuthResponse" "$ref": "#/definitions/auth.AuthResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей (некорректный email, слабый пароль)", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
}, },
"409": { "409": {
"description": "Email уже зарегистрирован", "description": "Conflict",
"schema": { "schema": {
"$ref": "#/definitions/auth.ErrorResponse" "$ref": "#/definitions/auth.ErrorResponse"
} }
@@ -335,14 +334,14 @@
} }
} }
}, },
"/api/v1/organizations": { "/api/organizations": {
"get": { "get": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Получение списка всех организаций с пагинацией.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.", "description": "Get all organizations",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -352,30 +351,16 @@
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Список организаций", "summary": "List organizations",
"parameters": [
{
"type": "integer",
"description": "Количество записей на странице (по умолчанию 20)",
"name": "limit",
"in": "query"
},
{
"type": "integer",
"description": "Смещение от начала списка (по умолчанию 0)",
"name": "offset",
"in": "query"
}
],
"responses": { "responses": {
"200": { "200": {
"description": "Список организаций", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgListResponse" "$ref": "#/definitions/org.OrgListResponse"
} }
}, },
"500": { "500": {
"description": "Внутренняя ошибка сервера", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -388,7 +373,7 @@
"Bearer": [] "Bearer": []
} }
], ],
"description": "Создание новой организации. slug используется в URL и должен быть уникальным.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.", "description": "Create a new organization",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -398,10 +383,10 @@
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Создание организации", "summary": "Create organization",
"parameters": [ "parameters": [
{ {
"description": "Название и slug организации", "description": "Organization details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -412,19 +397,19 @@
], ],
"responses": { "responses": {
"201": { "201": {
"description": "Организация создана", "description": "Created",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgResponse" "$ref": "#/definitions/org.OrgResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
}, },
"409": { "409": {
"description": "Slug уже занят", "description": "Conflict",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -432,14 +417,14 @@
} }
} }
}, },
"/api/v1/organizations/{id}": { "/api/organizations/{id}": {
"get": { "get": {
"security": [ "security": [
{ {
"Bearer": [] "Bearer": []
} }
], ],
"description": "Получение информации об организации по её ID.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.", "description": "Get organization details",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -449,11 +434,11 @@
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Получить организацию", "summary": "Get organization by ID",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
"description": "UUID организации", "description": "Organization ID",
"name": "id", "name": "id",
"in": "path", "in": "path",
"required": true "required": true
@@ -461,13 +446,13 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Данные организации", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgResponse" "$ref": "#/definitions/org.OrgResponse"
} }
}, },
"404": { "404": {
"description": "Организация не найдена", "description": "Not Found",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -480,7 +465,7 @@
"Bearer": [] "Bearer": []
} }
], ],
"description": "Обновление названия организации. slug изменить нельзя.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.", "description": "Update organization name",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -490,17 +475,17 @@
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Обновление организации", "summary": "Update organization",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
"description": "UUID организации", "description": "Organization ID",
"name": "id", "name": "id",
"in": "path", "in": "path",
"required": true "required": true
}, },
{ {
"description": "Новое название организации", "description": "New organization details",
"name": "request", "name": "request",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -511,19 +496,19 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Обновлённая организация", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/org.OrgResponse" "$ref": "#/definitions/org.OrgResponse"
} }
}, },
"400": { "400": {
"description": "Ошибка валидации полей", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
}, },
"404": { "404": {
"description": "Организация не найдена", "description": "Not Found",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -536,7 +521,7 @@
"Bearer": [] "Bearer": []
} }
], ],
"description": "Безвозвратное удаление организации по её ID.\n**Требуется:** заголовок `Authorization: Bearer \u003ctoken\u003e`.", "description": "Delete an organization",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -546,11 +531,11 @@
"tags": [ "tags": [
"organizations" "organizations"
], ],
"summary": "Удаление организации", "summary": "Delete organization",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
"description": "UUID организации", "description": "Organization ID",
"name": "id", "name": "id",
"in": "path", "in": "path",
"required": true "required": true
@@ -558,7 +543,7 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "{\"message\": \"organization deleted\"}", "description": "OK",
"schema": { "schema": {
"type": "object", "type": "object",
"additionalProperties": { "additionalProperties": {
@@ -567,7 +552,7 @@
} }
}, },
"404": { "404": {
"description": "Организация не найдена", "description": "Not Found",
"schema": { "schema": {
"$ref": "#/definitions/org.ErrorResponse" "$ref": "#/definitions/org.ErrorResponse"
} }
@@ -757,12 +742,6 @@
"org.OrgListResponse": { "org.OrgListResponse": {
"type": "object", "type": "object",
"properties": { "properties": {
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"organizations": { "organizations": {
"type": "array", "type": "array",
"items": { "items": {
@@ -819,7 +798,7 @@
}, },
"securityDefinitions": { "securityDefinitions": {
"Bearer": { "Bearer": {
"description": "Введите `Bearer \u003ctoken\u003e`, где token — access_token из ответа /auth/login или /auth/register", "description": "Type \"Bearer\" followed by a space and the JWT token.",
"type": "apiKey", "type": "apiKey",
"name": "Authorization", "name": "Authorization",
"in": "header" "in": "header"
+77 -119
View File
@@ -1,4 +1,3 @@
basePath: /api/v1
definitions: definitions:
auth.AuthResponse: auth.AuthResponse:
properties: properties:
@@ -126,10 +125,6 @@ definitions:
type: object type: object
org.OrgListResponse: org.OrgListResponse:
properties: properties:
limit:
type: integer
offset:
type: integer
organizations: organizations:
items: items:
$ref: '#/definitions/org.Organization' $ref: '#/definitions/org.Organization'
@@ -167,21 +162,17 @@ definitions:
type: object type: object
info: info:
contact: {} contact: {}
description: |- description: API for AegisGuard control plane
API системы управления AegisGuard. Позволяет управлять пользователями и организациями.
Все защищённые эндпоинты требуют заголовок `Authorization: Bearer <token>`.
Токен получается при регистрации или входе.
title: AegisGuard API title: AegisGuard API
version: "1.0" version: "1.0"
paths: paths:
/api/v1/auth/login: /api/auth/login:
post: post:
consumes: consumes:
- application/json - application/json
description: Аутентификация по email и паролю. Возвращает access_token (JWT) description: Authenticate user with email and password, returns JWT token
и refresh_token.
parameters: parameters:
- description: Email и пароль - description: Login credentials
in: body in: body
name: request name: request
required: true required: true
@@ -191,28 +182,27 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: Успешный вход, токены в ответе description: OK
schema: schema:
$ref: '#/definitions/auth.AuthResponse' $ref: '#/definitions/auth.AuthResponse'
"400": "400":
description: Ошибка валидации полей description: Bad Request
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
"401": "401":
description: Неверный email или пароль description: Unauthorized
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
summary: Вход summary: Login
tags: tags:
- auth - auth
/api/v1/auth/logout: /api/auth/logout:
post: post:
consumes: consumes:
- application/json - application/json
description: Аннулирование refresh_token. После выхода повторное использование description: Invalidate a refresh token (logout)
того же refresh_token вернёт 401.
parameters: parameters:
- description: Refresh_token для аннулирования - description: Refresh token to invalidate
in: body in: body
name: request name: request
required: true required: true
@@ -222,53 +212,49 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: '{"message": "logged out successfully"}' description: OK
schema: schema:
additionalProperties: additionalProperties:
type: string type: string
type: object type: object
"400": "400":
description: Не указан refresh_token description: Bad Request
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
"401": "401":
description: Refresh_token не найден или уже аннулирован description: Unauthorized
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
summary: Выход summary: Logout
tags: tags:
- auth - auth
/api/v1/auth/me: /api/auth/me:
get: get:
consumes: consumes:
- application/json - application/json
description: |- description: Get authenticated user's profile
Получение профиля текущего авторизованного пользователя.
**Требуется:** заголовок `Authorization: Bearer <token>`.
produces: produces:
- application/json - application/json
responses: responses:
"200": "200":
description: Данные пользователя description: OK
schema: schema:
$ref: '#/definitions/auth.UserResponse' $ref: '#/definitions/auth.UserResponse'
"401": "401":
description: Токен не указан или недействителен description: Unauthorized
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Профиль пользователя summary: Get current user
tags: tags:
- auth - auth
put: put:
consumes: consumes:
- application/json - application/json
description: |- description: Update current user's username
Обновление username текущего пользователя.
**Требуется:** заголовок `Authorization: Bearer <token>`.
parameters: parameters:
- description: Новый username - description: Profile update
in: body in: body
name: request name: request
required: true required: true
@@ -278,32 +264,29 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: Обновлённый профиль description: OK
schema: schema:
$ref: '#/definitions/auth.UserResponse' $ref: '#/definitions/auth.UserResponse'
"400": "400":
description: 'Ошибка валидации: username от 3 до 30 символов' description: Bad Request
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
"401": "401":
description: Токен не указан или недействителен description: Unauthorized
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Обновление профиля summary: Update profile
tags: tags:
- auth - auth
/api/v1/auth/password: /api/auth/password:
put: put:
consumes: consumes:
- application/json - application/json
description: |- description: Change current user's password
Изменение пароля текущего пользователя. Требуется указать старый и новый пароль.
**Требуется:** заголовок `Authorization: Bearer <token>`.
Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
parameters: parameters:
- description: Старый и новый пароль - description: Password change details
in: body in: body
name: request name: request
required: true required: true
@@ -313,34 +296,31 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: '{"message": "password changed successfully"}' description: OK
schema: schema:
additionalProperties: additionalProperties:
type: string type: string
type: object type: object
"400": "400":
description: 'Ошибка валидации: неверный старый пароль, слабый новый или description: Bad Request
совпадают'
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
"401": "401":
description: Токен не указан или недействителен description: Unauthorized
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Смена пароля summary: Change password
tags: tags:
- auth - auth
/api/v1/auth/refresh: /api/auth/refresh:
post: post:
consumes: consumes:
- application/json - application/json
description: |- description: Get a new access token using a refresh token
Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация).
Если refresh_token истёк или уже был использован — придёт 401.
parameters: parameters:
- description: Действительный refresh_token - description: Refresh token
in: body in: body
name: request name: request
required: true required: true
@@ -350,29 +330,27 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: Новая пара токенов description: OK
schema: schema:
$ref: '#/definitions/auth.AuthResponse' $ref: '#/definitions/auth.AuthResponse'
"400": "400":
description: Не указан refresh_token description: Bad Request
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
"401": "401":
description: Refresh_token недействителен или истёк description: Unauthorized
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
summary: Обновление токенов summary: Refresh token
tags: tags:
- auth - auth
/api/v1/auth/register: /api/auth/register:
post: post:
consumes: consumes:
- application/json - application/json
description: |- description: Create user account with username, email, password
Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token.
Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
parameters: parameters:
- description: Данные для регистрации - description: Registration details
in: body in: body
name: request name: request
required: true required: true
@@ -382,60 +360,47 @@ paths:
- application/json - application/json
responses: responses:
"201": "201":
description: Пользователь создан, токены в ответе description: Created
schema: schema:
$ref: '#/definitions/auth.AuthResponse' $ref: '#/definitions/auth.AuthResponse'
"400": "400":
description: Ошибка валидации полей (некорректный email, слабый пароль) description: Bad Request
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
"409": "409":
description: Email уже зарегистрирован description: Conflict
schema: schema:
$ref: '#/definitions/auth.ErrorResponse' $ref: '#/definitions/auth.ErrorResponse'
summary: Регистрация summary: Register
tags: tags:
- auth - auth
/api/v1/organizations: /api/organizations:
get: get:
consumes: consumes:
- application/json - application/json
description: |- description: Get all organizations
Получение списка всех организаций с пагинацией.
**Требуется:** заголовок `Authorization: Bearer <token>`.
parameters:
- description: Количество записей на странице (по умолчанию 20)
in: query
name: limit
type: integer
- description: Смещение от начала списка (по умолчанию 0)
in: query
name: offset
type: integer
produces: produces:
- application/json - application/json
responses: responses:
"200": "200":
description: Список организаций description: OK
schema: schema:
$ref: '#/definitions/org.OrgListResponse' $ref: '#/definitions/org.OrgListResponse'
"500": "500":
description: Внутренняя ошибка сервера description: Internal Server Error
schema: schema:
$ref: '#/definitions/org.ErrorResponse' $ref: '#/definitions/org.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Список организаций summary: List organizations
tags: tags:
- organizations - organizations
post: post:
consumes: consumes:
- application/json - application/json
description: |- description: Create a new organization
Создание новой организации. slug используется в URL и должен быть уникальным.
**Требуется:** заголовок `Authorization: Bearer <token>`.
parameters: parameters:
- description: Название и slug организации - description: Organization details
in: body in: body
name: request name: request
required: true required: true
@@ -445,31 +410,29 @@ paths:
- application/json - application/json
responses: responses:
"201": "201":
description: Организация создана description: Created
schema: schema:
$ref: '#/definitions/org.OrgResponse' $ref: '#/definitions/org.OrgResponse'
"400": "400":
description: Ошибка валидации полей description: Bad Request
schema: schema:
$ref: '#/definitions/org.ErrorResponse' $ref: '#/definitions/org.ErrorResponse'
"409": "409":
description: Slug уже занят description: Conflict
schema: schema:
$ref: '#/definitions/org.ErrorResponse' $ref: '#/definitions/org.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Создание организации summary: Create organization
tags: tags:
- organizations - organizations
/api/v1/organizations/{id}: /api/organizations/{id}:
delete: delete:
consumes: consumes:
- application/json - application/json
description: |- description: Delete an organization
Безвозвратное удаление организации по её ID.
**Требуется:** заголовок `Authorization: Bearer <token>`.
parameters: parameters:
- description: UUID организации - description: Organization ID
in: path in: path
name: id name: id
required: true required: true
@@ -478,28 +441,26 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: '{"message": "organization deleted"}' description: OK
schema: schema:
additionalProperties: additionalProperties:
type: string type: string
type: object type: object
"404": "404":
description: Организация не найдена description: Not Found
schema: schema:
$ref: '#/definitions/org.ErrorResponse' $ref: '#/definitions/org.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Удаление организации summary: Delete organization
tags: tags:
- organizations - organizations
get: get:
consumes: consumes:
- application/json - application/json
description: |- description: Get organization details
Получение информации об организации по её ID.
**Требуется:** заголовок `Authorization: Bearer <token>`.
parameters: parameters:
- description: UUID организации - description: Organization ID
in: path in: path
name: id name: id
required: true required: true
@@ -508,31 +469,29 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: Данные организации description: OK
schema: schema:
$ref: '#/definitions/org.OrgResponse' $ref: '#/definitions/org.OrgResponse'
"404": "404":
description: Организация не найдена description: Not Found
schema: schema:
$ref: '#/definitions/org.ErrorResponse' $ref: '#/definitions/org.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Получить организацию summary: Get organization by ID
tags: tags:
- organizations - organizations
put: put:
consumes: consumes:
- application/json - application/json
description: |- description: Update organization name
Обновление названия организации. slug изменить нельзя.
**Требуется:** заголовок `Authorization: Bearer <token>`.
parameters: parameters:
- description: UUID организации - description: Organization ID
in: path in: path
name: id name: id
required: true required: true
type: string type: string
- description: Новое название организации - description: New organization details
in: body in: body
name: request name: request
required: true required: true
@@ -542,28 +501,27 @@ paths:
- application/json - application/json
responses: responses:
"200": "200":
description: Обновлённая организация description: OK
schema: schema:
$ref: '#/definitions/org.OrgResponse' $ref: '#/definitions/org.OrgResponse'
"400": "400":
description: Ошибка валидации полей description: Bad Request
schema: schema:
$ref: '#/definitions/org.ErrorResponse' $ref: '#/definitions/org.ErrorResponse'
"404": "404":
description: Организация не найдена description: Not Found
schema: schema:
$ref: '#/definitions/org.ErrorResponse' $ref: '#/definitions/org.ErrorResponse'
security: security:
- Bearer: [] - Bearer: []
summary: Обновление организации summary: Update organization
tags: tags:
- organizations - organizations
schemes: schemes:
- http - http
securityDefinitions: securityDefinitions:
Bearer: Bearer:
description: Введите `Bearer <token>`, где token — access_token из ответа /auth/login description: Type "Bearer" followed by a space and the JWT token.
или /auth/register
in: header in: header
name: Authorization name: Authorization
type: apiKey type: apiKey
+1 -5
View File
@@ -6,14 +6,13 @@ require (
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.12.0
github.com/golang-jwt/jwt/v5 v5.3.1 github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.7.4
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/pressly/goose/v3 v3.24.2 github.com/pressly/goose/v3 v3.24.2
github.com/swaggo/files v1.0.1 github.com/swaggo/files v1.0.1
github.com/swaggo/gin-swagger v1.6.1 github.com/swaggo/gin-swagger v1.6.1
github.com/swaggo/swag v1.16.6 github.com/swaggo/swag v1.16.6
golang.org/x/crypto v0.53.0 golang.org/x/crypto v0.53.0
gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.31.1
) )
require ( require (
@@ -37,10 +36,7 @@ require (
github.com/goccy/go-yaml v1.19.2 // indirect github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.7.4 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/josharian/intern v1.0.0 // indirect github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
-8
View File
@@ -63,10 +63,6 @@ github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
@@ -207,10 +203,6 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8= modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E= modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
-9
View File
@@ -1,9 +0,0 @@
package api
import "github.com/gin-gonic/gin"
func GetUserID(c *gin.Context) string {
raw, _ := c.Get("user_id")
id, _ := raw.(string)
return id
}
+108
View File
@@ -0,0 +1,108 @@
# JWT Аутентификация — AegisGuard API
## Схема работы
- **access_token** — JWT, живёт 24 часа. Передаётся в заголовке `Authorization: Bearer`.
- **refresh_token** — случайная строка, хранится в БД в виде хеша. Используется **один раз** (ротация): при запросе новой пары старый токен удаляется.
- Регистрация сразу возвращает токены — отдельный логин не нужен.
## Эндпоинты
### POST /api/auth/register
Создание аккаунта.
```
Запрос:
{ "username": "john", "email": "john@example.com", "password": "Secret123" }
Ответ 201:
{
"token": "eyJhbGciOiJIUzI1NiIs...",
"refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=",
"user": {
"id": "uuid",
"username": "john",
"email": "john@example.com",
"created_at": "2026-06-13T12:00:00Z"
}
}
```
- `username` — 330 символов
- `email` — валидный email
- `password` — минимум 8 символов, обязательно заглавная + строчная + цифра
Ошибки: `400` (валидация), `409` (email уже занят).
### POST /api/auth/login
```
Запрос:
{ "email": "john@example.com", "password": "Secret123" }
Ответ 200:
{ "token": "...", "refresh_token": "...", "user": { ... } }
```
Rate limit: 10 попыток в минуту с одного IP (`429 Too Many Requests`).
### POST /api/auth/refresh
Обновить токены по refresh_token. Старый удаляется, выдаётся новая пара.
```
Запрос:
{ "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=" }
Ответ 200:
{ "token": "...", "refresh_token": "...", "user": { ... } }
```
### POST /api/auth/logout
Удалить refresh_token из БД.
```
Запрос:
{ "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=" }
Ответ 200:
{ "message": "logged out successfully" }
```
## Заголовок авторизации
```
Authorization: Bearer <access_token>
```
## Формат JWT
```json
{
"user_id": "uuid",
"email": "john@example.com",
"sub": "uuid",
"exp": 1718000000,
"iat": 1717913600
}
```
- `user_id` — UUID пользователя
- `email` — Email пользователя
- `sub` — то же, что `user_id`
- `exp` — Unix-timestamp истечения токена
- `iat` — Unix-timestamp выпуска токена
## Формат ошибок
```json
{ "error": "описание" }
```
- `400` — ошибка валидации
- `401` — неверный email/пароль, токен протух или невалиден
- `409` — email уже зарегистрирован
- `429` — превышен лимит попыток логина
- `500` — внутренняя ошибка сервера
+6 -10
View File
@@ -29,16 +29,12 @@ func GenerateToken(userID, email string, secret []byte, expiration time.Duration
} }
func ValidateToken(tokenString string, secret []byte) (*Claims, error) { func ValidateToken(tokenString string, secret []byte) (*Claims, error) {
token, err := jwt.ParseWithClaims( token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) {
tokenString, if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
&Claims{}, return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
func(t *jwt.Token) (interface{}, error) { }
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return secret, nil
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) })
}
return secret, nil
},
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+72 -62
View File
@@ -5,7 +5,6 @@ import (
"log" "log"
"net/http" "net/http"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/api"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -17,17 +16,16 @@ func NewHandler(service *Service) *Handler {
return &Handler{service: service} return &Handler{service: service}
} }
// @Summary Регистрация // @Summary Register epta
// @Description Создание новой учётной записи. После успешной регистрации сразу возвращается access_token и refresh_token. // @Description Create user account with username, email, password
// @Description Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param request body RegisterRequest true "Данные для регистрации" // @Param request body RegisterRequest true "Registration details"
// @Success 201 {object} AuthResponse "Пользователь создан, токены в ответе" // @Success 201 {object} AuthResponse
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей (некорректный email, слабый пароль)" // @Failure 400 {object} ErrorResponse
// @Failure 409 {object} ErrorResponse "Email уже зарегистрирован" // @Failure 409 {object} ErrorResponse
// @Router /api/v1/auth/register [post] // @Router /api/auth/register [post]
func (h *Handler) Register(c *gin.Context) { func (h *Handler) Register(c *gin.Context) {
var req RegisterRequest var req RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
@@ -53,16 +51,16 @@ func (h *Handler) Register(c *gin.Context) {
c.JSON(http.StatusCreated, resp) c.JSON(http.StatusCreated, resp)
} }
// @Summary Вход // @Summary Login
// @Description Аутентификация по email и паролю. Возвращает access_token (JWT) и refresh_token. // @Description Authenticate user with email and password, returns JWT token
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param request body LoginRequest true "Email и пароль" // @Param request body LoginRequest true "Login credentials"
// @Success 200 {object} AuthResponse "Успешный вход, токены в ответе" // @Success 200 {object} AuthResponse
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей" // @Failure 400 {object} ErrorResponse
// @Failure 401 {object} ErrorResponse "Неверный email или пароль" // @Failure 401 {object} ErrorResponse
// @Router /api/v1/auth/login [post] // @Router /api/auth/login [post]
func (h *Handler) Login(c *gin.Context) { func (h *Handler) Login(c *gin.Context) {
var req LoginRequest var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
@@ -84,17 +82,16 @@ func (h *Handler) Login(c *gin.Context) {
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
} }
// @Summary Обновление токенов // @Summary Refresh epta token
// @Description Получение новой пары токенов по refresh_token. Старый refresh_token становится недействительным (ротация). // @Description Get a new access token using a refresh token
// @Description Если refresh_token истёк или уже был использован — придёт 401.
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param request body RefreshRequest true "Действительный refresh_token" // @Param request body RefreshRequest true "Refresh token"
// @Success 200 {object} AuthResponse "Новая пара токенов" // @Success 200 {object} AuthResponse
// @Failure 400 {object} ErrorResponse "Не указан refresh_token" // @Failure 400 {object} ErrorResponse
// @Failure 401 {object} ErrorResponse "Refresh_token недействителен или истёк" // @Failure 401 {object} ErrorResponse
// @Router /api/v1/auth/refresh [post] // @Router /api/auth/refresh [post]
func (h *Handler) Refresh(c *gin.Context) { func (h *Handler) Refresh(c *gin.Context) {
var req RefreshRequest var req RefreshRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
@@ -116,16 +113,16 @@ func (h *Handler) Refresh(c *gin.Context) {
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
} }
// @Summary Выход // @Summary Logout epta
// @Description Аннулирование refresh_token. После выхода повторное использование того же refresh_token вернёт 401. // @Description Invalidate a refresh token (logout)
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param request body LogoutRequest true "Refresh_token для аннулирования" // @Param request body LogoutRequest true "Refresh token to invalidate"
// @Success 200 {object} map[string]string "{"message": "logged out successfully"}" // @Success 200 {object} map[string]string
// @Failure 400 {object} ErrorResponse "Не указан refresh_token" // @Failure 400 {object} ErrorResponse
// @Failure 401 {object} ErrorResponse "Refresh_token не найден или уже аннулирован" // @Failure 401 {object} ErrorResponse
// @Router /api/v1/auth/logout [post] // @Router /api/auth/logout [post]
func (h *Handler) Logout(c *gin.Context) { func (h *Handler) Logout(c *gin.Context) {
var req LogoutRequest var req LogoutRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
@@ -146,23 +143,28 @@ func (h *Handler) Logout(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"}) c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"})
} }
// @Summary Профиль пользователя // @Summary Get epta current user
// @Description Получение профиля текущего авторизованного пользователя. // @Description Get authenticated user's profile
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Success 200 {object} UserResponse "Данные пользователя" // @Success 200 {object} UserResponse
// @Failure 401 {object} ErrorResponse "Токен не указан или недействителен" // @Failure 401 {object} ErrorResponse
// @Router /api/v1/auth/me [get] // @Router /api/auth/me [get]
func (h *Handler) Me(c *gin.Context) { func (h *Handler) Me(c *gin.Context) {
userID := api.GetUserID(c) rawUserID, exists := c.Get("user_id")
if userID == "" { if !exists {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
return return
} }
userID, ok := rawUserID.(string)
if !ok {
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
return
}
user, err := h.service.GetUserByID(c.Request.Context(), userID) user, err := h.service.GetUserByID(c.Request.Context(), userID)
if err != nil { if err != nil {
if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrInvalidUserID) { if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrInvalidUserID) {
@@ -177,26 +179,30 @@ func (h *Handler) Me(c *gin.Context) {
c.JSON(http.StatusOK, UserResponse{User: *user}) c.JSON(http.StatusOK, UserResponse{User: *user})
} }
// @Summary Смена пароля // @Summary Change epta password
// @Description Изменение пароля текущего пользователя. Требуется указать старый и новый пароль. // @Description Change current user's password
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Description Пароль должен содержать минимум 8 символов, заглавную букву, строчную букву и цифру.
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param request body PasswordChangeRequest true "Старый и новый пароль" // @Param request body PasswordChangeRequest true "Password change details"
// @Success 200 {object} map[string]string "{"message": "password changed successfully"}" // @Success 200 {object} map[string]string
// @Failure 400 {object} ErrorResponse "Ошибка валидации: неверный старый пароль, слабый новый или совпадают" // @Failure 400 {object} ErrorResponse
// @Failure 401 {object} ErrorResponse "Токен не указан или недействителен" // @Failure 401 {object} ErrorResponse
// @Router /api/v1/auth/password [put] // @Router /api/auth/password [put]
func (h *Handler) ChangePassword(c *gin.Context) { func (h *Handler) ChangePassword(c *gin.Context) {
userID := api.GetUserID(c) rawUserID, exists := c.Get("user_id")
if userID == "" { if !exists {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
return return
} }
userID, ok := rawUserID.(string)
if !ok {
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
return
}
var req PasswordChangeRequest var req PasswordChangeRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
@@ -204,8 +210,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {
} }
if err := h.service.ChangePassword(c.Request.Context(), userID, req); err != nil { if err := h.service.ChangePassword(c.Request.Context(), userID, req); err != nil {
if errors.Is(err, ErrWrongPassword) || errors.Is(err, ErrSamePassword) || if errors.Is(err, ErrWrongPassword) || errors.Is(err, ErrSamePassword) || errors.Is(err, ErrWeakPassword) {
errors.Is(err, ErrWeakPassword) {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
return return
} }
@@ -221,25 +226,30 @@ func (h *Handler) ChangePassword(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "password changed successfully"}) c.JSON(http.StatusOK, gin.H{"message": "password changed successfully"})
} }
// @Summary Обновление профиля // @Summary Update epta profile
// @Description Обновление username текущего пользователя. // @Description Update current user's username
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Tags auth // @Tags auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param request body UpdateProfileRequest true "Новый username" // @Param request body UpdateProfileRequest true "Profile update"
// @Success 200 {object} UserResponse "Обновлённый профиль" // @Success 200 {object} UserResponse
// @Failure 400 {object} ErrorResponse "Ошибка валидации: username от 3 до 30 символов" // @Failure 400 {object} ErrorResponse
// @Failure 401 {object} ErrorResponse "Токен не указан или недействителен" // @Failure 401 {object} ErrorResponse
// @Router /api/v1/auth/me [put] // @Router /api/auth/me [put]
func (h *Handler) UpdateProfile(c *gin.Context) { func (h *Handler) UpdateProfile(c *gin.Context) {
userID := api.GetUserID(c) rawUserID, exists := c.Get("user_id")
if userID == "" { if !exists {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"}) c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
return return
} }
userID, ok := rawUserID.(string)
if !ok {
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
return
}
var req UpdateProfileRequest var req UpdateProfileRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()}) c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
+3 -12
View File
@@ -11,28 +11,19 @@ func AuthMiddleware(jwtSecret []byte) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization") authHeader := c.GetHeader("Authorization")
if authHeader == "" { if authHeader == "" {
c.AbortWithStatusJSON( c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "authorization header required"})
http.StatusUnauthorized,
ErrorResponse{Error: "authorization header required"},
)
return return
} }
parts := strings.SplitN(authHeader, " ", 2) parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
c.AbortWithStatusJSON( c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid authorization header format"})
http.StatusUnauthorized,
ErrorResponse{Error: "invalid authorization header format"},
)
return return
} }
claims, err := ValidateToken(parts[1], jwtSecret) claims, err := ValidateToken(parts[1], jwtSecret)
if err != nil { if err != nil {
c.AbortWithStatusJSON( c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid or expired token"})
http.StatusUnauthorized,
ErrorResponse{Error: "invalid or expired token"},
)
return return
} }
+16 -18
View File
@@ -5,26 +5,26 @@ import (
) )
type User struct { type User struct {
ID string `gorm:"type:uuid;primaryKey" json:"id"` ID string `json:"id"`
Username string `gorm:"type:text;not null" json:"username"` Username string `json:"username"`
Email string `gorm:"type:text;not null;uniqueIndex" json:"email"` Email string `json:"email"`
PasswordHash string `gorm:"column:password_hash;type:text;not null" json:"-"` PasswordHash string `json:"-"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` CreatedAt time.Time `json:"created_at"`
} }
type RegisterRequest struct { type RegisterRequest struct {
Username string `json:"username" binding:"required,min=3,max=30" example:"john"` Username string `json:"username" binding:"required,min=3,max=30" example:"john"`
Email string `json:"email" binding:"required,email" example:"john@example.com"` Email string `json:"email" binding:"required,email" example:"john@example.com"`
Password string `json:"password" binding:"required,min=8" example:"Secret123!"` Password string `json:"password" binding:"required,min=8" example:"Secret123!"`
} }
type LoginRequest struct { type LoginRequest struct {
Email string `json:"email" binding:"required,email" example:"john@example.com"` Email string `json:"email" binding:"required,email" example:"john@example.com"`
Password string `json:"password" binding:"required" example:"secret123"` Password string `json:"password" binding:"required" example:"secret123"`
} }
type AuthResponse struct { type AuthResponse struct {
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."` Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."`
RefreshToken string `json:"refresh_token" example:"dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4="` RefreshToken string `json:"refresh_token" example:"dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4="`
User UserPublic `json:"user"` User UserPublic `json:"user"`
} }
@@ -38,15 +38,13 @@ type LogoutRequest struct {
} }
type RefreshTokenDoc struct { type RefreshTokenDoc struct {
ID string `gorm:"type:uuid;primaryKey" json:"id"` ID string `json:"id"`
UserID string `gorm:"column:user_id;type:uuid;not null;index" json:"user_id"` UserID string `json:"user_id"`
TokenHash string `gorm:"column:token_hash;type:text;not null;uniqueIndex" json:"token_hash"` TokenHash string `json:"token_hash"`
ExpiresAt time.Time `gorm:"column:expires_at;type:timestamptz;not null" json:"expires_at"` ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` CreatedAt time.Time `json:"created_at"`
} }
func (RefreshTokenDoc) TableName() string { return "refresh_tokens" }
type UserPublic struct { type UserPublic struct {
ID string `json:"id"` ID string `json:"id"`
Username string `json:"username"` Username string `json:"username"`
@@ -68,7 +66,7 @@ type UserResponse struct {
} }
type PasswordChangeRequest struct { type PasswordChangeRequest struct {
OldPassword string `json:"old_password" binding:"required" example:"Secret123!"` OldPassword string `json:"old_password" binding:"required" example:"Secret123!"`
NewPassword string `json:"new_password" binding:"required,min=8" example:"NewSecret456!"` NewPassword string `json:"new_password" binding:"required,min=8" example:"NewSecret456!"`
} }
+77
View File
@@ -0,0 +1,77 @@
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()
}
}
+43 -44
View File
@@ -5,39 +5,33 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"gorm.io/gorm" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
) )
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
}
type Repository struct { type Repository struct {
db *gorm.DB pool *pgxpool.Pool
} }
func NewRepository(db *gorm.DB) *Repository { func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{db: db} return &Repository{pool: pool}
} }
func (r *Repository) CreateUser(ctx context.Context, user *User) error { func (r *Repository) CreateUser(ctx context.Context, user *User) error {
user.ID = uuid.New().String() user.ID = uuid.New().String()
user.CreatedAt = time.Now().UTC() user.CreatedAt = time.Now().UTC()
return r.db.WithContext(ctx).Create(user).Error _, 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
} }
func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) { func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) {
var user User var user User
err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error 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)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -46,7 +40,9 @@ func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, erro
func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) { func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) {
var user User var user User
err := r.db.WithContext(ctx).Where("id = ?", id).First(&user).Error 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)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -56,18 +52,18 @@ func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) {
func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error { func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error {
doc.ID = uuid.New().String() doc.ID = uuid.New().String()
doc.CreatedAt = time.Now().UTC() doc.CreatedAt = time.Now().UTC()
return r.db.WithContext(ctx).Create(doc).Error _, 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
} }
func (r *Repository) FindRefreshTokenByHash( func (r *Repository) FindRefreshTokenByHash(ctx context.Context, hash string) (*RefreshTokenDoc, error) {
ctx context.Context,
hash string,
) (*RefreshTokenDoc, error) {
var doc RefreshTokenDoc var doc RefreshTokenDoc
err := r.db.WithContext(ctx). err := r.pool.QueryRow(ctx,
Where("token_hash = ? AND expires_at > NOW()", hash). `SELECT id, user_id, token_hash, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1 AND expires_at > NOW()`, hash,
First(&doc). ).Scan(&doc.ID, &doc.UserID, &doc.TokenHash, &doc.ExpiresAt, &doc.CreatedAt)
Error
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -75,28 +71,31 @@ func (r *Repository) FindRefreshTokenByHash(
} }
func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error { func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&RefreshTokenDoc{}).Error _, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE id = $1`, id)
} return err
func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error) {
result := r.db.WithContext(ctx).Where("token_hash = ?", hash).Delete(&RefreshTokenDoc{})
if result.Error != nil {
return false, result.Error
}
return result.RowsAffected > 0, nil
} }
func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error { func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error {
return r.db.WithContext(ctx).Model(&User{}).Where("id = ?", id). _, err := r.pool.Exec(ctx, `UPDATE users SET username = $1 WHERE id = $2`, username, id)
Update("username", username).Error return err
} }
func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error { func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error {
return r.db.WithContext(ctx).Model(&User{}).Where("id = ?", id). _, err := r.pool.Exec(ctx, `UPDATE users SET password_hash = $1 WHERE id = $2`, passwordHash, id)
Update("password_hash", passwordHash).Error return err
} }
func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error { func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error {
return r.db.WithContext(ctx). _, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE expires_at <= NOW()`)
Where("expires_at <= NOW()").Delete(&RefreshTokenDoc{}).Error return err
} }
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
}
return tag.RowsAffected() > 0, nil
}
var ErrNoRows = pgx.ErrNoRows
+23 -41
View File
@@ -11,33 +11,30 @@ import (
"time" "time"
"unicode" "unicode"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
var ( var (
ErrEmailExists = errors.New("email already registered") ErrEmailExists = errors.New("email already registered")
ErrInvalidCreds = errors.New("invalid email or password") ErrInvalidCreds = errors.New("invalid email or password")
ErrUserNotFound = errors.New("user not found") ErrUserNotFound = errors.New("user not found")
ErrInvalidUserID = errors.New("invalid user ID") ErrInvalidUserID = errors.New("invalid user ID")
ErrInvalidRefresh = errors.New("invalid refresh token") ErrInvalidRefresh = errors.New("invalid refresh token")
ErrRefreshExpired = errors.New("refresh token expired") ErrRefreshExpired = errors.New("refresh token expired")
ErrLogoutInvalid = errors.New("refresh token not found or already used") ErrLogoutInvalid = errors.New("refresh token not found or already used")
ErrWrongPassword = errors.New("current password is incorrect") ErrWrongPassword = errors.New("current password is incorrect")
ErrWeakPassword = errors.New( ErrWeakPassword = errors.New("password must be at least 8 characters with uppercase, lowercase, and digit")
"password must be at least 8 characters with uppercase, lowercase, and digit", ErrSamePassword = errors.New("new password must differ from current password")
)
ErrSamePassword = errors.New("new password must differ from current password")
) )
type Service struct { type Service struct {
repo UserRepository repo *Repository
jwtSecret []byte jwtSecret []byte
jwtExp time.Duration jwtExp time.Duration
refreshExp time.Duration refreshExp time.Duration
} }
func NewService(repo UserRepository, jwtSecret string, jwtExp, refreshExp time.Duration) *Service { func NewService(repo *Repository, jwtSecret string, jwtExp, refreshExp time.Duration) *Service {
return &Service{ return &Service{
repo: repo, repo: repo,
jwtSecret: []byte(jwtSecret), jwtSecret: []byte(jwtSecret),
@@ -116,7 +113,7 @@ func (s *Service) Register(ctx context.Context, req RegisterRequest) (*AuthRespo
req.Email = strings.ToLower(req.Email) req.Email = strings.ToLower(req.Email)
existing, err := s.repo.FindByEmail(ctx, req.Email) existing, err := s.repo.FindByEmail(ctx, req.Email)
if err != nil && !errors.Is(err, db.ErrNoRows) { if err != nil && !errors.Is(err, ErrNoRows) {
return nil, fmt.Errorf("failed to check existing user: %w", err) return nil, fmt.Errorf("failed to check existing user: %w", err)
} }
if existing != nil { if existing != nil {
@@ -148,16 +145,13 @@ func (s *Service) Login(ctx context.Context, req LoginRequest) (*AuthResponse, e
req.Email = strings.ToLower(req.Email) req.Email = strings.ToLower(req.Email)
user, err := s.repo.FindByEmail(ctx, req.Email) user, err := s.repo.FindByEmail(ctx, req.Email)
if err != nil { if err != nil {
if errors.Is(err, db.ErrNoRows) { if errors.Is(err, ErrNoRows) {
return nil, ErrInvalidCreds return nil, ErrInvalidCreds
} }
return nil, fmt.Errorf("failed to find user: %w", err) return nil, fmt.Errorf("failed to find user: %w", err)
} }
if err := bcrypt.CompareHashAndPassword( if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
[]byte(user.PasswordHash),
[]byte(req.Password),
); err != nil {
return nil, ErrInvalidCreds return nil, ErrInvalidCreds
} }
@@ -169,7 +163,7 @@ func (s *Service) Refresh(ctx context.Context, rawRefresh string) (*AuthResponse
doc, err := s.repo.FindRefreshTokenByHash(ctx, hash) doc, err := s.repo.FindRefreshTokenByHash(ctx, hash)
if err != nil { if err != nil {
if errors.Is(err, db.ErrNoRows) { if errors.Is(err, ErrNoRows) {
return nil, ErrInvalidRefresh return nil, ErrInvalidRefresh
} }
return nil, fmt.Errorf("failed to find refresh token: %w", err) return nil, fmt.Errorf("failed to find refresh token: %w", err)
@@ -208,7 +202,7 @@ func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic,
user, err := s.repo.FindByID(ctx, userID) user, err := s.repo.FindByID(ctx, userID)
if err != nil { if err != nil {
if errors.Is(err, db.ErrNoRows) { if errors.Is(err, ErrNoRows) {
return nil, ErrUserNotFound return nil, ErrUserNotFound
} }
return nil, fmt.Errorf("failed to find user: %w", err) return nil, fmt.Errorf("failed to find user: %w", err)
@@ -218,27 +212,20 @@ func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic,
return &public, nil return &public, nil
} }
func (s *Service) ChangePassword( func (s *Service) ChangePassword(ctx context.Context, userID string, req PasswordChangeRequest) error {
ctx context.Context,
userID string,
req PasswordChangeRequest,
) error {
if userID == "" { if userID == "" {
return ErrInvalidUserID return ErrInvalidUserID
} }
user, err := s.repo.FindByID(ctx, userID) user, err := s.repo.FindByID(ctx, userID)
if err != nil { if err != nil {
if errors.Is(err, db.ErrNoRows) { if errors.Is(err, ErrNoRows) {
return ErrUserNotFound return ErrUserNotFound
} }
return fmt.Errorf("failed to find user: %w", err) return fmt.Errorf("failed to find user: %w", err)
} }
if err := bcrypt.CompareHashAndPassword( if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.OldPassword)); err != nil {
[]byte(user.PasswordHash),
[]byte(req.OldPassword),
); err != nil {
return ErrWrongPassword return ErrWrongPassword
} }
@@ -262,18 +249,14 @@ func (s *Service) ChangePassword(
return nil return nil
} }
func (s *Service) UpdateProfile( func (s *Service) UpdateProfile(ctx context.Context, userID string, req UpdateProfileRequest) (*UserPublic, error) {
ctx context.Context,
userID string,
req UpdateProfileRequest,
) (*UserPublic, error) {
if userID == "" { if userID == "" {
return nil, ErrInvalidUserID return nil, ErrInvalidUserID
} }
user, err := s.repo.FindByID(ctx, userID) user, err := s.repo.FindByID(ctx, userID)
if err != nil { if err != nil {
if errors.Is(err, db.ErrNoRows) { if errors.Is(err, ErrNoRows) {
return nil, ErrUserNotFound return nil, ErrUserNotFound
} }
return nil, fmt.Errorf("failed to find user: %w", err) return nil, fmt.Errorf("failed to find user: %w", err)
@@ -289,6 +272,5 @@ func (s *Service) UpdateProfile(
} }
func isPGUniqueViolation(err error) bool { func isPGUniqueViolation(err error) bool {
return err != nil && return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
(strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
} }
+7 -10
View File
@@ -10,11 +10,11 @@ import (
) )
type Config struct { type Config struct {
ServerPort string ServerPort string
DatabaseURL string DatabaseURL string
JWTSecret string JWTSecret string
JWTExpiration time.Duration JWTExpiration time.Duration
JWTRefreshExpiration time.Duration JWTRefreshExpiration time.Duration
} }
func Load() (*Config, error) { func Load() (*Config, error) {
@@ -23,11 +23,8 @@ func Load() (*Config, error) {
} }
cfg := &Config{ cfg := &Config{
ServerPort: getEnv("SERVER_PORT", "8080"), ServerPort: getEnv("SERVER_PORT", "8080"),
DatabaseURL: getEnv( DatabaseURL: getEnv("DATABASE_URL", "postgres://localhost:5432/aegisguard?sslmode=disable"),
"DATABASE_URL",
"postgres://localhost:5432/aegisguard?sslmode=disable",
),
JWTSecret: getEnv("JWT_SECRET", ""), JWTSecret: getEnv("JWT_SECRET", ""),
JWTExpiration: 24 * time.Hour, JWTExpiration: 24 * time.Hour,
JWTRefreshExpiration: 7 * 24 * time.Hour, JWTRefreshExpiration: 7 * 24 * time.Hour,
-5
View File
@@ -1,5 +0,0 @@
package db
import "gorm.io/gorm"
var ErrNoRows = gorm.ErrRecordNotFound
+33 -44
View File
@@ -4,7 +4,6 @@ import (
"errors" "errors"
"log" "log"
"net/http" "net/http"
"strconv"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -17,18 +16,17 @@ func NewHandler(service *Service) *Handler {
return &Handler{service: service} return &Handler{service: service}
} }
// @Summary Создание организации // @Summary Create organization
// @Description Создание новой организации. slug используется в URL и должен быть уникальным. // @Description Create a new organization
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Tags organizations // @Tags organizations
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param request body CreateOrgRequest true "Название и slug организации" // @Param request body CreateOrgRequest true "Organization details"
// @Success 201 {object} OrgResponse "Организация создана" // @Success 201 {object} OrgResponse
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей" // @Failure 400 {object} ErrorResponse
// @Failure 409 {object} ErrorResponse "Slug уже занят" // @Failure 409 {object} ErrorResponse
// @Router /api/v1/organizations [post] // @Router /api/organizations [post]
func (h *Handler) Create(c *gin.Context) { func (h *Handler) Create(c *gin.Context) {
var req CreateOrgRequest var req CreateOrgRequest
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
@@ -50,17 +48,16 @@ func (h *Handler) Create(c *gin.Context) {
c.JSON(http.StatusCreated, OrgResponse{Organization: *org}) c.JSON(http.StatusCreated, OrgResponse{Organization: *org})
} }
// @Summary Получить организацию // @Summary Get organization by ID
// @Description Получение информации об организации по её ID. // @Description Get organization details
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Tags organizations // @Tags organizations
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param id path string true "UUID организации" // @Param id path string true "Organization ID"
// @Success 200 {object} OrgResponse "Данные организации" // @Success 200 {object} OrgResponse
// @Failure 404 {object} ErrorResponse "Организация не найдена" // @Failure 404 {object} ErrorResponse
// @Router /api/v1/organizations/{id} [get] // @Router /api/organizations/{id} [get]
func (h *Handler) GetByID(c *gin.Context) { func (h *Handler) GetByID(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
@@ -78,23 +75,17 @@ func (h *Handler) GetByID(c *gin.Context) {
c.JSON(http.StatusOK, OrgResponse{Organization: *org}) c.JSON(http.StatusOK, OrgResponse{Organization: *org})
} }
// @Summary Список организаций // @Summary List organizations
// @Description Получение списка всех организаций с пагинацией. // @Description Get all organizations
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Tags organizations // @Tags organizations
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param limit query int false "Количество записей на странице (по умолчанию 20)" // @Success 200 {object} OrgListResponse
// @Param offset query int false "Смещение от начала списка (по умолчанию 0)" // @Failure 500 {object} ErrorResponse
// @Success 200 {object} OrgListResponse "Список организаций" // @Router /api/organizations [get]
// @Failure 500 {object} ErrorResponse "Внутренняя ошибка сервера"
// @Router /api/v1/organizations [get]
func (h *Handler) List(c *gin.Context) { func (h *Handler) List(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) resp, err := h.service.List(c.Request.Context())
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
resp, err := h.service.List(c.Request.Context(), limit, offset)
if err != nil { if err != nil {
log.Printf("list orgs error: %v", err) log.Printf("list orgs error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"}) c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
@@ -104,19 +95,18 @@ func (h *Handler) List(c *gin.Context) {
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
} }
// @Summary Обновление организации // @Summary Update organization
// @Description Обновление названия организации. slug изменить нельзя. // @Description Update organization name
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Tags organizations // @Tags organizations
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param id path string true "UUID организации" // @Param id path string true "Organization ID"
// @Param request body UpdateOrgRequest true "Новое название организации" // @Param request body UpdateOrgRequest true "New organization details"
// @Success 200 {object} OrgResponse "Обновлённая организация" // @Success 200 {object} OrgResponse
// @Failure 400 {object} ErrorResponse "Ошибка валидации полей" // @Failure 400 {object} ErrorResponse
// @Failure 404 {object} ErrorResponse "Организация не найдена" // @Failure 404 {object} ErrorResponse
// @Router /api/v1/organizations/{id} [put] // @Router /api/organizations/{id} [put]
func (h *Handler) Update(c *gin.Context) { func (h *Handler) Update(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
@@ -140,17 +130,16 @@ func (h *Handler) Update(c *gin.Context) {
c.JSON(http.StatusOK, OrgResponse{Organization: *org}) c.JSON(http.StatusOK, OrgResponse{Organization: *org})
} }
// @Summary Удаление организации // @Summary Delete organization
// @Description Безвозвратное удаление организации по её ID. // @Description Delete an organization
// @Description **Требуется:** заголовок `Authorization: Bearer <token>`.
// @Tags organizations // @Tags organizations
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Security Bearer // @Security Bearer
// @Param id path string true "UUID организации" // @Param id path string true "Organization ID"
// @Success 200 {object} map[string]string "{"message": "organization deleted"}" // @Success 200 {object} map[string]string
// @Failure 404 {object} ErrorResponse "Организация не найдена" // @Failure 404 {object} ErrorResponse
// @Router /api/v1/organizations/{id} [delete] // @Router /api/organizations/{id} [delete]
func (h *Handler) Delete(c *gin.Context) { func (h *Handler) Delete(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
+6 -8
View File
@@ -3,16 +3,16 @@ package org
import "time" import "time"
type Organization struct { type Organization struct {
ID string `gorm:"type:uuid;primaryKey" json:"id"` ID string `json:"id"`
Name string `gorm:"type:text;not null" json:"name"` Name string `json:"name"`
Slug string `gorm:"type:text;not null;uniqueIndex" json:"slug"` Slug string `json:"slug"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
} }
type CreateOrgRequest struct { type CreateOrgRequest struct {
Name string `json:"name" binding:"required,min=2,max=100" example:"My Corp"` Name string `json:"name" binding:"required,min=2,max=100" example:"My Corp"`
Slug string `json:"slug" binding:"required,min=2,max=50" example:"my-corp"` Slug string `json:"slug" binding:"required,min=2,max=50" example:"my-corp"`
} }
type UpdateOrgRequest struct { type UpdateOrgRequest struct {
@@ -26,8 +26,6 @@ type OrgResponse struct {
type OrgListResponse struct { type OrgListResponse struct {
Organizations []Organization `json:"organizations"` Organizations []Organization `json:"organizations"`
Total int `json:"total"` Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
} }
type ErrorResponse struct { type ErrorResponse struct {
+40 -34
View File
@@ -5,24 +5,18 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"gorm.io/gorm" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
) )
type OrgRepository interface { var ErrNoRows = pgx.ErrNoRows
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)
}
type Repository struct { type Repository struct {
db *gorm.DB pool *pgxpool.Pool
} }
func NewRepository(db *gorm.DB) *Repository { func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{db: db} return &Repository{pool: pool}
} }
func (r *Repository) Create(ctx context.Context, org *Organization) error { func (r *Repository) Create(ctx context.Context, org *Organization) error {
@@ -30,42 +24,54 @@ func (r *Repository) Create(ctx context.Context, org *Organization) error {
now := time.Now().UTC() now := time.Now().UTC()
org.CreatedAt = now org.CreatedAt = now
org.UpdatedAt = now org.UpdatedAt = now
return r.db.WithContext(ctx).Create(org).Error _, 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
} }
func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) { func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) {
var org Organization var org Organization
err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error 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)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &org, nil return &org, nil
} }
func (r *Repository) FindAll(ctx context.Context, limit, offset int) ([]Organization, error) { func (r *Repository) FindAll(ctx context.Context) ([]Organization, error) {
var orgs []Organization rows, err := r.pool.Query(ctx,
err := r.db.WithContext(ctx). `SELECT id, name, slug, created_at, updated_at FROM organizations ORDER BY created_at DESC`,
Order("created_at DESC"). )
Limit(limit). if err != nil {
Offset(offset). return nil, err
Find(&orgs).Error }
return orgs, err defer rows.Close()
}
func (r *Repository) Count(ctx context.Context) (int, error) { var orgs []Organization
var total int64 for rows.Next() {
err := r.db.WithContext(ctx).Model(&Organization{}).Count(&total).Error var org Organization
return int(total), err 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()
} }
func (r *Repository) Update(ctx context.Context, org *Organization) error { func (r *Repository) Update(ctx context.Context, org *Organization) error {
return r.db.WithContext(ctx).Model(org).Update("name", org.Name).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
} }
func (r *Repository) Delete(ctx context.Context, id string) (bool, error) { func (r *Repository) Delete(ctx context.Context, id string) error {
result := r.db.WithContext(ctx).Delete(&Organization{}, "id = ?", id) _, err := r.pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id)
if result.Error != nil { return err
return false, result.Error
}
return result.RowsAffected > 0, nil
} }
+18 -34
View File
@@ -5,8 +5,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db"
) )
var ( var (
@@ -15,10 +13,10 @@ var (
) )
type Service struct { type Service struct {
repo OrgRepository repo *Repository
} }
func NewService(repo OrgRepository) *Service { func NewService(repo *Repository) *Service {
return &Service{repo: repo} return &Service{repo: repo}
} }
@@ -43,7 +41,7 @@ func (s *Service) Create(ctx context.Context, req CreateOrgRequest) (*Organizati
func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error) { func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error) {
org, err := s.repo.FindByID(ctx, id) org, err := s.repo.FindByID(ctx, id)
if err != nil { if err != nil {
if errors.Is(err, db.ErrNoRows) { if errors.Is(err, ErrNoRows) {
return nil, ErrNotFound return nil, ErrNotFound
} }
return nil, fmt.Errorf("failed to find organization: %w", err) return nil, fmt.Errorf("failed to find organization: %w", err)
@@ -51,20 +49,8 @@ func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error)
return org, nil return org, nil
} }
func (s *Service) List(ctx context.Context, limit, offset int) (*OrgListResponse, error) { func (s *Service) List(ctx context.Context) (*OrgListResponse, error) {
if limit <= 0 { orgs, err := s.repo.FindAll(ctx)
limit = 20
}
if offset < 0 {
offset = 0
}
total, err := s.repo.Count(ctx)
if err != nil {
return nil, fmt.Errorf("failed to count organizations: %w", err)
}
orgs, err := s.repo.FindAll(ctx, limit, offset)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to list organizations: %w", err) return nil, fmt.Errorf("failed to list organizations: %w", err)
} }
@@ -73,20 +59,14 @@ func (s *Service) List(ctx context.Context, limit, offset int) (*OrgListResponse
} }
return &OrgListResponse{ return &OrgListResponse{
Organizations: orgs, Organizations: orgs,
Total: total, Total: len(orgs),
Limit: limit,
Offset: offset,
}, nil }, nil
} }
func (s *Service) Update( func (s *Service) Update(ctx context.Context, id string, req UpdateOrgRequest) (*Organization, error) {
ctx context.Context,
id string,
req UpdateOrgRequest,
) (*Organization, error) {
org, err := s.repo.FindByID(ctx, id) org, err := s.repo.FindByID(ctx, id)
if err != nil { if err != nil {
if errors.Is(err, db.ErrNoRows) { if errors.Is(err, ErrNoRows) {
return nil, ErrNotFound return nil, ErrNotFound
} }
return nil, fmt.Errorf("failed to find organization: %w", err) return nil, fmt.Errorf("failed to find organization: %w", err)
@@ -102,17 +82,21 @@ func (s *Service) Update(
} }
func (s *Service) Delete(ctx context.Context, id string) error { func (s *Service) Delete(ctx context.Context, id string) error {
found, err := s.repo.Delete(ctx, id) org, err := s.repo.FindByID(ctx, id)
if err != nil { if err != nil {
if errors.Is(err, ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("failed to find organization: %w", err)
}
if err := s.repo.Delete(ctx, org.ID); err != nil {
return fmt.Errorf("failed to delete organization: %w", err) return fmt.Errorf("failed to delete organization: %w", err)
} }
if !found {
return ErrNotFound
}
return nil return nil
} }
func isUniqueViolation(err error) bool { func isUniqueViolation(err error) bool {
return err != nil && return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
(strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
} }
+1 -3
View File
@@ -1,5 +1,4 @@
-- +goose Up CREATE TABLE IF NOT EXISTS users (
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
username TEXT NOT NULL, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE,
@@ -17,6 +16,5 @@ CREATE TABLE IF NOT EXISTS refresh_tokens (
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON refresh_tokens(expires_at); CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON refresh_tokens(expires_at);
-- +goose Down
DROP TABLE IF EXISTS refresh_tokens; DROP TABLE IF EXISTS refresh_tokens;
DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS users;