changed arhitecture
This commit is contained in:
83
internal/identity/auth/db/postgresql.go
Executable file
83
internal/identity/auth/db/postgresql.go
Executable 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
35
internal/identity/auth/dto.go
Executable 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
186
internal/identity/auth/handler.go
Executable 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
|
||||
}
|
||||
}
|
||||
55
internal/identity/auth/service.go
Normal file
55
internal/identity/auth/service.go
Normal 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)
|
||||
}
|
||||
10
internal/identity/auth/storage.go
Executable file
10
internal/identity/auth/storage.go
Executable 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)
|
||||
}
|
||||
108
internal/identity/permission/db/postgresql.go
Normal file
108
internal/identity/permission/db/postgresql.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/permission"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[permission.PermissionDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "permissions p", permissionColumns, scanPermission),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
|
||||
|
||||
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
|
||||
return permission.ListPermissionDTO{Count: count, Permissions: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " 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) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO permissions (code, name, guard_name)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto permission.UpdatePermissionDTO) (permission.PermissionDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE permissions SET
|
||||
code = $1, name = $2, guard_name = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) {
|
||||
var item permission.PermissionDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
35
internal/identity/permission/dto.go
Normal file
35
internal/identity/permission/dto.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package permission
|
||||
|
||||
import "time"
|
||||
|
||||
type PermissionDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PermissionName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListPermissionDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Permissions []PermissionDTO `json:"permissions"`
|
||||
}
|
||||
242
internal/identity/permission/handler.go
Normal file
242
internal/identity/permission/handler.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permissions"
|
||||
|
||||
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("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List permissions
|
||||
// @Description Returns paginated permissions with optional filters
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by name"
|
||||
// @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 /permissions [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 permissions failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get permission by ID
|
||||
// @Description Returns a single permission
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create permission
|
||||
// @Description Creates a new permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionDTO true "Permission payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePermissionDTO
|
||||
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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update permission
|
||||
// @Description Updates an existing permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Param body body UpdatePermissionDTO true "Permission payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{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 UpdatePermissionDTO
|
||||
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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete permission
|
||||
// @Description Deletes a permission
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission 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("permission_name")); raw != "" {
|
||||
filter.PermissionName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/identity/permission/storage.go
Normal file
11
internal/identity/permission/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package permission
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (PermissionDTO, error)
|
||||
Create(ctx context.Context, dto CreatePermissionDTO) (PermissionDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdatePermissionDTO) (PermissionDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
132
internal/identity/permissionuser/db/postgresql.go
Normal file
132
internal/identity/permissionuser/db/postgresql.go
Normal file
@@ -0,0 +1,132 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/permissionuser"
|
||||
"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) permissionuser.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const permissionUserFromClause = ` FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
JOIN users u ON u.id = pu.user_id`
|
||||
|
||||
const permissionUserSelectColumns = `pu.id, pu.permission_id, p.name, pu.user_id, u.name, pu.created_at, pu.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permissionuser.ListFilter) (permissionuser.ListPermissionUserDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+permissionUserFromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
|
||||
query := `SELECT ` + permissionUserSelectColumns + permissionUserFromClause + whereClause + ` ORDER BY pu.id DESC`
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []permissionuser.PermissionUserDTO
|
||||
for rows.Next() {
|
||||
item, err := scanPermissionUser(rows)
|
||||
if err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
|
||||
return permissionuser.ListPermissionUserDTO{Count: count, Items: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter permissionuser.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("pu.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
conditions = append(conditions, fmt.Sprintf("p.name ILIKE $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " 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) Create(ctx context.Context, dto permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO permission_user (permission_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, permission_id, user_id, created_at, updated_at
|
||||
)
|
||||
SELECT inserted.id, inserted.permission_id, p.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
|
||||
FROM inserted
|
||||
JOIN permissions p ON p.id = inserted.permission_id
|
||||
JOIN users u ON u.id = inserted.user_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId)
|
||||
return scanPermissionUser(row)
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM permission_user 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 scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) {
|
||||
var item permissionuser.PermissionUserDTO
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permissionuser.PermissionUserDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return permissionuser.PermissionUserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
28
internal/identity/permissionuser/dto.go
Normal file
28
internal/identity/permissionuser/dto.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package permissionuser
|
||||
|
||||
import "time"
|
||||
|
||||
type PermissionUserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
PermissionId int64 `json:"permissionId"`
|
||||
PermissionName string `json:"permissionName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ListPermissionUserDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Items []PermissionUserDTO `json:"items"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
PermissionName string
|
||||
}
|
||||
|
||||
type CreatePermissionUserDTO struct {
|
||||
PermissionId int64 `json:"permissionId" binding:"required"`
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
}
|
||||
152
internal/identity/permissionuser/handler.go
Normal file
152
internal/identity/permissionuser/handler.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package permissionuser
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permission-users"
|
||||
|
||||
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.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List permission users
|
||||
// @Description Returns the authenticated user's permission-user assignments with the related user and permission
|
||||
// @Tags permission-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by permission name"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-users [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
filter := ListFilter{
|
||||
UserId: &userID,
|
||||
PermissionName: strings.TrimSpace(c.Query("permission_name")),
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list permission users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign user to permission
|
||||
// @Description Creates a permission-user assignment
|
||||
// @Tags permission-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionUserDTO true "Permission-user payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePermissionUserDTO
|
||||
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 permission user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Remove user from permission
|
||||
// @Description Deletes a permission-user assignment
|
||||
// @Tags permission-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission-user ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-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 permission user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission 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
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (int64, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
return parseID(id)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
9
internal/identity/permissionuser/storage.go
Normal file
9
internal/identity/permissionuser/storage.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package permissionuser
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionUserDTO, error)
|
||||
Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
38
internal/identity/rbac/middleware.go
Normal file
38
internal/identity/rbac/middleware.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RequirePermission returns a gin middleware that 403s unless the
|
||||
// authenticated user (set by appresult.JwtTokenCheck, which must run first)
|
||||
// has been directly granted the given permission code. Not currently
|
||||
// attached to any route.
|
||||
func RequirePermission(service *Service, code string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, code)
|
||||
if err != nil || !granted {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
42
internal/identity/rbac/service.go
Normal file
42
internal/identity/rbac/service.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// Package rbac provides permission-check capability on top of the existing
|
||||
// permissions/permission_user tables. It is not wired into any route yet —
|
||||
// today every route is still gated only by appresult.JwtTokenCheck()'s
|
||||
// admin-claim check. RequirePermission is available for routes to opt into
|
||||
// once permission data is populated and specific routes are chosen.
|
||||
//
|
||||
// Note: the schema has no role_permission pivot table, so role-based
|
||||
// permission resolution isn't possible yet — HasPermission only resolves
|
||||
// permissions granted directly via permission_user.
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"online-back/pkg/client/postgresql"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
client postgresql.Client
|
||||
}
|
||||
|
||||
func NewService(client postgresql.Client) *Service {
|
||||
return &Service{client: client}
|
||||
}
|
||||
|
||||
// HasPermission reports whether userID has been directly granted the
|
||||
// permission identified by code (permissions.code) via permission_user.
|
||||
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
WHERE pu.user_id = $1 AND p.code = $2
|
||||
)`
|
||||
|
||||
var granted bool
|
||||
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return granted, nil
|
||||
}
|
||||
56
internal/identity/rbac/service_test.go
Normal file
56
internal/identity/rbac/service_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type fakeClient struct {
|
||||
granted bool
|
||||
}
|
||||
|
||||
func (f *fakeClient) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
|
||||
return fakeRow{granted: f.granted}
|
||||
}
|
||||
|
||||
func (f *fakeClient) Begin(ctx context.Context) (pgx.Tx, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type fakeRow struct {
|
||||
granted bool
|
||||
}
|
||||
|
||||
func (r fakeRow) Scan(dest ...interface{}) error {
|
||||
*dest[0].(*bool) = r.granted
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestHasPermission(t *testing.T) {
|
||||
granted, err := NewService(&fakeClient{granted: true}).HasPermission(context.Background(), 1, "province.write")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !granted {
|
||||
t.Fatal("expected permission to be granted")
|
||||
}
|
||||
|
||||
granted, err = NewService(&fakeClient{granted: false}).HasPermission(context.Background(), 1, "province.write")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if granted {
|
||||
t.Fatal("expected permission to not be granted")
|
||||
}
|
||||
}
|
||||
108
internal/identity/role/db/postgresql.go
Normal file
108
internal/identity/role/db/postgresql.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/role"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[role.RoleDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "roles r", roleColumns, scanRole),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at`
|
||||
|
||||
const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
|
||||
return role.ListRoleDTO{Count: count, Roles: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.RoleName != "" {
|
||||
args = append(args, likePattern(filter.RoleName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " 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) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO roles (code, name, guard_name)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING %s`, roleReturningColumns)
|
||||
|
||||
return scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDTO) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE roles SET
|
||||
code = $1, name = $2, guard_name = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING %s`, roleReturningColumns)
|
||||
|
||||
item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanRole(row genericrepo.Scanner) (role.RoleDTO, error) {
|
||||
var item role.RoleDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
35
internal/identity/role/dto.go
Normal file
35
internal/identity/role/dto.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package role
|
||||
|
||||
import "time"
|
||||
|
||||
type RoleDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateRoleDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateRoleDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
RoleName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListRoleDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Roles []RoleDTO `json:"roles"`
|
||||
}
|
||||
242
internal/identity/role/handler.go
Normal file
242
internal/identity/role/handler.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package role
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/roles"
|
||||
|
||||
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("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List roles
|
||||
// @Description Returns paginated roles with optional filters
|
||||
// @Tags role
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param role_name query string false "Filter by name"
|
||||
// @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 /roles [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 roles failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get role by ID
|
||||
// @Description Returns a single role
|
||||
// @Tags role
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles/{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 role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create role
|
||||
// @Description Creates a new role
|
||||
// @Tags role
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateRoleDTO true "Role payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateRoleDTO
|
||||
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 role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update role
|
||||
// @Description Updates an existing role
|
||||
// @Tags role
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role ID"
|
||||
// @Param body body UpdateRoleDTO true "Role payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles/{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 UpdateRoleDTO
|
||||
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 role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete role
|
||||
// @Description Deletes a role
|
||||
// @Tags role
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles/{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 role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("role 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("role_name")); raw != "" {
|
||||
filter.RoleName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/identity/role/storage.go
Normal file
11
internal/identity/role/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package role
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListRoleDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (RoleDTO, error)
|
||||
Create(ctx context.Context, dto CreateRoleDTO) (RoleDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateRoleDTO) (RoleDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
132
internal/identity/roleusers/db/postgresql.go
Normal file
132
internal/identity/roleusers/db/postgresql.go
Normal file
@@ -0,0 +1,132 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/roleusers"
|
||||
"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) roleusers.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const roleUserFromClause = ` FROM role_user ru
|
||||
JOIN roles r ON r.id = ru.role_id
|
||||
JOIN users u ON u.id = ru.user_id`
|
||||
|
||||
const roleUserSelectColumns = `ru.id, ru.role_id, r.name, ru.user_id, u.name, ru.created_at, ru.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter roleusers.ListFilter) (roleusers.ListRoleUserDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+roleUserFromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
|
||||
query := `SELECT ` + roleUserSelectColumns + roleUserFromClause + whereClause + ` ORDER BY ru.id DESC`
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []roleusers.RoleUserDTO
|
||||
for rows.Next() {
|
||||
item, err := scanRoleUser(rows)
|
||||
if err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
|
||||
return roleusers.ListRoleUserDTO{Count: count, Items: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter roleusers.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("ru.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.RoleName != "" {
|
||||
args = append(args, likePattern(filter.RoleName))
|
||||
conditions = append(conditions, fmt.Sprintf("r.name ILIKE $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " 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) Create(ctx context.Context, dto roleusers.CreateRoleUserDTO) (roleusers.RoleUserDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, role_id, user_id, created_at, updated_at
|
||||
)
|
||||
SELECT inserted.id, inserted.role_id, r.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
|
||||
FROM inserted
|
||||
JOIN roles r ON r.id = inserted.role_id
|
||||
JOIN users u ON u.id = inserted.user_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.RoleId, dto.UserId)
|
||||
return scanRoleUser(row)
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM role_user 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 scanRoleUser(row scannable) (roleusers.RoleUserDTO, error) {
|
||||
var item roleusers.RoleUserDTO
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.RoleId, &item.RoleName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return roleusers.RoleUserDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return roleusers.RoleUserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
28
internal/identity/roleusers/dto.go
Normal file
28
internal/identity/roleusers/dto.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package roleusers
|
||||
|
||||
import "time"
|
||||
|
||||
type RoleUserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
RoleId int64 `json:"roleId"`
|
||||
RoleName string `json:"roleName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ListRoleUserDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Items []RoleUserDTO `json:"items"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
RoleName string
|
||||
}
|
||||
|
||||
type CreateRoleUserDTO struct {
|
||||
RoleId int64 `json:"roleId" binding:"required"`
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
}
|
||||
152
internal/identity/roleusers/handler.go
Normal file
152
internal/identity/roleusers/handler.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package roleusers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/role-users"
|
||||
|
||||
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.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List role users
|
||||
// @Description Returns the authenticated user's role-user assignments with the related user and role
|
||||
// @Tags role-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param role_name query string false "Filter by role name"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /role-users [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
filter := ListFilter{
|
||||
UserId: &userID,
|
||||
RoleName: strings.TrimSpace(c.Query("role_name")),
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list role users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign user to role
|
||||
// @Description Creates a role-user assignment
|
||||
// @Tags role-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateRoleUserDTO true "Role-user payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /role-users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateRoleUserDTO
|
||||
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 role user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Remove user from role
|
||||
// @Description Deletes a role-user assignment
|
||||
// @Tags role-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role-user ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /role-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 role user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("role 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
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (int64, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
return parseID(id)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
9
internal/identity/roleusers/storage.go
Normal file
9
internal/identity/roleusers/storage.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package roleusers
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListRoleUserDTO, error)
|
||||
Create(ctx context.Context, dto CreateRoleUserDTO) (RoleUserDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
45
internal/identity/router.go
Normal file
45
internal/identity/router.go
Normal file
@@ -0,0 +1,45 @@
|
||||
// Package identity groups authentication, users, and RBAC (roles,
|
||||
// permissions, and their user/branch assignments) under one bounded
|
||||
// context, replacing the flat internal/admin/* listing.
|
||||
package identity
|
||||
|
||||
import (
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/auth"
|
||||
authdb "online-back/internal/identity/auth/db"
|
||||
"online-back/internal/identity/permission"
|
||||
permissiondb "online-back/internal/identity/permission/db"
|
||||
"online-back/internal/identity/permissionuser"
|
||||
permissionuserdb "online-back/internal/identity/permissionuser/db"
|
||||
"online-back/internal/identity/role"
|
||||
roledb "online-back/internal/identity/role/db"
|
||||
"online-back/internal/identity/roleusers"
|
||||
roleusersdb "online-back/internal/identity/roleusers/db"
|
||||
"online-back/internal/identity/user"
|
||||
userdb "online-back/internal/identity/user/db"
|
||||
"online-back/internal/identity/userbranch"
|
||||
userbranchdb "online-back/internal/identity/userbranch/db"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Register wires every identity module's handler onto router.
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
|
||||
for _, h := range Handlers(client, logger) {
|
||||
h.Register(router)
|
||||
}
|
||||
}
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
auth.NewHandler(logger, authdb.NewRepository(client, logger)),
|
||||
user.NewHandler(logger, userdb.NewRepository(client, logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
||||
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
|
||||
permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)),
|
||||
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
224
internal/identity/user/db/postgresql.go
Normal file
224
internal/identity/user/db/postgresql.go
Normal 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
|
||||
}
|
||||
66
internal/identity/user/dto.go
Normal file
66
internal/identity/user/dto.go
Normal 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"`
|
||||
}
|
||||
437
internal/identity/user/handler.go
Normal file
437
internal/identity/user/handler.go
Normal 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{})
|
||||
}
|
||||
12
internal/identity/user/storage.go
Normal file
12
internal/identity/user/storage.go
Normal 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
|
||||
}
|
||||
140
internal/identity/userbranch/db/postgresql.go
Normal file
140
internal/identity/userbranch/db/postgresql.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/userbranch"
|
||||
"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) userbranch.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const userBranchFromClause = ` FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
JOIN users u ON u.id = bu.user_id`
|
||||
|
||||
const userBranchSelectColumns = `bu.id, bu.branch_id, b.name, bu.user_id, u.name, bu.created_at, bu.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter userbranch.ListFilter) (userbranch.ListUserBranchDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+userBranchFromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
|
||||
query := `SELECT ` + userBranchSelectColumns + userBranchFromClause + whereClause + ` ORDER BY bu.id DESC`
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []userbranch.UserBranchDTO
|
||||
for rows.Next() {
|
||||
item, err := scanUserBranch(rows)
|
||||
if err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
|
||||
return userbranch.ListUserBranchDTO{Count: count, Items: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter userbranch.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("bu.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchName != "" {
|
||||
args = append(args, likePattern(filter.BranchName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
b.name->>'en' ILIKE $%[1]d OR b.name->>'ru' ILIKE $%[1]d OR b.name->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " 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) Create(ctx context.Context, dto userbranch.CreateUserBranchDTO) (userbranch.UserBranchDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO branch_user (branch_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, branch_id, user_id, created_at, updated_at
|
||||
)
|
||||
SELECT inserted.id, inserted.branch_id, b.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
|
||||
FROM inserted
|
||||
JOIN branches b ON b.id = inserted.branch_id
|
||||
JOIN users u ON u.id = inserted.user_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.BranchId, dto.UserId)
|
||||
return scanUserBranch(row)
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM branch_user 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 scanUserBranch(row scannable) (userbranch.UserBranchDTO, error) {
|
||||
var item userbranch.UserBranchDTO
|
||||
var branchNameJSON []byte
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.BranchId, &branchNameJSON, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return userbranch.UserBranchDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return userbranch.UserBranchDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil {
|
||||
return userbranch.UserBranchDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
34
internal/identity/userbranch/dto.go
Normal file
34
internal/identity/userbranch/dto.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package userbranch
|
||||
|
||||
import "time"
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type UserBranchDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
BranchName LocalizedText `json:"branchName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ListUserBranchDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Items []UserBranchDTO `json:"items"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
BranchName string
|
||||
}
|
||||
|
||||
type CreateUserBranchDTO struct {
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
}
|
||||
152
internal/identity/userbranch/handler.go
Normal file
152
internal/identity/userbranch/handler.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package userbranch
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/branch-users"
|
||||
|
||||
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.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List branch users
|
||||
// @Description Returns the authenticated user's branch-user assignments with the related user and branch
|
||||
// @Tags branch-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param branch_name query string false "Filter by branch name (en, ru, tm)"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /branch-users [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
filter := ListFilter{
|
||||
UserId: &userID,
|
||||
BranchName: strings.TrimSpace(c.Query("branch_name")),
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list branch users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign user to branch
|
||||
// @Description Creates a branch-user assignment
|
||||
// @Tags branch-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateUserBranchDTO true "Branch-user payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /branch-users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateUserBranchDTO
|
||||
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 branch user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Remove user from branch
|
||||
// @Description Deletes a branch-user assignment
|
||||
// @Tags branch-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Branch-user ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /branch-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 branch user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("branch 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
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (int64, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
return parseID(id)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
9
internal/identity/userbranch/storage.go
Normal file
9
internal/identity/userbranch/storage.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package userbranch
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListUserBranchDTO, error)
|
||||
Create(ctx context.Context, dto CreateUserBranchDTO) (UserBranchDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
Reference in New Issue
Block a user