changed arhitecture
This commit is contained in:
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
|
||||
}
|
||||
Reference in New Issue
Block a user