refactor: migrate from raw pgx to GORM, unify ErrNoRows, cleanup auth
This commit is contained in:
@@ -1,108 +0,0 @@
|
||||
# JWT Аутентификация — AegisGuard API
|
||||
|
||||
## Схема работы
|
||||
|
||||
- **access_token** — JWT, живёт 24 часа. Передаётся в заголовке `Authorization: Bearer`.
|
||||
- **refresh_token** — случайная строка, хранится в БД в виде хеша. Используется **один раз** (ротация): при запросе новой пары старый токен удаляется.
|
||||
- Регистрация сразу возвращает токены — отдельный логин не нужен.
|
||||
|
||||
## Эндпоинты
|
||||
|
||||
### POST /api/auth/register
|
||||
|
||||
Создание аккаунта.
|
||||
|
||||
```
|
||||
Запрос:
|
||||
{ "username": "john", "email": "john@example.com", "password": "Secret123" }
|
||||
|
||||
Ответ 201:
|
||||
{
|
||||
"token": "eyJhbGciOiJIUzI1NiIs...",
|
||||
"refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=",
|
||||
"user": {
|
||||
"id": "uuid",
|
||||
"username": "john",
|
||||
"email": "john@example.com",
|
||||
"created_at": "2026-06-13T12:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `username` — 3–30 символов
|
||||
- `email` — валидный email
|
||||
- `password` — минимум 8 символов, обязательно заглавная + строчная + цифра
|
||||
|
||||
Ошибки: `400` (валидация), `409` (email уже занят).
|
||||
|
||||
### POST /api/auth/login
|
||||
|
||||
```
|
||||
Запрос:
|
||||
{ "email": "john@example.com", "password": "Secret123" }
|
||||
|
||||
Ответ 200:
|
||||
{ "token": "...", "refresh_token": "...", "user": { ... } }
|
||||
```
|
||||
|
||||
Rate limit: 10 попыток в минуту с одного IP (`429 Too Many Requests`).
|
||||
|
||||
### POST /api/auth/refresh
|
||||
|
||||
Обновить токены по refresh_token. Старый удаляется, выдаётся новая пара.
|
||||
|
||||
```
|
||||
Запрос:
|
||||
{ "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=" }
|
||||
|
||||
Ответ 200:
|
||||
{ "token": "...", "refresh_token": "...", "user": { ... } }
|
||||
```
|
||||
|
||||
### POST /api/auth/logout
|
||||
|
||||
Удалить refresh_token из БД.
|
||||
|
||||
```
|
||||
Запрос:
|
||||
{ "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=" }
|
||||
|
||||
Ответ 200:
|
||||
{ "message": "logged out successfully" }
|
||||
```
|
||||
|
||||
## Заголовок авторизации
|
||||
|
||||
```
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
## Формат JWT
|
||||
|
||||
```json
|
||||
{
|
||||
"user_id": "uuid",
|
||||
"email": "john@example.com",
|
||||
"sub": "uuid",
|
||||
"exp": 1718000000,
|
||||
"iat": 1717913600
|
||||
}
|
||||
```
|
||||
|
||||
- `user_id` — UUID пользователя
|
||||
- `email` — Email пользователя
|
||||
- `sub` — то же, что `user_id`
|
||||
- `exp` — Unix-timestamp истечения токена
|
||||
- `iat` — Unix-timestamp выпуска токена
|
||||
|
||||
## Формат ошибок
|
||||
|
||||
```json
|
||||
{ "error": "описание" }
|
||||
```
|
||||
|
||||
- `400` — ошибка валидации
|
||||
- `401` — неверный email/пароль, токен протух или невалиден
|
||||
- `409` — email уже зарегистрирован
|
||||
- `429` — превышен лимит попыток логина
|
||||
- `500` — внутренняя ошибка сервера
|
||||
+10
-6
@@ -29,12 +29,16 @@ func GenerateToken(userID, email string, secret []byte, expiration time.Duration
|
||||
}
|
||||
|
||||
func ValidateToken(tokenString string, secret []byte) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return secret, nil
|
||||
})
|
||||
token, err := jwt.ParseWithClaims(
|
||||
tokenString,
|
||||
&Claims{},
|
||||
func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return secret, nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+22
-38
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/api"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -16,8 +17,8 @@ func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// @Summary Register epta
|
||||
// @Description Create user account with username, email, password
|
||||
// @Summary Register
|
||||
// @Description Создание учетной записи пользователя с полями username, email, password
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -52,7 +53,7 @@ func (h *Handler) Register(c *gin.Context) {
|
||||
}
|
||||
|
||||
// @Summary Login
|
||||
// @Description Authenticate user with email and password, returns JWT token
|
||||
// @Description Аунтефикация пользователя с помощью email и password, возвращает JWT token
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -82,8 +83,8 @@ func (h *Handler) Login(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// @Summary Refresh epta token
|
||||
// @Description Get a new access token using a refresh token
|
||||
// @Summary Refresh token
|
||||
// @Description Получение ново
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -113,8 +114,8 @@ func (h *Handler) Refresh(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// @Summary Logout epta
|
||||
// @Description Invalidate a refresh token (logout)
|
||||
// @Summary Logout
|
||||
// @Description Аннулирует refresh token
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -143,8 +144,8 @@ func (h *Handler) Logout(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"})
|
||||
}
|
||||
|
||||
// @Summary Get epta current user
|
||||
// @Description Get authenticated user's profile
|
||||
// @Summary Get current user
|
||||
// @Description Получить профиль авторизованного пользователя
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -153,18 +154,12 @@ func (h *Handler) Logout(c *gin.Context) {
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/me [get]
|
||||
func (h *Handler) Me(c *gin.Context) {
|
||||
rawUserID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
userID := api.GetUserID(c)
|
||||
if userID == "" {
|
||||
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := rawUserID.(string)
|
||||
if !ok {
|
||||
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.service.GetUserByID(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrInvalidUserID) {
|
||||
@@ -179,8 +174,8 @@ func (h *Handler) Me(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, UserResponse{User: *user})
|
||||
}
|
||||
|
||||
// @Summary Change epta password
|
||||
// @Description Change current user's password
|
||||
// @Summary Change password
|
||||
// @Description Изменить текущий password пользователя
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -191,18 +186,12 @@ func (h *Handler) Me(c *gin.Context) {
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/password [put]
|
||||
func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
rawUserID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
userID := api.GetUserID(c)
|
||||
if userID == "" {
|
||||
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := rawUserID.(string)
|
||||
if !ok {
|
||||
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
|
||||
return
|
||||
}
|
||||
|
||||
var req PasswordChangeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
|
||||
@@ -210,7 +199,8 @@ func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
}
|
||||
|
||||
if err := h.service.ChangePassword(c.Request.Context(), userID, req); err != nil {
|
||||
if errors.Is(err, ErrWrongPassword) || errors.Is(err, ErrSamePassword) || errors.Is(err, ErrWeakPassword) {
|
||||
if errors.Is(err, ErrWrongPassword) || errors.Is(err, ErrSamePassword) ||
|
||||
errors.Is(err, ErrWeakPassword) {
|
||||
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -226,8 +216,8 @@ func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "password changed successfully"})
|
||||
}
|
||||
|
||||
// @Summary Update epta profile
|
||||
// @Description Update current user's username
|
||||
// @Summary Update profile
|
||||
// @Description Обновить username текущего пользователя
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -238,18 +228,12 @@ func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/me [put]
|
||||
func (h *Handler) UpdateProfile(c *gin.Context) {
|
||||
rawUserID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
userID := api.GetUserID(c)
|
||||
if userID == "" {
|
||||
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := rawUserID.(string)
|
||||
if !ok {
|
||||
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "invalid user ID in context"})
|
||||
return
|
||||
}
|
||||
|
||||
var req UpdateProfileRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
|
||||
|
||||
@@ -11,19 +11,28 @@ func AuthMiddleware(jwtSecret []byte) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "authorization header required"})
|
||||
c.AbortWithStatusJSON(
|
||||
http.StatusUnauthorized,
|
||||
ErrorResponse{Error: "authorization header required"},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid authorization header format"})
|
||||
c.AbortWithStatusJSON(
|
||||
http.StatusUnauthorized,
|
||||
ErrorResponse{Error: "invalid authorization header format"},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := ValidateToken(parts[1], jwtSecret)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid or expired token"})
|
||||
c.AbortWithStatusJSON(
|
||||
http.StatusUnauthorized,
|
||||
ErrorResponse{Error: "invalid or expired token"},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+18
-16
@@ -5,26 +5,26 @@ import (
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
PasswordHash string `json:"-"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID string `gorm:"type:uuid;primaryKey" json:"id"`
|
||||
Username string `gorm:"type:text;not null" json:"username"`
|
||||
Email string `gorm:"type:text;not null;uniqueIndex" json:"email"`
|
||||
PasswordHash string `gorm:"column:password_hash;type:text;not null" json:"-"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
}
|
||||
|
||||
type RegisterRequest struct {
|
||||
Username string `json:"username" binding:"required,min=3,max=30" example:"john"`
|
||||
Email string `json:"email" binding:"required,email" example:"john@example.com"`
|
||||
Password string `json:"password" binding:"required,min=8" example:"Secret123!"`
|
||||
Email string `json:"email" binding:"required,email" example:"john@example.com"`
|
||||
Password string `json:"password" binding:"required,min=8" example:"Secret123!"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email" binding:"required,email" example:"john@example.com"`
|
||||
Password string `json:"password" binding:"required" example:"secret123"`
|
||||
Email string `json:"email" binding:"required,email" example:"john@example.com"`
|
||||
Password string `json:"password" binding:"required" example:"secret123"`
|
||||
}
|
||||
|
||||
type AuthResponse struct {
|
||||
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."`
|
||||
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."`
|
||||
RefreshToken string `json:"refresh_token" example:"dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4="`
|
||||
User UserPublic `json:"user"`
|
||||
}
|
||||
@@ -38,13 +38,15 @@ type LogoutRequest struct {
|
||||
}
|
||||
|
||||
type RefreshTokenDoc struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
TokenHash string `json:"token_hash"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID string `gorm:"type:uuid;primaryKey" json:"id"`
|
||||
UserID string `gorm:"column:user_id;type:uuid;not null;index" json:"user_id"`
|
||||
TokenHash string `gorm:"column:token_hash;type:text;not null;uniqueIndex" json:"token_hash"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at;type:timestamptz;not null" json:"expires_at"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
}
|
||||
|
||||
func (RefreshTokenDoc) TableName() string { return "refresh_tokens" }
|
||||
|
||||
type UserPublic struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
@@ -66,7 +68,7 @@ type UserResponse struct {
|
||||
}
|
||||
|
||||
type PasswordChangeRequest struct {
|
||||
OldPassword string `json:"old_password" binding:"required" example:"Secret123!"`
|
||||
OldPassword string `json:"old_password" binding:"required" example:"Secret123!"`
|
||||
NewPassword string `json:"new_password" binding:"required,min=8" example:"NewSecret456!"`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type visitor struct {
|
||||
count int
|
||||
lastSeen time.Time
|
||||
}
|
||||
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
visitors map[string]*visitor
|
||||
rate int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func NewRateLimiter(rate int, window time.Duration) *RateLimiter {
|
||||
rl := &RateLimiter{
|
||||
visitors: make(map[string]*visitor),
|
||||
rate: rate,
|
||||
window: window,
|
||||
}
|
||||
|
||||
go rl.cleanup()
|
||||
return rl
|
||||
}
|
||||
|
||||
func (rl *RateLimiter) cleanup() {
|
||||
ticker := time.NewTicker(10 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
rl.mu.Lock()
|
||||
now := time.Now()
|
||||
for ip, v := range rl.visitors {
|
||||
if now.Sub(v.lastSeen) > rl.window*2 {
|
||||
delete(rl.visitors, ip)
|
||||
}
|
||||
}
|
||||
rl.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (rl *RateLimiter) Middleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
|
||||
rl.mu.Lock()
|
||||
v, exists := rl.visitors[ip]
|
||||
now := time.Now()
|
||||
|
||||
if !exists || now.Sub(v.lastSeen) > rl.window {
|
||||
rl.visitors[ip] = &visitor{count: 1, lastSeen: now}
|
||||
rl.mu.Unlock()
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
v.count++
|
||||
v.lastSeen = now
|
||||
|
||||
if v.count > rl.rate {
|
||||
rl.mu.Unlock()
|
||||
c.JSON(http.StatusTooManyRequests, ErrorResponse{Error: "too many requests, try again later"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
rl.mu.Unlock()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
+49
-48
@@ -5,33 +5,39 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
pool *pgxpool.Pool
|
||||
type UserRepository interface {
|
||||
CreateUser(ctx context.Context, user *User) error
|
||||
FindByEmail(ctx context.Context, email string) (*User, error)
|
||||
FindByID(ctx context.Context, id string) (*User, error)
|
||||
CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error
|
||||
FindRefreshTokenByHash(ctx context.Context, hash string) (*RefreshTokenDoc, error)
|
||||
DeleteRefreshToken(ctx context.Context, id string) error
|
||||
DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error)
|
||||
UpdateUserUsername(ctx context.Context, id, username string) error
|
||||
UpdateUserPassword(ctx context.Context, id, passwordHash string) error
|
||||
DeleteExpiredRefreshTokens(ctx context.Context) error
|
||||
}
|
||||
|
||||
func NewRepository(pool *pgxpool.Pool) *Repository {
|
||||
return &Repository{pool: pool}
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
func (r *Repository) CreateUser(ctx context.Context, user *User) error {
|
||||
user.ID = uuid.New().String()
|
||||
user.CreatedAt = time.Now().UTC()
|
||||
_, err := r.pool.Exec(ctx,
|
||||
`INSERT INTO users (id, username, email, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
user.ID, user.Username, user.Email, user.PasswordHash, user.CreatedAt,
|
||||
)
|
||||
return err
|
||||
return r.db.WithContext(ctx).Create(user).Error
|
||||
}
|
||||
|
||||
func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) {
|
||||
var user User
|
||||
err := r.pool.QueryRow(ctx,
|
||||
`SELECT id, username, email, password_hash, created_at FROM users WHERE email = $1`, email,
|
||||
).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt)
|
||||
err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -40,9 +46,7 @@ func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, erro
|
||||
|
||||
func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) {
|
||||
var user User
|
||||
err := r.pool.QueryRow(ctx,
|
||||
`SELECT id, username, email, password_hash, created_at FROM users WHERE id = $1`, id,
|
||||
).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt)
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&user).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -52,18 +56,18 @@ func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) {
|
||||
func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error {
|
||||
doc.ID = uuid.New().String()
|
||||
doc.CreatedAt = time.Now().UTC()
|
||||
_, err := r.pool.Exec(ctx,
|
||||
`INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
doc.ID, doc.UserID, doc.TokenHash, doc.ExpiresAt, doc.CreatedAt,
|
||||
)
|
||||
return err
|
||||
return r.db.WithContext(ctx).Create(doc).Error
|
||||
}
|
||||
|
||||
func (r *Repository) FindRefreshTokenByHash(ctx context.Context, hash string) (*RefreshTokenDoc, error) {
|
||||
func (r *Repository) FindRefreshTokenByHash(
|
||||
ctx context.Context,
|
||||
hash string,
|
||||
) (*RefreshTokenDoc, error) {
|
||||
var doc RefreshTokenDoc
|
||||
err := r.pool.QueryRow(ctx,
|
||||
`SELECT id, user_id, token_hash, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1 AND expires_at > NOW()`, hash,
|
||||
).Scan(&doc.ID, &doc.UserID, &doc.TokenHash, &doc.ExpiresAt, &doc.CreatedAt)
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("token_hash = ? AND expires_at > NOW()", hash).
|
||||
First(&doc).
|
||||
Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,31 +75,28 @@ func (r *Repository) FindRefreshTokenByHash(ctx context.Context, hash string) (*
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error {
|
||||
_, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error {
|
||||
_, err := r.pool.Exec(ctx, `UPDATE users SET username = $1 WHERE id = $2`, username, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error {
|
||||
_, err := r.pool.Exec(ctx, `UPDATE users SET password_hash = $1 WHERE id = $2`, passwordHash, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error {
|
||||
_, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE expires_at <= NOW()`)
|
||||
return err
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&RefreshTokenDoc{}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error) {
|
||||
tag, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE token_hash = $1`, hash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
result := r.db.WithContext(ctx).Where("token_hash = ?", hash).Delete(&RefreshTokenDoc{})
|
||||
if result.Error != nil {
|
||||
return false, result.Error
|
||||
}
|
||||
return tag.RowsAffected() > 0, nil
|
||||
return result.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
var ErrNoRows = pgx.ErrNoRows
|
||||
func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error {
|
||||
return r.db.WithContext(ctx).Model(&User{}).Where("id = ?", id).
|
||||
Update("username", username).Error
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error {
|
||||
return r.db.WithContext(ctx).Model(&User{}).Where("id = ?", id).
|
||||
Update("password_hash", passwordHash).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("expires_at <= NOW()").Delete(&RefreshTokenDoc{}).Error
|
||||
}
|
||||
|
||||
+41
-23
@@ -11,30 +11,33 @@ import (
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrEmailExists = errors.New("email already registered")
|
||||
ErrInvalidCreds = errors.New("invalid email or password")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrInvalidUserID = errors.New("invalid user ID")
|
||||
ErrInvalidRefresh = errors.New("invalid refresh token")
|
||||
ErrRefreshExpired = errors.New("refresh token expired")
|
||||
ErrLogoutInvalid = errors.New("refresh token not found or already used")
|
||||
ErrWrongPassword = errors.New("current password is incorrect")
|
||||
ErrWeakPassword = errors.New("password must be at least 8 characters with uppercase, lowercase, and digit")
|
||||
ErrSamePassword = errors.New("new password must differ from current password")
|
||||
ErrEmailExists = errors.New("email already registered")
|
||||
ErrInvalidCreds = errors.New("invalid email or password")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrInvalidUserID = errors.New("invalid user ID")
|
||||
ErrInvalidRefresh = errors.New("invalid refresh token")
|
||||
ErrRefreshExpired = errors.New("refresh token expired")
|
||||
ErrLogoutInvalid = errors.New("refresh token not found or already used")
|
||||
ErrWrongPassword = errors.New("current password is incorrect")
|
||||
ErrWeakPassword = errors.New(
|
||||
"password must be at least 8 characters with uppercase, lowercase, and digit",
|
||||
)
|
||||
ErrSamePassword = errors.New("new password must differ from current password")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
repo UserRepository
|
||||
jwtSecret []byte
|
||||
jwtExp time.Duration
|
||||
refreshExp time.Duration
|
||||
}
|
||||
|
||||
func NewService(repo *Repository, jwtSecret string, jwtExp, refreshExp time.Duration) *Service {
|
||||
func NewService(repo UserRepository, jwtSecret string, jwtExp, refreshExp time.Duration) *Service {
|
||||
return &Service{
|
||||
repo: repo,
|
||||
jwtSecret: []byte(jwtSecret),
|
||||
@@ -113,7 +116,7 @@ func (s *Service) Register(ctx context.Context, req RegisterRequest) (*AuthRespo
|
||||
req.Email = strings.ToLower(req.Email)
|
||||
|
||||
existing, err := s.repo.FindByEmail(ctx, req.Email)
|
||||
if err != nil && !errors.Is(err, ErrNoRows) {
|
||||
if err != nil && !errors.Is(err, db.ErrNoRows) {
|
||||
return nil, fmt.Errorf("failed to check existing user: %w", err)
|
||||
}
|
||||
if existing != nil {
|
||||
@@ -145,13 +148,16 @@ func (s *Service) Login(ctx context.Context, req LoginRequest) (*AuthResponse, e
|
||||
req.Email = strings.ToLower(req.Email)
|
||||
user, err := s.repo.FindByEmail(ctx, req.Email)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoRows) {
|
||||
if errors.Is(err, db.ErrNoRows) {
|
||||
return nil, ErrInvalidCreds
|
||||
}
|
||||
return nil, fmt.Errorf("failed to find user: %w", err)
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
|
||||
if err := bcrypt.CompareHashAndPassword(
|
||||
[]byte(user.PasswordHash),
|
||||
[]byte(req.Password),
|
||||
); err != nil {
|
||||
return nil, ErrInvalidCreds
|
||||
}
|
||||
|
||||
@@ -163,7 +169,7 @@ func (s *Service) Refresh(ctx context.Context, rawRefresh string) (*AuthResponse
|
||||
|
||||
doc, err := s.repo.FindRefreshTokenByHash(ctx, hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoRows) {
|
||||
if errors.Is(err, db.ErrNoRows) {
|
||||
return nil, ErrInvalidRefresh
|
||||
}
|
||||
return nil, fmt.Errorf("failed to find refresh token: %w", err)
|
||||
@@ -202,7 +208,7 @@ func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic,
|
||||
|
||||
user, err := s.repo.FindByID(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoRows) {
|
||||
if errors.Is(err, db.ErrNoRows) {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to find user: %w", err)
|
||||
@@ -212,20 +218,27 @@ func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic,
|
||||
return &public, nil
|
||||
}
|
||||
|
||||
func (s *Service) ChangePassword(ctx context.Context, userID string, req PasswordChangeRequest) error {
|
||||
func (s *Service) ChangePassword(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
req PasswordChangeRequest,
|
||||
) error {
|
||||
if userID == "" {
|
||||
return ErrInvalidUserID
|
||||
}
|
||||
|
||||
user, err := s.repo.FindByID(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoRows) {
|
||||
if errors.Is(err, db.ErrNoRows) {
|
||||
return ErrUserNotFound
|
||||
}
|
||||
return fmt.Errorf("failed to find user: %w", err)
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.OldPassword)); err != nil {
|
||||
if err := bcrypt.CompareHashAndPassword(
|
||||
[]byte(user.PasswordHash),
|
||||
[]byte(req.OldPassword),
|
||||
); err != nil {
|
||||
return ErrWrongPassword
|
||||
}
|
||||
|
||||
@@ -249,14 +262,18 @@ func (s *Service) ChangePassword(ctx context.Context, userID string, req Passwor
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateProfile(ctx context.Context, userID string, req UpdateProfileRequest) (*UserPublic, error) {
|
||||
func (s *Service) UpdateProfile(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
req UpdateProfileRequest,
|
||||
) (*UserPublic, error) {
|
||||
if userID == "" {
|
||||
return nil, ErrInvalidUserID
|
||||
}
|
||||
|
||||
user, err := s.repo.FindByID(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoRows) {
|
||||
if errors.Is(err, db.ErrNoRows) {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to find user: %w", err)
|
||||
@@ -272,5 +289,6 @@ func (s *Service) UpdateProfile(ctx context.Context, userID string, req UpdatePr
|
||||
}
|
||||
|
||||
func isPGUniqueViolation(err error) bool {
|
||||
return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
|
||||
return err != nil &&
|
||||
(strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user