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,224 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/identity/user"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
"golang.org/x/crypto/bcrypt"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) user.Repository {
return &repository{client: client, logger: logger}
}
const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.social_media, u.light_mode, u.role, u.active, u.created_at, u.updated_at`
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return user.ListUserDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return user.ListUserDTO{}, err
}
defer rows.Close()
var items []user.UserDTO
for rows.Next() {
item, err := scanUser(rows)
if err != nil {
return user.ListUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return user.ListUserDTO{}, err
}
return user.ListUserDTO{Count: count, Users: items}, nil
}
func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) {
return buildFilteredListQuery(filter, "")
}
func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM users u `
var conditions []string
if filter.Username != "" {
args = append(args, likePattern(filter.Username))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
}
if role != "" {
args = append(args, role)
n := len(args)
conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n))
}
if len(conditions) == 0 {
return fromClause, "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return user.ListUserDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d `,
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return user.ListUserDTO{}, err
}
defer rows.Close()
var items []user.UserDTO
for rows.Next() {
item, err := scanUser(rows)
if err != nil {
return user.ListUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return user.ListUserDTO{}, err
}
return user.ListUserDTO{Count: count, Users: items}, nil
}
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM users u WHERE u.id = $1`, userColumns)
item, err := scanUser(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return user.UserDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.UserDTO, error) {
socialMedia, err := json.Marshal(dto.SocialMedia)
if err != nil {
return user.UserDTO{}, err
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost)
if err != nil {
return user.UserDTO{}, err
}
active := true
if dto.Active != nil {
active = *dto.Active
}
query := fmt.Sprintf(`
INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING %s`, userReturningColumns)
return scanUser(r.client.QueryRow(ctx, query,
dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, socialMedia, dto.LightMode, dto.Role, active,
))
}
func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO) (user.UserDTO, error) {
socialMedia, err := json.Marshal(dto.SocialMedia)
if err != nil {
return user.UserDTO{}, err
}
query := fmt.Sprintf(`
UPDATE users SET
email = $1, name = $2, first_name = $3, last_name = $4, username = $5, phone = $6, avatar = $7,
social_media = $8, light_mode = $9, role = $10, active = $11,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $12
RETURNING %s`, userReturningColumns)
item, err := scanUser(r.client.QueryRow(ctx, query,
dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, socialMedia, dto.LightMode, dto.Role, dto.Active, id,
))
if errors.Is(err, pgx.ErrNoRows) {
return user.UserDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanUser(row scannable) (user.UserDTO, error) {
var item user.UserDTO
var socialMedia []byte
if err := row.Scan(
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
&socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt,
); err != nil {
return user.UserDTO{}, err
}
if err := json.Unmarshal(socialMedia, &item.SocialMedia); err != nil {
return user.UserDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,66 @@
package user
import "time"
type SocialMedia struct {
Facebook string `json:"facebook"`
Instagram string `json:"instagram"`
Telegram string `json:"telegram"`
}
type UserDTO struct {
Id int64 `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
SocialMedia SocialMedia `json:"socialMedia"`
LightMode int `json:"lightMode"`
Role string `json:"role"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateUserDTO struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
Name string `json:"name" binding:"required"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username" binding:"required"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
SocialMedia SocialMedia `json:"socialMedia"`
LightMode int `json:"lightMode"`
Role string `json:"role"`
Active *bool `json:"active"`
}
type UpdateUserDTO struct {
Email string `json:"email" binding:"required"`
Name string `json:"name" binding:"required"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username" binding:"required"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
SocialMedia SocialMedia `json:"socialMedia"`
LightMode int `json:"lightMode"`
Role string `json:"role"`
Active bool `json:"active"`
}
type ListFilter struct {
Username string
Page int
Limit int
}
type ListUserDTO struct {
Count int64 `json:"count"`
Users []UserDTO `json:"users"`
}

View File

@@ -0,0 +1,437 @@
package user
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"online-back/internal/appresult"
"online-back/internal/config"
"online-back/internal/handlers"
"online-back/pkg/logging"
minioUpload "online-back/pkg/minio"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
"github.com/minio/minio-go/v7"
)
const (
baseURL = "/users"
fileUploadURL = "/file"
fileURL = "/file/:id"
)
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.GET("/role", h.listUsersByRole)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
// Avatar/profile file storage — kept at the top-level /file path (not
// nested under /users) to preserve the existing API contract; this used
// to live in the auth handler purely incidentally.
files := router.Group("", appresult.JwtTokenCheck())
files.POST(fileUploadURL, h.fileUpload)
files.GET(fileURL, h.getFile)
files.DELETE(fileURL, h.deleteFile)
}
// list godoc
// @Summary List users
// @Description Returns paginated users with optional filters
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param username query string false "Filter by username"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// listUsersByRole godoc
// @Summary List users by role
// @Description Returns paginated users filtered by role
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param role query string true "user role"
// @Param username query string false "Filter by username"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/role [get]
func (h *handler) listUsersByRole(c *gin.Context) {
role := strings.TrimSpace(c.Query("role"))
if role == "" {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByRole(c.Request.Context(), role, filter)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// getByID godoc
// @Summary Get user by ID
// @Description Returns a single user
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create user
// @Description Creates a new user
// @Tags user
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateUserDTO true "User payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users [post]
func (h *handler) create(c *gin.Context) {
var dto CreateUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update user
// @Description Updates an existing user
// @Tags user
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Param body body UpdateUserDTO true "User payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
var dto UpdateUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete user
// @Description Deletes a user
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("user removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("username")); raw != "" {
filter.Username = raw
}
return filter, true
}
// fileUpload godoc
// @Description file upload
// @Tags file-upload
//
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "this is a test file"
//
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /file [post]
func (h *handler) fileUpload(c *gin.Context) {
file, header, err := c.Request.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
defer file.Close()
minioCfg := config.GetConfig().Minio
minioClient, ok := h.connectMinio(c, minioCfg)
if !ok {
return
}
ctx := c.Request.Context()
if err := ensureBucket(ctx, minioClient, minioCfg.Bucket); err != nil {
h.logger.Errorf("ensure minio bucket failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
objectName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
contentType := header.Header.Get("Content-Type")
if _, err := minioClient.PutObject(ctx, minioCfg.Bucket, objectName, file, header.Size, minio.PutObjectOptions{ContentType: contentType}); err != nil {
h.logger.Errorf("upload file to minio failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(objectName))
}
// getFile godoc
// @Description download file
// @Tags file-upload
// @Produce octet-stream
// @Param id path string true "object name"
// @Security BearerAuth
// @Success 200 {file} binary
// @Failure 500 {object} appresult.AppError
// @Router /file/{id} [get]
func (h *handler) getFile(c *gin.Context) {
id := c.Param("id")
minioCfg := config.GetConfig().Minio
minioClient, ok := h.connectMinio(c, minioCfg)
if !ok {
return
}
object, err := minioClient.GetObject(c.Request.Context(), minioCfg.Bucket, id, minio.GetObjectOptions{})
if err != nil {
h.logger.Errorf("get object from minio failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
return
}
defer object.Close()
content, err := io.ReadAll(object)
if err != nil {
h.logger.Errorf("read object from minio failed: %v", err)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.Data(http.StatusOK, http.DetectContentType(content), content)
}
// deleteFile godoc
// @Description remove file
// @Tags file-upload
// @Produce json
// @Param id path string true "object name"
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 500 {object} appresult.AppError
// @Router /file/{id} [delete]
func (h *handler) deleteFile(c *gin.Context) {
id := c.Param("id")
minioCfg := config.GetConfig().Minio
minioClient, ok := h.connectMinio(c, minioCfg)
if !ok {
return
}
if err := minioClient.RemoveObject(c.Request.Context(), minioCfg.Bucket, id, minio.RemoveObjectOptions{GovernanceBypass: true}); err != nil {
h.logger.Errorf("remove object from minio failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("file removed"))
}
// connectMinio opens a MinIO client, writing an error response and returning
// ok=false if the connection fails so callers can bail out immediately.
func (h *handler) connectMinio(c *gin.Context, cfg config.MinioConfig) (*minio.Client, bool) {
client, err := minioUpload.Connect(cfg.Endpoint, cfg.AccessKey, cfg.SecretKey, cfg.UseSSL)
if err != nil {
h.logger.Errorf("minio connection failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return nil, false
}
return client, true
}
func ensureBucket(ctx context.Context, client *minio.Client, bucket string) error {
exists, err := client.BucketExists(ctx, bucket)
if err != nil {
return err
}
if exists {
return nil
}
return client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})
}

View File

@@ -0,0 +1,12 @@
package user
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListUserDTO, error)
GetByID(ctx context.Context, id int64) (UserDTO, error)
GetByRole(ctx context.Context, role string, filter ListFilter) (ListUserDTO, error)
Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)
Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error)
Delete(ctx context.Context, id int64) error
}