added some govno to postgres
This commit is contained in:
@@ -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` — 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` — внутренняя ошибка сервера
|
||||
+101
-6
@@ -16,13 +16,13 @@ func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// @Summary Epta registration
|
||||
// @Summary Register epta
|
||||
// @Description Create user account with username, email, password
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body RegisterRequest true "Registration details"
|
||||
// @Success 201 {object} UserResponse
|
||||
// @Success 201 {object} AuthResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 409 {object} ErrorResponse
|
||||
// @Router /api/auth/register [post]
|
||||
@@ -33,21 +33,25 @@ func (h *Handler) Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.service.Register(c.Request.Context(), req)
|
||||
resp, err := h.service.Register(c.Request.Context(), req)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrEmailExists) {
|
||||
c.JSON(http.StatusConflict, ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrWeakPassword) {
|
||||
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
log.Printf("register error: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, UserResponse{User: *user})
|
||||
c.JSON(http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
// @Summary Epta login
|
||||
// @Summary Login
|
||||
// @Description Authenticate user with email and password, returns JWT token
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
@@ -139,7 +143,7 @@ func (h *Handler) Logout(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"})
|
||||
}
|
||||
|
||||
// @Summary Epta get current user
|
||||
// @Summary Get epta current user
|
||||
// @Description Get authenticated user's profile
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
@@ -174,3 +178,94 @@ func (h *Handler) Me(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, UserResponse{User: *user})
|
||||
}
|
||||
|
||||
// @Summary Change epta password
|
||||
// @Description Change current user's password
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body PasswordChangeRequest true "Password change details"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/password [put]
|
||||
func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
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()})
|
||||
return
|
||||
}
|
||||
|
||||
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) {
|
||||
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrInvalidUserID) {
|
||||
c.JSON(http.StatusNotFound, ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
log.Printf("change password error: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "password changed successfully"})
|
||||
}
|
||||
|
||||
// @Summary Update profile
|
||||
// @Description Update current user's username
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body UpdateProfileRequest true "Profile update"
|
||||
// @Success 200 {object} UserResponse
|
||||
// @Failure 400 {object} ErrorResponse
|
||||
// @Failure 401 {object} ErrorResponse
|
||||
// @Router /api/auth/me [put]
|
||||
func (h *Handler) UpdateProfile(c *gin.Context) {
|
||||
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()})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.service.UpdateProfile(c.Request.Context(), userID, req)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrInvalidUserID) {
|
||||
c.JSON(http.StatusNotFound, ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
log.Printf("update profile error: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, UserResponse{User: *user})
|
||||
}
|
||||
|
||||
+10
-1
@@ -15,7 +15,7 @@ type User struct {
|
||||
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=6" example:"secret123"`
|
||||
Password string `json:"password" binding:"required,min=8" example:"Secret123!"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
@@ -65,6 +65,15 @@ type UserResponse struct {
|
||||
User UserPublic `json:"user"`
|
||||
}
|
||||
|
||||
type PasswordChangeRequest struct {
|
||||
OldPassword string `json:"old_password" binding:"required" example:"Secret123!"`
|
||||
NewPassword string `json:"new_password" binding:"required,min=8" example:"NewSecret456!"`
|
||||
}
|
||||
|
||||
type UpdateProfileRequest struct {
|
||||
Username string `json:"username" binding:"required,min=3,max=30" example:"john_updated"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error" example:"invalid email or password"`
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
+16
-29
@@ -17,30 +17,6 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
|
||||
return &Repository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *Repository) Migrate(ctx context.Context) error {
|
||||
schema := `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||
id UUID PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON refresh_tokens(expires_at);
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, schema)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) CreateUser(ctx context.Context, user *User) error {
|
||||
user.ID = uuid.New().String()
|
||||
user.CreatedAt = time.Now().UTC()
|
||||
@@ -86,7 +62,7 @@ func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDo
|
||||
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`, hash,
|
||||
`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
|
||||
@@ -99,6 +75,21 @@ func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error {
|
||||
_, err := r.pool.Exec(ctx, `UPDATE users SET username = $1 WHERE id = $2`, username, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error {
|
||||
_, err := r.pool.Exec(ctx, `UPDATE users SET password_hash = $1 WHERE id = $2`, passwordHash, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error {
|
||||
_, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE expires_at <= NOW()`)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error) {
|
||||
tag, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE token_hash = $1`, hash)
|
||||
if err != nil {
|
||||
@@ -107,8 +98,4 @@ func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string)
|
||||
return tag.RowsAffected() > 0, nil
|
||||
}
|
||||
|
||||
func (r *Repository) EnsureIndexes(ctx context.Context) error {
|
||||
return r.Migrate(ctx)
|
||||
}
|
||||
|
||||
var ErrNoRows = pgx.ErrNoRows
|
||||
|
||||
+105
-18
@@ -7,21 +7,24 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"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")
|
||||
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 {
|
||||
@@ -53,6 +56,27 @@ func generateRandomToken() (string, error) {
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func validatePasswordStrength(password string) error {
|
||||
if len(password) < 8 {
|
||||
return ErrWeakPassword
|
||||
}
|
||||
var hasUpper, hasLower, hasDigit bool
|
||||
for _, ch := range password {
|
||||
switch {
|
||||
case unicode.IsUpper(ch):
|
||||
hasUpper = true
|
||||
case unicode.IsLower(ch):
|
||||
hasLower = true
|
||||
case unicode.IsDigit(ch):
|
||||
hasDigit = true
|
||||
}
|
||||
}
|
||||
if !hasUpper || !hasLower || !hasDigit {
|
||||
return ErrWeakPassword
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) issueTokenPair(ctx context.Context, user *User) (*AuthResponse, error) {
|
||||
accessToken, err := GenerateToken(user.ID, user.Email, s.jwtSecret, s.jwtExp)
|
||||
if err != nil {
|
||||
@@ -81,8 +105,13 @@ func (s *Service) issueTokenPair(ctx context.Context, user *User) (*AuthResponse
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Register(ctx context.Context, req RegisterRequest) (*UserPublic, error) {
|
||||
func (s *Service) Register(ctx context.Context, req RegisterRequest) (*AuthResponse, error) {
|
||||
if err := validatePasswordStrength(req.Password); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Email = strings.ToLower(req.Email)
|
||||
|
||||
existing, err := s.repo.FindByEmail(ctx, req.Email)
|
||||
if err != nil && !errors.Is(err, ErrNoRows) {
|
||||
return nil, fmt.Errorf("failed to check existing user: %w", err)
|
||||
@@ -103,11 +132,13 @@ func (s *Service) Register(ctx context.Context, req RegisterRequest) (*UserPubli
|
||||
}
|
||||
|
||||
if err := s.repo.CreateUser(ctx, user); err != nil {
|
||||
if isPGUniqueViolation(err) {
|
||||
return nil, ErrEmailExists
|
||||
}
|
||||
return nil, fmt.Errorf("failed to create user: %w", err)
|
||||
}
|
||||
|
||||
public := NewUserPublic(user)
|
||||
return &public, nil
|
||||
return s.issueTokenPair(ctx, user)
|
||||
}
|
||||
|
||||
func (s *Service) Login(ctx context.Context, req LoginRequest) (*AuthResponse, error) {
|
||||
@@ -138,13 +169,6 @@ func (s *Service) Refresh(ctx context.Context, rawRefresh string) (*AuthResponse
|
||||
return nil, fmt.Errorf("failed to find refresh token: %w", err)
|
||||
}
|
||||
|
||||
if time.Now().UTC().After(doc.ExpiresAt) {
|
||||
if err := s.repo.DeleteRefreshToken(ctx, doc.ID); err != nil {
|
||||
log.Printf("failed to cleanup expired refresh token: %v", err)
|
||||
}
|
||||
return nil, ErrRefreshExpired
|
||||
}
|
||||
|
||||
if err := s.repo.DeleteRefreshToken(ctx, doc.ID); err != nil {
|
||||
return nil, fmt.Errorf("failed to delete old refresh token: %w", err)
|
||||
}
|
||||
@@ -187,3 +211,66 @@ func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic,
|
||||
public := NewUserPublic(user)
|
||||
return &public, nil
|
||||
}
|
||||
|
||||
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) {
|
||||
return ErrUserNotFound
|
||||
}
|
||||
return fmt.Errorf("failed to find user: %w", err)
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.OldPassword)); err != nil {
|
||||
return ErrWrongPassword
|
||||
}
|
||||
|
||||
if req.OldPassword == req.NewPassword {
|
||||
return ErrSamePassword
|
||||
}
|
||||
|
||||
if err := validatePasswordStrength(req.NewPassword); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to hash password: %w", err)
|
||||
}
|
||||
|
||||
if err := s.repo.UpdateUserPassword(ctx, userID, string(hash)); err != nil {
|
||||
return fmt.Errorf("failed to update password: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
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) {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to find user: %w", err)
|
||||
}
|
||||
|
||||
if err := s.repo.UpdateUserUsername(ctx, userID, req.Username); err != nil {
|
||||
return nil, fmt.Errorf("failed to update username: %w", err)
|
||||
}
|
||||
|
||||
user.Username = req.Username
|
||||
public := NewUserPublic(user)
|
||||
return &public, nil
|
||||
}
|
||||
|
||||
func isPGUniqueViolation(err error) bool {
|
||||
return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user