ch some
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled

This commit is contained in:
2026-09-04 19:33:26 +05:00
parent 28509eb4ca
commit d1a6fcaadc
102 changed files with 2089 additions and 1957 deletions

View File

@@ -10,8 +10,10 @@ import (
"online-back/internal/identity/rbac"
"online-back/internal/identity/user"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
"golang.org/x/crypto/bcrypt"
@@ -55,6 +57,31 @@ const userBranchesJSON = `COALESCE((
) b
), '[]'::json)`
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)
FROM permissions p
WHERE NOT EXISTS (
SELECT 1 FROM permission_user pu
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny'
)
AND (
EXISTS (
SELECT 1 FROM permission_user pu
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow'
)
OR EXISTS (
SELECT 1 FROM permission_role pr
WHERE pr.role_id = r.id AND pr.permission_id = p.id
)
)
), '[]'::json)`
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...)
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
@@ -181,7 +208,7 @@ func appendNameSearch(conditions []string, args []interface{}, term string) ([]s
if term == "" {
return conditions, args
}
args = append(args, likePattern(term))
args = append(args, shared.LikePattern(term))
n := len(args)
conditions = append(conditions, fmt.Sprintf(
`(u.username ILIKE $%d OR u.first_name ILIKE $%d OR u.last_name ILIKE $%d OR CONCAT_WS(' ', u.first_name, u.last_name) ILIKE $%d)`,
@@ -190,13 +217,6 @@ func appendNameSearch(conditions []string, args []interface{}, term string) ([]s
return conditions, 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)
if len(filter.BranchIds) == 0 {
@@ -211,8 +231,8 @@ func (r *repository) GetByRole(ctx context.Context, role string, filter user.Lis
}
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
query := fmt.Sprintf(`SELECT %s, %s%s WHERE u.id = $1`, userColumns, userBranchesJSON, userFromClause)
item, err := scanStaffUser(r.client.QueryRow(ctx, query, id))
query := fmt.Sprintf(`SELECT %s, %s, %s%s WHERE u.id = $1`, userColumns, userBranchesJSON, userPermissionsJSON, userFromClause)
item, err := scanUserDetail(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return user.UserDTO{}, err
}
@@ -306,14 +326,16 @@ func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDT
}
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
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
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return guardName, err
}
func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error {
@@ -344,11 +366,7 @@ func roleIDByCode(ctx context.Context, tx pgx.Tx, roleCode string) *int64 {
return &id
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanUser(row scannable) (user.UserDTO, error) {
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,
@@ -359,7 +377,7 @@ func scanUser(row scannable) (user.UserDTO, error) {
return item, nil
}
func scanUserWithRoleID(row scannable) (user.UserDTO, error) {
func scanUserWithRoleID(row genericrepo.Scanner) (user.UserDTO, error) {
var item user.UserDTO
var roleID sql.NullInt64
var roleCode sql.NullString
@@ -373,7 +391,7 @@ func scanUserWithRoleID(row scannable) (user.UserDTO, error) {
return item, nil
}
func scanStaffUser(row scannable) (user.UserDTO, error) {
func scanStaffUser(row genericrepo.Scanner) (user.UserDTO, error) {
var item user.UserDTO
var roleID sql.NullInt64
var roleCode sql.NullString
@@ -385,16 +403,50 @@ func scanStaffUser(row scannable) (user.UserDTO, error) {
return user.UserDTO{}, err
}
applyJoinedRole(&item, roleID, roleCode)
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
item.Branches = []user.StaffBranchDTO{}
return item, nil
}
if err := json.Unmarshal(branchesJSON, &item.Branches); err != nil {
if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil {
return user.UserDTO{}, err
}
if item.Branches == nil {
item.Branches = []user.StaffBranchDTO{}
}
return item, nil
}
func scanUserDetail(row genericrepo.Scanner) (user.UserDTO, error) {
var item user.UserDTO
var roleID sql.NullInt64
var roleCode sql.NullString
var branchesJSON []byte
var permissionsJSON []byte
if err := row.Scan(
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
&item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, &branchesJSON, &permissionsJSON,
); err != nil {
return user.UserDTO{}, err
}
applyJoinedRole(&item, roleID, roleCode)
if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil {
return user.UserDTO{}, err
}
if err := unmarshalJSON(permissionsJSON, &item.Permissions); err != nil {
return user.UserDTO{}, err
}
if item.Branches == nil {
item.Branches = []user.StaffBranchDTO{}
}
if item.Permissions == nil {
item.Permissions = []user.UserPermissionDTO{}
}
return item, nil
}
func unmarshalJSON(raw []byte, dest interface{}) error {
if len(raw) == 0 || string(raw) == "null" {
return nil
}
return json.Unmarshal(raw, dest)
}
func applyJoinedRole(item *user.UserDTO, roleID sql.NullInt64, roleCode sql.NullString) {
if roleCode.Valid {
item.Role = roleCode.String

View File

@@ -14,21 +14,30 @@ type StaffBranchDTO struct {
Name LocalizedText `json:"name"`
}
type UserPermissionDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
GuardName string `json:"guardName"`
Module string `json:"module"`
}
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"`
Role string `json:"role"`
RoleId *int64 `json:"roleId,omitempty"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Branches []StaffBranchDTO `json:"branches,omitempty"`
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"`
Role string `json:"role"`
RoleId *int64 `json:"roleId,omitempty"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Branches []StaffBranchDTO `json:"branches,omitempty"`
Permissions []UserPermissionDTO `json:"permissions,omitempty"`
}
type CreateUserDTO struct {

View File

@@ -14,6 +14,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/config"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging"
minioUpload "online-back/pkg/minio"
@@ -79,6 +80,7 @@ func (h *handler) list(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
rbac.BindBranchIDs(c, &filter.BranchIds)
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
@@ -141,6 +143,7 @@ func (h *handler) listStaff(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
rbac.BindBranchIDs(c, &filter.BranchIds)
result, err := h.repository.ListStaff(c.Request.Context(), filter)
if err != nil {
@@ -154,7 +157,7 @@ func (h *handler) listStaff(c *gin.Context) {
// getByID godoc
// @Summary Get user by ID
// @Description Returns a single user with assigned branches and roleId
// @Description Returns a single user with assigned branches, roleId, and effective permissions
// @Tags user
// @Produce json
// @Security BearerAuth
@@ -165,7 +168,7 @@ func (h *handler) listStaff(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -207,6 +210,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)
return
} else if !allowed {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create user failed: %v", err)
@@ -232,7 +244,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -248,6 +260,15 @@ 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)
return
} else if !allowed {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
@@ -275,7 +296,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -297,24 +318,31 @@ func (h *handler) delete(c *gin.Context) {
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
// 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
}
return id, true
code := strings.ToLower(strings.TrimSpace(role))
if code == "" {
code = "user"
}
guardName, err := h.repository.RoleGuardName(c.Request.Context(), code)
if err != nil {
return false, err
}
return rbac.EffectiveGuard(code, guardName) != rbac.GuardAdmin, nil
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
Page: shared.DefaultPage,
Limit: shared.DefaultLimit,
}
if raw := c.Query("page"); raw != "" {
@@ -327,7 +355,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false
}
filter.Limit = limit
@@ -339,8 +367,6 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Search = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}

View File

@@ -0,0 +1,97 @@
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)
}
}
}

View File

@@ -10,4 +10,7 @@ type Repository interface {
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
// 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)
}