changed arhitecture

This commit is contained in:
2026-07-15 18:08:19 +05:00
parent 7e3a5cebcc
commit 585ba63bc2
95 changed files with 4985 additions and 1360 deletions

View File

@@ -0,0 +1,83 @@
package db
import (
"context"
"errors"
"online-back/internal/identity/auth"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Repository {
return &repository{
client: client,
logger: logger,
}
}
const (
loginQuery = `SELECT id, password FROM users WHERE email = $1`
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at
FROM users WHERE id = $1`
)
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
var result auth.UserCredentials
err := r.client.QueryRow(ctx, loginQuery, dto.Email).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredentials, error) {
var result auth.UserCredentials
err := r.client.QueryRow(ctx, userByIDQuery, id).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
&profile.LastName,
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
)
return profile, err
}
const updateProfileQuery = `
UPDATE users SET
name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $6
RETURNING id, name, first_name, last_name, phone, avatar, created_at`
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, updateProfileQuery,
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
).Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
&profile.LastName,
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return auth.UserProfileDTO{}, err
}
return profile, err
}

35
internal/identity/auth/dto.go Executable file
View File

@@ -0,0 +1,35 @@
package auth
import "time"
type LoginDTO struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}
type RefreshTokenDTO struct {
RefreshToken string `json:"refreshToken" binding:"required"`
}
type UserProfileDTO struct {
Id int `json:"id"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
CreatedAt time.Time `json:"createdAt"`
}
type UpdateProfileDTO struct {
Name string `json:"name" binding:"required"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
}
type UserCredentials struct {
Id int
Password string
}

186
internal/identity/auth/handler.go Executable file
View File

@@ -0,0 +1,186 @@
package auth
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const (
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
)
type handler struct {
logger *logging.Logger
repository Repository
service *Service
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository, service: NewService(repository)}
}
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.refreshToken)
protected := router.Group("", appresult.JwtTokenCheck())
protected.GET(profileURL, h.getProfile)
protected.PUT(profileURL, h.updateProfile)
}
// login godoc
// @Summary Login
// @Description Authenticates a user by email and password
// @Tags auth
// @Accept json
// @Produce json
// @Param body body LoginDTO true "Login payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /login [post]
func (h *handler) login(c *gin.Context) {
var dto LoginDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
tokenPair, err := h.service.Login(c.Request.Context(), dto)
if errors.Is(err, ErrInvalidCredentials) {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// refreshToken godoc
// @Summary Refresh tokens
// @Description Issues a new access and refresh token pair
// @Tags auth
// @Accept json
// @Produce json
// @Param body body RefreshTokenDTO true "Refresh token payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /token [post]
func (h *handler) refreshToken(c *gin.Context) {
var dto RefreshTokenDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
tokenPair, err := h.service.RefreshToken(c.Request.Context(), dto.RefreshToken)
if errors.Is(err, ErrInvalidCredentials) {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// getProfile godoc
// @Summary Get profile
// @Description Returns the authenticated user's profile
// @Tags auth
// @Produce json
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /profile [get]
func (h *handler) getProfile(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
profile, err := h.repository.GetProfile(c.Request.Context(), userID)
if err != nil {
h.logger.Errorf("get profile failed: %v", err)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
}
// updateProfile godoc
// @Summary Update profile
// @Description Updates the authenticated user's profile
// @Tags auth
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body UpdateProfileDTO true "Profile payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /profile [put]
func (h *handler) updateProfile(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
var dto UpdateProfileDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
profile, err := h.repository.UpdateProfile(c.Request.Context(), userID, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update profile failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
}
func currentUserID(c *gin.Context) (int, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
switch id := rawID.(type) {
case int:
return id, id > 0
case string:
parsed, err := strconv.Atoi(id)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}

View File

@@ -0,0 +1,55 @@
package auth
import (
"context"
"errors"
"online-back/pkg/utils"
"golang.org/x/crypto/bcrypt"
)
// ErrInvalidCredentials covers both "no such user" and "wrong password" for
// login, and any refresh-token validation failure — callers map it to 401.
// Any other error from these methods (token generation failure) maps to 400.
var ErrInvalidCredentials = errors.New("invalid credentials")
type Service struct {
repository Repository
}
func NewService(repository Repository) *Service {
return &Service{repository: repository}
}
func (s *Service) Login(ctx context.Context, dto LoginDTO) (map[string]string, error) {
user, err := s.repository.Login(ctx, dto)
if err != nil {
return nil, ErrInvalidCredentials
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
return nil, ErrInvalidCredentials
}
return utils.GenerateTokenPair(user.Id)
}
func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (map[string]string, error) {
claims, err := utils.ParseRefreshToken(refreshToken)
if err != nil {
return nil, ErrInvalidCredentials
}
id, ok := utils.ClaimID(claims)
if !ok {
return nil, ErrInvalidCredentials
}
user, err := s.repository.GetUserByID(ctx, id)
if err != nil || user.Id != id {
return nil, ErrInvalidCredentials
}
return utils.GenerateTokenPair(id)
}

View File

@@ -0,0 +1,10 @@
package auth
import "context"
type Repository interface {
Login(ctx context.Context, dto LoginDTO) (UserCredentials, error)
GetUserByID(ctx context.Context, id int) (UserCredentials, error)
GetProfile(ctx context.Context, id int) (UserProfileDTO, error)
UpdateProfile(ctx context.Context, id int, dto UpdateProfileDTO) (UserProfileDTO, error)
}