changed role permission
This commit is contained in:
1 parent
f0ecf23879
commit
323e131216
74 files changed
+2915
-4713
No files matched your search
@@ -30,17 +30,10 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) user.Reposi
|
||||
|
||||
const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.active, u.created_at, u.updated_at, r.id, r.code`
|
||||
|
||||
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, role, active, created_at, updated_at`
|
||||
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, active, created_at, updated_at`
|
||||
|
||||
const userFromClause = ` FROM users u
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_id `
|
||||
LEFT JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL `
|
||||
|
||||
const userBranchesJSON = `COALESCE((
|
||||
SELECT json_agg(jsonb_build_object(
|
||||
@@ -57,19 +50,13 @@ const userBranchesJSON = `COALESCE((
|
||||
) b
|
||||
), '[]'::json)`
|
||||
|
||||
// userPermissionsJSON lists the effective permissions: every one for an
|
||||
// is_super role, else the role's role_permissions.
|
||||
const userPermissionsJSON = `COALESCE((
|
||||
SELECT json_agg(jsonb_build_object(
|
||||
'id', p.id,
|
||||
'code', COALESCE(p.code, ''),
|
||||
'name', p.name,
|
||||
'guardName', p.guard_name,
|
||||
'module', COALESCE(p.module, '')
|
||||
) ORDER BY p.module, p.id)
|
||||
SELECT json_agg(jsonb_build_object('code', p.code, 'name', p.name) ORDER BY p.code)
|
||||
FROM permissions p
|
||||
WHERE p.deleted_at IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM permission_role pr
|
||||
WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL
|
||||
WHERE r.is_super OR EXISTS (
|
||||
SELECT 1 FROM role_permissions rp WHERE rp.role_id = r.id AND rp.permission_code = p.code
|
||||
)
|
||||
), '[]'::json)`
|
||||
|
||||
@@ -225,7 +212,7 @@ func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.UserDTO, error) {
|
||||
func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO, roleID int64) (user.UserDTO, error) {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
@@ -236,78 +223,56 @@ func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.U
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
role := strings.TrimSpace(dto.Role)
|
||||
if role == "" {
|
||||
role = "user"
|
||||
}
|
||||
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, role, active)
|
||||
INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, role_id, active)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING %s`, userReturningColumns)
|
||||
|
||||
item, err := scanUser(tx.QueryRow(ctx, query,
|
||||
dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, role, active,
|
||||
item, err := scanUser(r.client.QueryRow(ctx, query,
|
||||
dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, roleID, active,
|
||||
))
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
|
||||
if err := assignRoleByCode(ctx, tx, item.Id, role); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
item.RoleId = roleIDByCode(ctx, tx, role)
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
return r.withRole(ctx, item, roleID)
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO) (user.UserDTO, error) {
|
||||
role := strings.TrimSpace(dto.Role)
|
||||
if role == "" {
|
||||
role = "user"
|
||||
}
|
||||
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO, roleID int64) (user.UserDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE users SET
|
||||
email = $1, name = $2, first_name = $3, last_name = $4, username = $5, phone = $6, avatar = $7,
|
||||
role = $8, active = $9,
|
||||
role_id = $8, active = $9,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $10 AND deleted_at IS NULL
|
||||
RETURNING %s`, userReturningColumns)
|
||||
|
||||
item, err := scanUser(tx.QueryRow(ctx, query,
|
||||
dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, role, dto.Active, id,
|
||||
item, err := scanUser(r.client.QueryRow(ctx, query,
|
||||
dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, roleID, dto.Active, id,
|
||||
))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return r.withRole(ctx, item, roleID)
|
||||
}
|
||||
|
||||
if err := replaceRoleByCode(ctx, tx, item.Id, role); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
item.RoleId = roleIDByCode(ctx, tx, role)
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
func (r *repository) SetRole(ctx context.Context, id, roleID int64) error {
|
||||
tag, err := r.client.Exec(ctx, `
|
||||
UPDATE users SET role_id = $1, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $2 AND deleted_at IS NULL`, roleID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) withRole(ctx context.Context, item user.UserDTO, roleID int64) (user.UserDTO, error) {
|
||||
if err := r.client.QueryRow(ctx, `SELECT code FROM roles WHERE id = $1`, roleID).Scan(&item.Role); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
item.RoleId = &roleID
|
||||
return item, nil
|
||||
}
|
||||
|
||||
@@ -315,48 +280,36 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return genericrepo.Delete(ctx, r.client, "users", id)
|
||||
}
|
||||
|
||||
func (r *repository) RoleGuardName(ctx context.Context, code string) (string, error) {
|
||||
var guardName string
|
||||
err := r.client.QueryRow(ctx, `SELECT guard_name FROM roles WHERE code = $1`, code).Scan(&guardName)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", nil
|
||||
}
|
||||
return guardName, err
|
||||
func (r *repository) RoleByCode(ctx context.Context, code string) (*rbac.RoleInfo, error) {
|
||||
return rbac.ScanRoleInfo(r.client.QueryRow(ctx,
|
||||
rbac.RoleInfoSelect+`WHERE r.code = $1 AND r.deleted_at IS NULL`, strings.TrimSpace(code)))
|
||||
}
|
||||
|
||||
func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error {
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
SELECT r.id, $1 FROM roles r WHERE r.code = $2`, userID, roleCode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return fmt.Errorf("role %q not found", roleCode)
|
||||
}
|
||||
return nil
|
||||
func (r *repository) RoleByID(ctx context.Context, id int64) (*rbac.RoleInfo, error) {
|
||||
return rbac.ScanRoleInfo(r.client.QueryRow(ctx,
|
||||
rbac.RoleInfoSelect+`WHERE r.id = $1 AND r.deleted_at IS NULL`, id))
|
||||
}
|
||||
|
||||
func replaceRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error {
|
||||
if _, err := tx.Exec(ctx, `UPDATE role_user SET deleted_at = now() WHERE user_id = $1 AND deleted_at IS NULL`, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
return assignRoleByCode(ctx, tx, userID, roleCode)
|
||||
func (r *repository) RoleOfUser(ctx context.Context, userID int64) (*rbac.RoleInfo, error) {
|
||||
return rbac.ScanRoleInfo(r.client.QueryRow(ctx,
|
||||
rbac.RoleInfoSelect+`JOIN users u ON u.role_id = r.id
|
||||
WHERE u.id = $1 AND u.deleted_at IS NULL AND r.deleted_at IS NULL`, userID))
|
||||
}
|
||||
|
||||
func roleIDByCode(ctx context.Context, tx pgx.Tx, roleCode string) *int64 {
|
||||
var id int64
|
||||
if err := tx.QueryRow(ctx, `SELECT id FROM roles WHERE code = $1`, roleCode).Scan(&id); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &id
|
||||
func (r *repository) CountSuperUsers(ctx context.Context) (int64, error) {
|
||||
var count int64
|
||||
err := r.client.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM users u
|
||||
JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL
|
||||
WHERE r.is_super AND u.deleted_at IS NULL`).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func scanUser(row genericrepo.Scanner) (user.UserDTO, error) {
|
||||
var item user.UserDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
||||
&item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
&item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
|
||||
@@ -15,11 +15,8 @@ type StaffBranchDTO struct {
|
||||
}
|
||||
|
||||
type UserPermissionDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
Module string `json:"module"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type UserDTO struct {
|
||||
@@ -49,8 +46,10 @@ type CreateUserDTO struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role string `json:"role"`
|
||||
Active *bool `json:"active"`
|
||||
// Role is a role code; RoleId wins when both are sent. Neither → "user".
|
||||
Role string `json:"role"`
|
||||
RoleId *int64 `json:"roleId"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateUserDTO struct {
|
||||
@@ -61,8 +60,15 @@ type UpdateUserDTO struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
// Role is a role code; RoleId wins when both are sent. Neither keeps
|
||||
// the user's current role.
|
||||
Role string `json:"role"`
|
||||
RoleId *int64 `json:"roleId"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type SetUserRoleDTO struct {
|
||||
RoleId int64 `json:"roleId" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
@@ -70,8 +76,8 @@ type ListFilter struct {
|
||||
BranchIds []int64
|
||||
Page int
|
||||
Limit int
|
||||
// AllRoles, when true, skips the role=user filter so admin/superadmin
|
||||
// callers see every user regardless of role.
|
||||
// AllRoles, when true, skips the role=user filter so all-scope callers
|
||||
// see every user regardless of role.
|
||||
AllRoles bool
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
minioUpload "online-back/pkg/minio"
|
||||
@@ -26,7 +27,6 @@ import (
|
||||
const (
|
||||
baseURL = "/users"
|
||||
fileUploadURL = "/file"
|
||||
fileURL = "/file/:id"
|
||||
publicFileURL = "/file/:file_name"
|
||||
)
|
||||
|
||||
@@ -40,20 +40,23 @@ func NewHandler(logger *logging.Logger, repository Repository) *handler {
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Users))
|
||||
group.GET("", h.list)
|
||||
group.GET("/clients", h.listClients)
|
||||
group.GET("/staff", h.listStaff)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.PUT("/:id/role", h.setRole)
|
||||
group.DELETE("/:id", h.delete)
|
||||
|
||||
// Operators pick a client for a new order without holding users.
|
||||
rbac.Group(router, baseURL+"/clients", rbac.Staff()).GET("", h.listClients)
|
||||
|
||||
// Upload/delete stay on the admin API (JWT). GET is public at /file/:file_name
|
||||
// so nginx can serve avatars as https://host/file/<file_name>.
|
||||
files := router.Group("", appresult.JwtTokenCheck())
|
||||
files.POST(fileUploadURL, h.fileUpload)
|
||||
files.DELETE(fileURL, h.deleteFile)
|
||||
files := rbac.Group(router, fileUploadURL, rbac.Authenticated())
|
||||
files.POST("", h.fileUpload)
|
||||
files.DELETE("/:id", h.deleteFile)
|
||||
}
|
||||
|
||||
func (h *handler) RegisterPublic(engine *gin.Engine) {
|
||||
@@ -62,7 +65,7 @@ func (h *handler) RegisterPublic(engine *gin.Engine) {
|
||||
|
||||
// list godoc
|
||||
// @Summary List users
|
||||
// @Description Returns paginated users, including roleId. Admin-guard callers (admin, superadmin, and other admin-guard roles) see users of every role; branch-scoped operators see role=user only, scoped to their branches.
|
||||
// @Description Returns paginated users, including roleId. All-scope callers see users of every role; branch-scope callers see role=user only, scoped to their branches.
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
@@ -80,7 +83,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
filter.AllRoles = rbac.IsAdminGuard(c)
|
||||
filter.AllRoles = rbac.HasAllScope(c)
|
||||
rbac.BindBranchIDs(c, &filter.BranchIds)
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
@@ -194,7 +197,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
|
||||
// create godoc
|
||||
// @Summary Create user
|
||||
// @Description Creates a new user
|
||||
// @Description Creates a new user. The role (roleId or role code, default "user") must be one the caller could grant: no wider scope, no permission the caller lacks, superadmin only from a superadmin.
|
||||
// @Tags user
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -202,6 +205,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
// @Param body body CreateUserDTO true "User payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 403 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
@@ -211,16 +215,15 @@ func (h *handler) create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if allowed, err := h.roleAssignmentAllowed(c, dto.Role); err != nil {
|
||||
h.logger.Errorf("resolve role guard failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
next, ok := h.requestedRole(c, dto.RoleId, dto.Role, "user")
|
||||
if !ok {
|
||||
return
|
||||
} else if !allowed {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
if !h.authorizeRoleChange(c, 0, nil, next) {
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
item, err := h.repository.Create(c.Request.Context(), dto, next.ID)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
@@ -232,7 +235,7 @@ func (h *handler) create(c *gin.Context) {
|
||||
|
||||
// update godoc
|
||||
// @Summary Update user
|
||||
// @Description Updates an existing user
|
||||
// @Description Updates an existing user. Sending roleId or role changes the role (same rules as create); sending neither keeps it. Callers cannot manage a user whose role they could not grant, nor change their own role.
|
||||
// @Tags user
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -241,7 +244,9 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Param body body UpdateUserDTO true "User payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 403 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 409 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
@@ -261,16 +266,21 @@ func (h *handler) update(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if allowed, err := h.roleAssignmentAllowed(c, dto.Role); err != nil {
|
||||
h.logger.Errorf("resolve role guard failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
current, ok := h.currentRole(c, id)
|
||||
if !ok {
|
||||
return
|
||||
} else if !allowed {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
next := current
|
||||
if dto.RoleId != nil || strings.TrimSpace(dto.Role) != "" {
|
||||
if next, ok = h.requestedRole(c, dto.RoleId, dto.Role, ""); !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
if !h.authorizeRoleChange(c, id, current, next) {
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto, next.ID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
@@ -284,16 +294,81 @@ func (h *handler) update(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// setRole godoc
|
||||
// @Summary Set user role
|
||||
// @Description Gives the user exactly one role. Same rules as create/update.
|
||||
// @Tags user
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Param body body SetUserRoleDTO true "Role"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 403 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 409 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id}/role [put]
|
||||
func (h *handler) setRole(c *gin.Context) {
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if rbac.HasBranchScope(c) && !rbac.GuardUser(c, id) {
|
||||
return
|
||||
}
|
||||
|
||||
var dto SetUserRoleDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
current, ok := h.currentRole(c, id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
next, ok := h.requestedRole(c, &dto.RoleId, "", "")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !h.authorizeRoleChange(c, id, current, next) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.SetRole(c.Request.Context(), id, next.ID); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("set user role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
h.logger.Errorf("get user after role change 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
|
||||
// @Description Deletes a user. Callers cannot delete themselves, a user whose role they could not grant, or the last superadmin.
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 403 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 409 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
@@ -307,6 +382,23 @@ func (h *handler) delete(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
current, ok := h.currentRole(c, id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p := rbac.PrincipalFrom(c)
|
||||
if id == p.UserID {
|
||||
h.forbid(c, "cannot delete yourself", nil)
|
||||
return
|
||||
}
|
||||
if err := p.CanGrant(*current); err != nil {
|
||||
h.forbid(c, "cannot manage this user", err)
|
||||
return
|
||||
}
|
||||
if current.IsSuper && !h.otherSuperExists(c) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
@@ -319,25 +411,100 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("user removed"))
|
||||
}
|
||||
|
||||
// roleAssignmentAllowed asks "would granting this role let the target run
|
||||
// requests as guardAdmin?" using the role's real guard_name, the same input
|
||||
// rbac.Guard() resolves on every request - not a hardcoded list of role
|
||||
// names, which would drift the moment a new role is added. Without this, an
|
||||
// operator holding users.manage could set role:"admin" on themselves via
|
||||
// this same endpoint and escape branch scoping entirely.
|
||||
func (h *handler) roleAssignmentAllowed(c *gin.Context, role string) (bool, error) {
|
||||
if rbac.IsAdminGuard(c) {
|
||||
return true, nil
|
||||
}
|
||||
code := strings.ToLower(strings.TrimSpace(role))
|
||||
// requestedRole resolves roleID (preferred) or code, falling back to
|
||||
// fallbackCode when both are empty. It answers 400 for an unknown role.
|
||||
func (h *handler) requestedRole(c *gin.Context, roleID *int64, code, fallbackCode string) (*rbac.RoleInfo, bool) {
|
||||
ctx := c.Request.Context()
|
||||
code = strings.TrimSpace(code)
|
||||
if code == "" {
|
||||
code = "user"
|
||||
code = fallbackCode
|
||||
}
|
||||
|
||||
var role *rbac.RoleInfo
|
||||
var err error
|
||||
switch {
|
||||
case roleID != nil:
|
||||
role, err = h.repository.RoleByID(ctx, *roleID)
|
||||
case code != "":
|
||||
role, err = h.repository.RoleByCode(ctx, code)
|
||||
}
|
||||
guardName, err := h.repository.RoleGuardName(c.Request.Context(), code)
|
||||
if err != nil {
|
||||
return false, err
|
||||
h.logger.Errorf("resolve role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return nil, false
|
||||
}
|
||||
return rbac.EffectiveGuard(code, guardName) != rbac.GuardAdmin, nil
|
||||
if role == nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrUnknownRole)
|
||||
return nil, false
|
||||
}
|
||||
return role, true
|
||||
}
|
||||
|
||||
// currentRole answers 404 when the user does not exist.
|
||||
func (h *handler) currentRole(c *gin.Context, userID int64) (*rbac.RoleInfo, bool) {
|
||||
role, err := h.repository.RoleOfUser(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
h.logger.Errorf("load user role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return nil, false
|
||||
}
|
||||
if role == nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return role, true
|
||||
}
|
||||
|
||||
// authorizeRoleChange enforces the grant rules for moving user targetID
|
||||
// (0 = new user) from current (nil = new user) to next:
|
||||
// - the caller must be able to grant the user's current role, so nobody
|
||||
// edits a user who outranks them;
|
||||
// - a role change must be one the caller could grant (scope, permissions,
|
||||
// superadmin), must not be the caller's own role, and must not demote
|
||||
// the last superadmin.
|
||||
func (h *handler) authorizeRoleChange(c *gin.Context, targetID int64, current, next *rbac.RoleInfo) bool {
|
||||
p := rbac.PrincipalFrom(c)
|
||||
if current != nil {
|
||||
if err := p.CanGrant(*current); err != nil {
|
||||
h.forbid(c, "cannot manage this user", err)
|
||||
return false
|
||||
}
|
||||
if current.ID == next.ID {
|
||||
return true
|
||||
}
|
||||
if targetID == p.UserID {
|
||||
h.forbid(c, "cannot change your own role", nil)
|
||||
return false
|
||||
}
|
||||
}
|
||||
if err := p.CanGrant(*next); err != nil {
|
||||
h.forbid(c, "cannot grant this role", err)
|
||||
return false
|
||||
}
|
||||
if current != nil && current.IsSuper && !next.IsSuper {
|
||||
return h.otherSuperExists(c)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// otherSuperExists answers 409 when removing one superadmin would leave none.
|
||||
func (h *handler) otherSuperExists(c *gin.Context) bool {
|
||||
count, err := h.repository.CountSuperUsers(c.Request.Context())
|
||||
if err != nil {
|
||||
h.logger.Errorf("count superadmins failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
if count <= 1 {
|
||||
c.JSON(http.StatusConflict, appresult.ErrLastSuperadmin)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *handler) forbid(c *gin.Context, reason string, err error) {
|
||||
h.logger.Warnf("user role check denied (%s): %v", reason, err)
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// stubRoleRepo only implements RoleGuardName meaningfully - the other
|
||||
// methods exist solely to satisfy the Repository interface, since
|
||||
// roleAssignmentAllowed never calls them.
|
||||
type stubRoleRepo struct {
|
||||
guards map[string]string
|
||||
}
|
||||
|
||||
func (s *stubRoleRepo) List(context.Context, ListFilter) (ListUserDTO, error) {
|
||||
return ListUserDTO{}, nil
|
||||
}
|
||||
func (s *stubRoleRepo) ListStaff(context.Context, ListFilter) (ListUserDTO, error) {
|
||||
return ListUserDTO{}, nil
|
||||
}
|
||||
func (s *stubRoleRepo) GetByID(context.Context, int64) (UserDTO, error) { return UserDTO{}, nil }
|
||||
func (s *stubRoleRepo) GetByRole(context.Context, string, ListFilter) (ListUserDTO, error) {
|
||||
return ListUserDTO{}, nil
|
||||
}
|
||||
func (s *stubRoleRepo) Create(context.Context, CreateUserDTO) (UserDTO, error) { return UserDTO{}, nil }
|
||||
func (s *stubRoleRepo) Update(context.Context, int64, UpdateUserDTO) (UserDTO, error) {
|
||||
return UserDTO{}, nil
|
||||
}
|
||||
func (s *stubRoleRepo) Delete(context.Context, int64) error { return nil }
|
||||
func (s *stubRoleRepo) RoleGuardName(_ context.Context, code string) (string, error) {
|
||||
return s.guards[code], nil
|
||||
}
|
||||
|
||||
var _ Repository = (*stubRoleRepo)(nil)
|
||||
|
||||
func TestRoleAssignmentAllowed(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
// Mirrors db/seed.sql's roles table, plus a role added after this code
|
||||
// was written - to prove the check follows guard_name, not a hardcoded
|
||||
// list of role names.
|
||||
repo := &stubRoleRepo{guards: map[string]string{
|
||||
"user": "web",
|
||||
"operator": "operator",
|
||||
"admin": "admin",
|
||||
"superadmin": "admin",
|
||||
"manager": "admin",
|
||||
"currency_maintainer": "admin",
|
||||
"custom_branch_ops": "operator",
|
||||
}}
|
||||
h := &handler{repository: repo}
|
||||
|
||||
newContext := func(guard string) *gin.Context {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPut, "/", nil)
|
||||
if guard != "" {
|
||||
c.Set("guard", guard)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
admin := newContext("admin")
|
||||
for _, role := range []string{"", "user", "operator", "admin", "superadmin", "manager", "currency_maintainer", "unknown-role"} {
|
||||
allowed, err := h.roleAssignmentAllowed(admin, role)
|
||||
if err != nil {
|
||||
t.Fatalf("role %q: unexpected error %v", role, err)
|
||||
}
|
||||
if !allowed {
|
||||
t.Fatalf("admin guard should be able to assign role %q", role)
|
||||
}
|
||||
}
|
||||
|
||||
operator := newContext("operator")
|
||||
for _, role := range []string{"", "user", "operator", "USER", " Operator ", "custom_branch_ops"} {
|
||||
allowed, err := h.roleAssignmentAllowed(operator, role)
|
||||
if err != nil {
|
||||
t.Fatalf("role %q: unexpected error %v", role, err)
|
||||
}
|
||||
if !allowed {
|
||||
t.Fatalf("operator guard should be able to assign role %q", role)
|
||||
}
|
||||
}
|
||||
for _, role := range []string{"admin", "superadmin", "manager", "currency_maintainer", "unknown-role"} {
|
||||
allowed, err := h.roleAssignmentAllowed(operator, role)
|
||||
if err != nil {
|
||||
t.Fatalf("role %q: unexpected error %v", role, err)
|
||||
}
|
||||
if allowed {
|
||||
t.Fatalf("operator guard must not be able to assign role %q", role)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,26 @@
|
||||
package user
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
|
||||
"online-back/internal/identity/rbac"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListUserDTO, error)
|
||||
ListStaff(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)
|
||||
Create(ctx context.Context, dto CreateUserDTO, roleID int64) (UserDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateUserDTO, roleID int64) (UserDTO, error)
|
||||
SetRole(ctx context.Context, id, roleID int64) error
|
||||
Delete(ctx context.Context, id int64) error
|
||||
// RoleGuardName returns the guard_name of the role with the given code,
|
||||
// or "" if no such role exists.
|
||||
RoleGuardName(ctx context.Context, code string) (string, error)
|
||||
|
||||
// RoleByCode / RoleByID return nil when no live role matches.
|
||||
RoleByCode(ctx context.Context, code string) (*rbac.RoleInfo, error)
|
||||
RoleByID(ctx context.Context, id int64) (*rbac.RoleInfo, error)
|
||||
// RoleOfUser returns the user's current role, nil if the user is gone.
|
||||
RoleOfUser(ctx context.Context, userID int64) (*rbac.RoleInfo, error)
|
||||
// CountSuperUsers counts live users holding an is_super role.
|
||||
CountSuperUsers(ctx context.Context) (int64, error)
|
||||
}
|
||||
Reference in new issue
Block a user