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