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

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -78,7 +79,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /activity-logs/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
// GET /activity-logs/card-orders → list that module instead of 400.
q := c.Request.URL.Query()
@@ -104,24 +105,10 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
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,
Page: shared.DefaultPage,
Limit: shared.DefaultLimit,
}
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
@@ -146,8 +133,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if err != nil || limit < 1 {
return ListFilter{}, false
}
if limit > maxLimit {
limit = maxLimit
if limit > shared.MaxLimit {
limit = shared.MaxLimit
}
filter.Limit = limit
}
@@ -169,7 +156,7 @@ func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
if raw == "" {
return nil, true
}
id, ok := parseID(raw)
id, ok := shared.ParseID(raw)
if !ok {
return nil, false
}

View File

@@ -7,6 +7,7 @@ import (
"sync"
"testing"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -61,7 +62,7 @@ func TestParseListFilterIgnoresUndefinedAndCapsLimit(t *testing.T) {
if filter.Module != "card-orders" {
t.Fatalf("module=%q", filter.Module)
}
if filter.Limit != maxLimit {
if filter.Limit != shared.MaxLimit {
t.Fatalf("limit=%d", filter.Limit)
}
if filter.Page != 2 {
@@ -90,7 +91,7 @@ func TestGetByIDListsModuleWhenPathIsNotNumeric(t *testing.T) {
if repo.listFilter.Module != "card-orders" {
t.Fatalf("module=%q", repo.listFilter.Module)
}
if repo.listFilter.Limit != maxLimit {
if repo.listFilter.Limit != shared.MaxLimit {
t.Fatalf("limit=%d", repo.listFilter.Limit)
}
}

View File

@@ -11,6 +11,7 @@ import (
"online-back/internal/identity/auth"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
@@ -71,15 +72,29 @@ const profilePermissionsJSON = `COALESCE((
SELECT json_agg(jsonb_build_object(
'id', p.id,
'code', COALESCE(p.code, ''),
'name', p.name
) ORDER BY p.id)
FROM permission_role pr
JOIN permissions p ON p.id = pr.permission_id
WHERE pr.role_id = r.id
'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)`
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at,
r.id, r.code, r.name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1`
r.id, r.code, r.name, r.guard_name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1`
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
phone := strings.TrimSpace(dto.Phone)
@@ -127,14 +142,10 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
return r.GetProfile(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanProfile(row scannable) (auth.UserProfileDTO, error) {
func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
var roleID sql.NullInt64
var roleCode, roleName sql.NullString
var roleCode, roleName, roleGuard sql.NullString
var branchesJSON []byte
var permissionsJSON []byte
@@ -149,6 +160,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
&roleID,
&roleCode,
&roleName,
&roleGuard,
&branchesJSON,
&permissionsJSON,
)
@@ -158,9 +170,10 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
if roleID.Valid {
profile.Role = &auth.ProfileRoleDTO{
Id: roleID.Int64,
Code: roleCode.String,
Name: roleName.String,
Id: roleID.Int64,
Code: roleCode.String,
Name: roleName.String,
GuardName: roleGuard.String,
}
}
@@ -177,6 +190,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
return auth.UserProfileDTO{}, err
}
}
profile.Modules = auth.GroupProfileModules(profile.Permissions)
return profile, nil
}

View File

@@ -19,9 +19,10 @@ type LocalizedText struct {
}
type ProfileRoleDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
GuardName string `json:"guardName"`
}
type ProfileBranchDTO struct {
@@ -31,9 +32,16 @@ type ProfileBranchDTO struct {
}
type ProfilePermissionDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
GuardName string `json:"guardName"`
Module string `json:"module"`
}
type ProfileModuleDTO struct {
Module string `json:"module"`
Permissions []ProfilePermissionDTO `json:"permissions"`
}
type UserProfileDTO struct {
@@ -45,6 +53,7 @@ type UserProfileDTO struct {
Avatar string `json:"avatar"`
Role *ProfileRoleDTO `json:"role"`
Branches []ProfileBranchDTO `json:"branches"`
Modules []ProfileModuleDTO `json:"modules"`
Permissions []ProfilePermissionDTO `json:"permissions"`
CreatedAt time.Time `json:"createdAt"`
}

View File

@@ -242,7 +242,7 @@ func (h *handler) refreshToken(c *gin.Context) {
// getProfile godoc
// @Summary Get profile
// @Description Returns the authenticated user's profile with role, branches, and permissions
// @Description Returns the authenticated user's profile with role, branches, and permissions grouped by saha (module)
// @Tags auth
// @Produce json
// @Security BearerAuth

View File

@@ -0,0 +1,37 @@
package auth
import (
"sort"
"online-back/internal/identity/permission"
)
func GroupProfileModules(perms []ProfilePermissionDTO) []ProfileModuleDTO {
buckets := make(map[string][]ProfilePermissionDTO)
seen := make(map[string]struct{})
for _, p := range perms {
module := p.Module
buckets[module] = append(buckets[module], p)
seen[module] = struct{}{}
}
modules := make([]ProfileModuleDTO, 0, len(seen))
for _, name := range permission.ModuleOrder() {
ps, ok := buckets[name]
if !ok {
continue
}
modules = append(modules, ProfileModuleDTO{Module: name, Permissions: ps})
delete(seen, name)
}
var extra []string
for name := range seen {
extra = append(extra, name)
}
sort.Strings(extra)
for _, name := range extra {
modules = append(modules, ProfileModuleDTO{Module: name, Permissions: buckets[name]})
}
return modules
}

View File

@@ -7,6 +7,7 @@ import (
"strings"
"online-back/internal/identity/permission"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -28,9 +29,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) permission.
}
}
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.module, p.created_at, p.updated_at`
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
const permissionReturningColumns = `id, code, name, guard_name, module, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
whereClause, args := buildListQuery(filter)
@@ -46,10 +47,18 @@ func (r *repository) List(ctx context.Context, filter permission.ListFilter) (pe
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.PermissionName != "" {
args = append(args, likePattern(filter.PermissionName))
args = append(args, shared.LikePattern(filter.PermissionName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n))
}
if filter.GuardName != "" {
args = append(args, filter.GuardName)
conditions = append(conditions, fmt.Sprintf(`p.guard_name = $%d`, len(args)))
}
if filter.Module != "" {
args = append(args, filter.Module)
conditions = append(conditions, fmt.Sprintf(`p.module = $%d`, len(args)))
}
if len(conditions) == 0 {
return "", args
@@ -58,35 +67,57 @@ func buildListQuery(filter permission.ListFilter) (whereClause string, args []in
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) Tree(ctx context.Context, guardName string) (permission.PermissionTreeDTO, error) {
query := `SELECT ` + permissionColumns + ` FROM permissions p`
var args []interface{}
if guardName != "" {
query += ` WHERE p.guard_name = $1`
args = append(args, guardName)
}
query += ` ORDER BY p.guard_name, p.module, p.id`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return permission.PermissionTreeDTO{}, err
}
defer rows.Close()
var items []permission.PermissionDTO
for rows.Next() {
item, err := scanPermission(rows)
if err != nil {
return permission.PermissionTreeDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return permission.PermissionTreeDTO{}, err
}
return permission.BuildTree(items), nil
}
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)
INSERT INTO permissions (code, name, guard_name, module)
VALUES ($1, $2, $3, $4)
RETURNING %s`, permissionReturningColumns)
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module))
}
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,
code = $1, name = $2, guard_name = $3, module = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $4
WHERE id = $5
RETURNING %s`, permissionReturningColumns)
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module, id))
if errors.Is(err, pgx.ErrNoRows) {
return permission.PermissionDTO{}, err
}
@@ -100,7 +131,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
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,
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.Module, &item.CreatedAt, &item.UpdatedAt,
); err != nil {
return permission.PermissionDTO{}, err
}

View File

@@ -7,24 +7,29 @@ type PermissionDTO struct {
Code string `json:"code"`
Name string `json:"name"`
GuardName string `json:"guardName"`
Module string `json:"module"`
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"`
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
Module string `json:"module" binding:"required"`
}
type UpdatePermissionDTO struct {
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"`
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
Module string `json:"module" binding:"required"`
}
type ListFilter struct {
PermissionName string
GuardName string
Module string
Page int
Limit int
}
@@ -33,3 +38,17 @@ type ListPermissionDTO struct {
Count int64 `json:"count"`
Permissions []PermissionDTO `json:"permissions"`
}
type PermissionTreeDTO struct {
Guards []GuardModulesDTO `json:"guards"`
}
type GuardModulesDTO struct {
GuardName string `json:"guardName"`
Modules []ModulePermissionsDTO `json:"modules"`
}
type ModulePermissionsDTO struct {
Module string `json:"module"`
Permissions []PermissionDTO `json:"permissions"`
}

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -28,6 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.GET("/tree", h.tree)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
@@ -41,6 +43,8 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Produce json
// @Security BearerAuth
// @Param permission_name query string false "Filter by name"
// @Param guard_name query string false "Filter by guard (web, operator, admin)"
// @Param module query string false "Filter by saha (cards, loans, …)"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
@@ -64,6 +68,32 @@ func (h *handler) list(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// tree godoc
// @Summary Permission tree
// @Description Returns permissions grouped as guard → module (saha) → permissions
// @Tags permission
// @Produce json
// @Security BearerAuth
// @Param guard_name query string false "Filter by guard (web, operator, admin)"
// @Success 200 {object} appresult.AppSuccess
// @Failure 500 {object} appresult.AppError
// @Router /permissions/tree [get]
func (h *handler) tree(c *gin.Context) {
guardName := strings.TrimSpace(c.Query("guard_name"))
if guardName == "" {
guardName = strings.TrimSpace(c.Query("guardName"))
}
result, err := h.repository.Tree(c.Request.Context(), guardName)
if err != nil {
h.logger.Errorf("permission tree 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
@@ -77,7 +107,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /permissions/{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
@@ -115,6 +145,10 @@ func (h *handler) create(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !IsKnownModule(dto.Module) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
@@ -141,7 +175,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /permissions/{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
@@ -152,6 +186,10 @@ func (h *handler) update(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !IsKnownModule(dto.Module) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
@@ -180,7 +218,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /permissions/{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
@@ -198,24 +236,10 @@ func (h *handler) delete(c *gin.Context) {
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,
Page: shared.DefaultPage,
Limit: shared.DefaultLimit,
}
if raw := c.Query("page"); raw != "" {
@@ -228,7 +252,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
@@ -237,6 +261,24 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := strings.TrimSpace(c.Query("permission_name")); raw != "" {
filter.PermissionName = raw
}
if raw := firstQuery(c, "guard_name", "guardName"); raw != "" {
filter.GuardName = raw
}
if raw := firstQuery(c, "module"); raw != "" {
filter.Module = raw
}
return filter, true
}
func firstQuery(c *gin.Context, keys ...string) string {
for _, key := range keys {
if key == "" {
continue
}
if raw := strings.TrimSpace(c.Query(key)); raw != "" {
return raw
}
}
return ""
}

View File

@@ -0,0 +1,54 @@
package permission
const (
ModuleDashboard = "dashboard"
ModuleCards = "cards"
ModuleLoans = "loans"
ModuleUsers = "users"
ModuleRoles = "roles"
ModuleBranches = "branches"
ModuleProvinces = "provinces"
ModuleActivityLogs = "activity-logs"
ModuleBackups = "backups"
ModuleCurrencies = "currencies"
)
var moduleOrder = []string{
ModuleDashboard,
ModuleCards,
ModuleLoans,
ModuleUsers,
ModuleRoles,
ModuleBranches,
ModuleProvinces,
ModuleActivityLogs,
ModuleBackups,
ModuleCurrencies,
}
var guardOrder = []string{"operator", "admin", "web"}
var knownModules = map[string]struct{}{
ModuleDashboard: {},
ModuleCards: {},
ModuleLoans: {},
ModuleUsers: {},
ModuleRoles: {},
ModuleBranches: {},
ModuleProvinces: {},
ModuleActivityLogs: {},
ModuleBackups: {},
ModuleCurrencies: {},
}
func IsKnownModule(module string) bool {
_, ok := knownModules[module]
return ok
}
// ModuleOrder is the display order of sahalar in trees and profile.
func ModuleOrder() []string {
out := make([]string, len(moduleOrder))
copy(out, moduleOrder)
return out
}

View File

@@ -4,6 +4,7 @@ import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error)
Tree(ctx context.Context, guardName string) (PermissionTreeDTO, 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)

View File

@@ -0,0 +1,67 @@
package permission
import "sort"
type treeKey struct {
guard string
module string
}
// BuildTree groups a flat permission list into guard → module → permissions
// so the admin UI can render sahalar (cards, loans, …) as a tree.
func BuildTree(items []PermissionDTO) PermissionTreeDTO {
buckets := make(map[treeKey][]PermissionDTO)
guardsSeen := make(map[string]struct{})
modulesByGuard := make(map[string]map[string]struct{})
for _, item := range items {
key := treeKey{guard: item.GuardName, module: item.Module}
buckets[key] = append(buckets[key], item)
guardsSeen[item.GuardName] = struct{}{}
if modulesByGuard[item.GuardName] == nil {
modulesByGuard[item.GuardName] = make(map[string]struct{})
}
modulesByGuard[item.GuardName][item.Module] = struct{}{}
}
guards := make([]GuardModulesDTO, 0, len(guardsSeen))
for _, guard := range orderedKeys(guardOrder, guardsSeen) {
modulesSeen := modulesByGuard[guard]
modules := make([]ModulePermissionsDTO, 0, len(modulesSeen))
for _, module := range orderedKeys(moduleOrder, modulesSeen) {
perms := buckets[treeKey{guard: guard, module: module}]
if perms == nil {
perms = []PermissionDTO{}
}
modules = append(modules, ModulePermissionsDTO{
Module: module,
Permissions: perms,
})
}
guards = append(guards, GuardModulesDTO{
GuardName: guard,
Modules: modules,
})
}
return PermissionTreeDTO{Guards: guards}
}
func orderedKeys(order []string, seen map[string]struct{}) []string {
keys := make([]string, 0, len(seen))
used := make(map[string]struct{}, len(seen))
for _, name := range order {
if _, ok := seen[name]; ok {
keys = append(keys, name)
used[name] = struct{}{}
}
}
var extra []string
for name := range seen {
if _, ok := used[name]; !ok {
extra = append(extra, name)
}
}
sort.Strings(extra)
return append(keys, extra...)
}

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/identity/permissionrole"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
@@ -39,21 +40,10 @@ func (r *repository) Create(ctx context.Context, dto permissionrole.CreatePermis
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM permission_role WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return genericrepo.Delete(ctx, r.client, "permission_role", id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPermissionRole(row scannable) (permissionrole.PermissionRoleDTO, error) {
func scanPermissionRole(row genericrepo.Scanner) (permissionrole.PermissionRoleDTO, error) {
var item permissionrole.PermissionRoleDTO
err := row.Scan(

View File

@@ -1,16 +1,12 @@
package permissionrole
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/permission-roles"
@@ -43,20 +39,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Failure 500 {object} appresult.AppError
// @Router /permission-roles [post]
func (h *handler) create(c *gin.Context) {
var dto CreatePermissionRoleDTO
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 role failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
shared.CreateAssoc[CreatePermissionRoleDTO, PermissionRoleDTO](c, h.logger, h.repository, "permission role")
}
// delete godoc
@@ -72,28 +55,5 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /permission-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 permission role failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("permission 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
shared.DeleteAssoc[CreatePermissionRoleDTO, PermissionRoleDTO](c, h.logger, h.repository, "permission role")
}

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/identity/permissionuser"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
@@ -40,21 +41,10 @@ func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermis
}
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
return genericrepo.Delete(ctx, r.client, "permission_user", id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) {
func scanPermissionUser(row genericrepo.Scanner) (permissionuser.PermissionUserDTO, error) {
var item permissionuser.PermissionUserDTO
err := row.Scan(

View File

@@ -1,16 +1,12 @@
package permissionuser
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/permission-users"
@@ -43,20 +39,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @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))
shared.CreateAssoc[CreatePermissionUserDTO, PermissionUserDTO](c, h.logger, h.repository, "permission user")
}
// delete godoc
@@ -72,28 +55,5 @@ func (h *handler) create(c *gin.Context) {
// @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
shared.DeleteAssoc[CreatePermissionUserDTO, PermissionUserDTO](c, h.logger, h.repository, "permission user")
}

View File

@@ -10,9 +10,11 @@ import (
"online-back/internal/appresult"
"online-back/internal/config"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"github.com/sirupsen/logrus"
)
const (
@@ -109,15 +111,27 @@ func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
c.Set(contextBranchIDs, ids)
if !operatorRoleAllows(c.Request.Method, c.Request.URL.Path) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
abortForbidden(c, "route not in operator allow-list", logrus.Fields{"userId": userID})
return
}
if !operatorProfileOrFile(c.Request.URL.Path) && len(ids) == 0 {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
if !operatorProfileOrFile(c.Request.URL.Path) && !operatorClientsList(c.Request.URL.Path) && len(ids) == 0 {
abortForbidden(c, "operator has no assigned branches", logrus.Fields{"userId": userID})
return
}
if perm := operatorPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" {
granted, err := service.HasPermission(c.Request.Context(), userID, perm)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !granted {
abortForbidden(c, "missing permission for operator path", logrus.Fields{"userId": userID, "permission": perm})
return
}
}
if !operatorWriteAllowed(c, service, ids) {
return
}
@@ -125,6 +139,31 @@ func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
c.Next()
}
// abortForbidden logs why a request was denied (method, path, and any extra
// fields the caller passes) before writing the 403, since appresult.ErrForbidden
// alone gives the client and the logs no way to tell which rbac check failed.
func abortForbidden(c *gin.Context, reason string, fields logrus.Fields) {
entry := logging.GetLogger().WithFields(logrus.Fields{
"method": c.Request.Method,
"path": c.Request.URL.Path,
})
for k, v := range fields {
entry = entry.WithField(k, v)
}
entry.Warn("rbac forbidden: " + reason)
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
}
// EffectiveGuard resolves the guard a role with the given code/guard_name
// would run requests under - the same resolution Guard() applies to the
// caller on every request. Exposed so callers that grant a role (e.g. the
// user handler) can ask "would this reach guardAdmin?" against the role's
// real guard_name instead of matching against a hardcoded list of role
// names, which drifts the moment a new role is added.
func EffectiveGuard(code, guardName string) string {
return effectiveGuard(code, guardName)
}
func effectiveGuard(code, guardName string) string {
code = strings.ToLower(strings.TrimSpace(code))
guard := strings.ToLower(strings.TrimSpace(guardName))
@@ -132,7 +171,7 @@ func effectiveGuard(code, guardName string) string {
switch code {
case "admin", "superadmin", "manager":
return guardAdmin
case roleOperator:
case roleOperator, "operatot":
return guardOperator
}
@@ -220,6 +259,8 @@ func enforceOwnWrites(c *gin.Context, userID int64) bool {
}
payload["userId"] = userID
payload["user_id"] = userID
payload["createdBy"] = userID
payload["created_by"] = userID
rewritten, err := json.Marshal(payload)
if err != nil {
return true
@@ -251,6 +292,7 @@ func scopeOwnedLists(c *gin.Context, userID int64) {
query := c.Request.URL.Query()
query.Set("user_id", strconv.FormatInt(userID, 10))
query.Set("created_by", strconv.FormatInt(userID, 10))
c.Request.URL.RawQuery = query.Encode()
}
@@ -319,6 +361,9 @@ var userCatalogPrefixes = []string{
"/loan-types",
"/loans-documents",
"/currencies",
"/branches",
"/provinces",
"/users/clients",
}
var userSelfPrefixes = []string{
@@ -328,6 +373,7 @@ var userSelfPrefixes = []string{
var userOwnedPrefixes = []string{
"/cards",
"/card-balances",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
@@ -362,6 +408,11 @@ func operatorProfileOrFile(path string) bool {
return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/")
}
func operatorClientsList(path string) bool {
rest := adminREST(path)
return rest == "/users/clients" || strings.HasPrefix(rest, "/users/clients/")
}
func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64) bool {
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
@@ -391,9 +442,21 @@ func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64)
}
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
abortForbidden(c, "payload branchId not in operator's assigned branches", logrus.Fields{
"requestedBranchId": *payload.BranchId,
"allowedBranchIds": branchIDs,
})
return false
}
// A new order's customer has no prior record in the branch to be
// "visible" through yet — the branchId check above already scopes the
// create to the operator's own branch, so only enforce user visibility
// when reassigning an existing record (PUT/PATCH).
if c.Request.Method == http.MethodPost {
return true
}
if payload.UserId != nil && *payload.UserId > 0 {
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
if err != nil {
@@ -401,7 +464,10 @@ func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64)
return false
}
if !visible {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
abortForbidden(c, "payload userId not visible in operator's branches", logrus.Fields{
"requestedUserId": *payload.UserId,
"allowedBranchIds": branchIDs,
})
return false
}
}
@@ -419,19 +485,65 @@ func adminREST(path string) string {
return rest
}
// operatorPathPermission returns "cards" or "loans" for saha endpoints.
// Empty string: shared catalog (profile, file, dashboard, branches, provinces,
// users/clients, currencies read) — any operator may call it.
func operatorPathPermission(method, path string) string {
rest := adminREST(path)
switch {
case matchesPrefix(rest, []string{
"/cards",
"/card-balances",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/payment-cards",
"/reasons-cards",
}):
return "cards"
case matchesPrefix(rest, []string{
"/loan-orders",
"/loans-repayment",
"/loan-paid-off-letters",
"/loan-types",
"/loans-documents",
}):
return "loans"
case matchesPrefix(rest, []string{"/users/clients"}):
return ""
case matchesPrefix(rest, []string{"/users", "/branch-users"}):
if method == http.MethodGet {
return "users.view"
}
return "users.manage"
}
return ""
}
var operatorWritePrefixes = []string{
"/profile",
"/file",
"/users",
"/branch-users",
"/cards",
"/card-balances",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/payment-cards",
"/reasons-cards",
"/loan-orders",
"/loans-repayment",
"/loan-paid-off-letters",
"/loan-types",
"/loans-documents",
}
var operatorGetPrefixes = []string{
@@ -440,6 +552,7 @@ var operatorGetPrefixes = []string{
"/dashboard",
"/users",
"/cards",
"/card-balances",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",

View File

@@ -35,14 +35,22 @@ func TestUserRoleAllows(t *testing.T) {
{http.MethodPost, "/api/admin/card-orders", true},
{http.MethodPut, "/api/admin/loan-orders/2", true},
{http.MethodDelete, "/api/admin/loan-orders/2", true},
{http.MethodGet, "/api/admin/card-balances", false},
{http.MethodGet, "/api/admin/card-balances", true},
{http.MethodPost, "/api/admin/card-balances", true},
{http.MethodPut, "/api/admin/card-balances/9", true},
{http.MethodDelete, "/api/admin/card-balances/9", true},
{http.MethodGet, "/api/admin/profile", true},
{http.MethodPut, "/api/admin/profile", true},
{http.MethodPost, "/api/admin/file", true},
{http.MethodDelete, "/api/admin/profile", false},
{http.MethodGet, "/api/admin/users", false},
{http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/provinces", true},
{http.MethodPost, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/branches", true},
{http.MethodPost, "/api/admin/branches", false},
{http.MethodGet, "/api/admin/users/clients", true},
{http.MethodPost, "/api/admin/users", false},
{http.MethodGet, "/api/admin/loan-types", true},
{http.MethodPost, "/api/admin/loan-types", false},
{http.MethodPost, "/api/admin/loan-orders", true},
@@ -75,11 +83,13 @@ func TestOperatorRoleAllows(t *testing.T) {
{http.MethodDelete, "/api/admin/card-orders/2", true},
{http.MethodGet, "/api/admin/dashboard", true},
{http.MethodGet, "/api/admin/users", true},
{http.MethodGet, "/api/admin/users/clients", true},
{http.MethodPost, "/api/admin/users", true},
{http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", true},
{http.MethodPost, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/card-balances", false},
{http.MethodGet, "/api/admin/card-balances", true},
{http.MethodPost, "/api/admin/card-balances", true},
}
for _, tt := range tests {
if got := operatorRoleAllows(tt.method, tt.path); got != tt.want {
@@ -88,12 +98,124 @@ func TestOperatorRoleAllows(t *testing.T) {
}
}
func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) {
if userRoleAllows(http.MethodGet, "/api/admin/card-balances") {
t.Fatal("/cards must not grant /card-balances")
func TestOperatorClientsListNeedsNoPermission(t *testing.T) {
if got := operatorPathPermission(http.MethodGet, "/api/admin/users/clients"); got != "" {
t.Fatalf("clients GET perm=%q, want none", got)
}
if operatorRoleAllows(http.MethodGet, "/api/admin/card-balances") {
t.Fatal("operator /cards must not grant /card-balances")
if got := operatorPathPermission(http.MethodGet, "/api/admin/users"); got != "users.view" {
t.Fatalf("users GET perm=%q, want users.view", got)
}
auth := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{}}
if status := serveGuard(auth, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK {
t.Fatalf("clients status=%d", status)
}
if status := serveGuard(auth, http.MethodGet, "/api/admin/users", "7", nil); status != http.StatusForbidden {
t.Fatalf("users list status=%d", status)
}
noBranch := &stubAuth{role: roleOperator, perms: map[string]bool{}}
if status := serveGuard(noBranch, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK {
t.Fatalf("no-branch clients status=%d", status)
}
}
func TestOperatorCardsAndLoansSahalar(t *testing.T) {
cardsOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true}}
loansOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"loans": true}}
both := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true, "loans": true}}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
t.Fatalf("cards GET orders=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodPost, "/api/admin/card-pin-orders", "7", nil); status != http.StatusOK {
t.Fatalf("cards POST pin=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/visa-master-payment-orders", "7", nil); status != http.StatusOK {
t.Fatalf("cards GET visa=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusForbidden {
t.Fatalf("cards GET loans=%d", status)
}
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK {
t.Fatalf("loans GET orders=%d", status)
}
if status := serveGuard(loansOnly, http.MethodPut, "/api/admin/loan-paid-off-letters/1", "7", nil); status != http.StatusOK {
t.Fatalf("loans PUT letter=%d", status)
}
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusForbidden {
t.Fatalf("loans GET cards=%d", status)
}
if status := serveGuard(both, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
t.Fatalf("both GET cards=%d", status)
}
if status := serveGuard(both, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK {
t.Fatalf("both GET loans=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusOK {
t.Fatalf("cards GET balances=%d", status)
}
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusForbidden {
t.Fatalf("loans GET balances=%d", status)
}
if got := operatorPathPermission(http.MethodGet, "/api/admin/card-balances"); got != "cards" {
t.Fatalf("card-balances path=%q", got)
}
if got := operatorPathPermission(http.MethodPost, "/api/admin/card-orders"); got != "cards" {
t.Fatalf("card-orders path=%q", got)
}
}
func TestAllCardAndLoanRoutesMapped(t *testing.T) {
cardPaths := []string{
"/api/admin/cards",
"/api/admin/card-balances",
"/api/admin/card-orders",
"/api/admin/card-pin-orders",
"/api/admin/card-rekwizit-orders",
"/api/admin/visa-master-payment-orders",
"/api/admin/payment-cards",
"/api/admin/reasons-cards",
}
loanPaths := []string{
"/api/admin/loan-orders",
"/api/admin/loans-repayment",
"/api/admin/loan-paid-off-letters",
"/api/admin/loan-types",
"/api/admin/loans-documents",
}
for _, path := range cardPaths {
if got := operatorPathPermission(http.MethodGet, path); got != "cards" {
t.Errorf("GET %s perm=%q, want cards", path, got)
}
if got := operatorPathPermission(http.MethodPost, path); got != "cards" {
t.Errorf("POST %s perm=%q, want cards", path, got)
}
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
t.Errorf("%s not on operator allowlist", path)
}
}
for _, path := range loanPaths {
if got := operatorPathPermission(http.MethodGet, path); got != "loans" {
t.Errorf("GET %s perm=%q, want loans", path, got)
}
if got := operatorPathPermission(http.MethodPost, path); got != "loans" {
t.Errorf("POST %s perm=%q, want loans", path, got)
}
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
t.Errorf("%s not on operator allowlist", path)
}
}
}
func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) {
if matchesPrefix("/card-balances", []string{"/cards"}) {
t.Fatal("/cards prefix must not match /card-balances")
}
if !matchesPrefix("/card-balances", userOwnedPrefixes) {
t.Fatal("/card-balances must be granted via its own entry in userOwnedPrefixes")
}
}
@@ -139,6 +261,7 @@ func TestScopeOwnedListsInjectsUserID(t *testing.T) {
"/api/admin/loan-orders",
"/api/admin/loans-repayment",
"/api/admin/loan-paid-off-letters",
"/api/admin/card-balances",
}
for _, path := range paths {
w := httptest.NewRecorder()
@@ -151,6 +274,21 @@ func TestScopeOwnedListsInjectsUserID(t *testing.T) {
}
}
func TestScopeOwnedListsInjectsCreatedByForCardBalances(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/card-balances?status=pending", nil)
scopeOwnedLists(c, 42)
if got := c.Request.URL.Query().Get("created_by"); got != "42" {
t.Fatalf("card-balances created_by=%q, want 42", got)
}
if got := c.Request.URL.Query().Get("status"); got != "pending" {
t.Fatalf("existing query params must be preserved, status=%q", got)
}
}
func TestScopeOwnedListsSkipsReferenceData(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
@@ -182,10 +320,17 @@ func TestGuardMatrix(t *testing.T) {
{"user PUT card-orders", roleUser, nil, http.MethodPut, "/api/admin/card-orders/3", http.StatusOK},
{"user DELETE loan-orders", roleUser, nil, http.MethodDelete, "/api/admin/loan-orders/3", http.StatusOK},
{"user PATCH cards", roleUser, nil, http.MethodPatch, "/api/admin/cards/3", http.StatusOK},
{"user GET card-balances", roleUser, nil, http.MethodGet, "/api/admin/card-balances", http.StatusOK},
{"user POST card-balances", roleUser, nil, http.MethodPost, "/api/admin/card-balances", http.StatusOK},
{"user DELETE card-balances", roleUser, nil, http.MethodDelete, "/api/admin/card-balances/3", http.StatusOK},
{"user POST loans-repayment", roleUser, nil, http.MethodPost, "/api/admin/loans-repayment", http.StatusOK},
{"user PUT profile", roleUser, nil, http.MethodPut, "/api/admin/profile", http.StatusOK},
{"user POST file", roleUser, nil, http.MethodPost, "/api/admin/file", http.StatusOK},
{"user GET users", roleUser, nil, http.MethodGet, "/api/admin/users", http.StatusForbidden},
{"user GET users/clients", roleUser, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK},
{"user GET branches", roleUser, nil, http.MethodGet, "/api/admin/branches", http.StatusOK},
{"user GET provinces", roleUser, nil, http.MethodGet, "/api/admin/provinces", http.StatusOK},
{"user POST branches", roleUser, nil, http.MethodPost, "/api/admin/branches", http.StatusForbidden},
{"no-role GET currencies", "", nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"no-role GET backups", "", nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
@@ -196,6 +341,7 @@ func TestGuardMatrix(t *testing.T) {
{"operator POST card-orders", roleOperator, []int64{1}, http.MethodPost, "/api/admin/card-orders", http.StatusOK},
{"operator no branch GET currencies", roleOperator, nil, http.MethodGet, "/api/admin/currencies", http.StatusForbidden},
{"operator no branch GET profile", roleOperator, nil, http.MethodGet, "/api/admin/profile", http.StatusOK},
{"operator no branch GET users/clients", roleOperator, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK},
{"admin GET backups", "admin", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
{"admin POST currencies", "admin", nil, http.MethodPost, "/api/admin/currencies", http.StatusOK},
@@ -289,9 +435,17 @@ func TestOperatorWriteAllowedUserVisibility(t *testing.T) {
t.Fatalf("visible user status=%d", status)
}
// Creating a brand-new order for a customer who has no prior record in
// the branch must still succeed — the branchId check alone scopes a
// create to the operator's own branch.
hidden := &stubAuth{role: roleOperator, branches: []int64{1}, visible: false}
if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden {
t.Fatalf("hidden user status=%d", status)
if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK {
t.Fatalf("new customer create status=%d", status)
}
// Reassigning an existing order's customer still enforces visibility.
if status := serveGuard(hidden, http.MethodPut, "/api/admin/card-orders/1", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden {
t.Fatalf("update hidden user status=%d", status)
}
}
@@ -349,6 +503,40 @@ func TestAllowsBranchAndGuardUser(t *testing.T) {
}
}
func TestGuardNewBranchAssignment(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
// No branch scope (admin caller): always allowed.
if !GuardNewBranchAssignment(c, 42) {
t.Fatal("admin caller should be able to assign any user")
}
// Operator scoped to branch 1.
c.Set(contextBranchIDs, []int64{1})
// Target has no existing branch: first-time assignment is allowed.
c.Set(contextService, &stubAuth{branches: nil})
if !GuardNewBranchAssignment(c, 42) {
t.Fatal("unbranched target should be assignable")
}
// Target already belongs to the operator's own branch: no-op re-assignment is allowed.
c.Set(contextService, &stubAuth{branches: []int64{1}})
if !GuardNewBranchAssignment(c, 42) {
t.Fatal("target already in caller's branch should be assignable")
}
// Target belongs to a different branch: reject cross-branch poaching.
c.Set(contextService, &stubAuth{branches: []int64{2}})
if GuardNewBranchAssignment(c, 42) {
t.Fatal("target from a foreign branch must not be assignable")
}
}
func TestBindBranchIDs(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
@@ -402,12 +590,13 @@ func TestUserInBranchSQLIncludesNewOrderTables(t *testing.T) {
for _, table := range []string{
"branch_user", "card_orders", "loan_orders", "card_pin_orders",
"card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters",
"card_balances",
} {
if !strings.Contains(sql, table) {
t.Errorf("missing %s", table)
}
}
if strings.Count(sql, "$3") != 7 {
if strings.Count(sql, "$3") != 8 {
t.Fatalf("$3 count=%d", strings.Count(sql, "$3"))
}
}
@@ -460,6 +649,9 @@ func (s *stubAuth) BranchIDs(context.Context, int64) ([]int64, error) {
}
func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool, error) {
if s.perms == nil {
return true, nil
}
return s.perms[code], nil
}
@@ -486,6 +678,7 @@ func TestEffectiveGuard(t *testing.T) {
{"", "", guardWeb},
{roleOperator, guardAdmin, guardOperator},
{roleOperator, guardWeb, guardOperator},
{"operatot", guardWeb, guardOperator},
{"superadmin", guardWeb, guardAdmin},
{"admin", guardWeb, guardAdmin},
{"manager", guardOperator, guardAdmin},
@@ -548,6 +741,34 @@ func TestEnforceOwnWritesRewritesUserID(t *testing.T) {
}
}
func TestEnforceOwnWritesRewritesCreatedByForCardBalances(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", "7")
c.Next()
})
r.Use(Guard(&stubAuth{role: roleUser}))
r.POST("/api/admin/card-balances", func(c *gin.Context) {
body, _ := io.ReadAll(c.Request.Body)
c.String(http.StatusOK, string(body))
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/admin/card-balances", bytes.NewReader([]byte(`{"createdBy":99,"cardNumber":"4111111111111111"}`)))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d", w.Code)
}
if !strings.Contains(w.Body.String(), `"createdBy":7`) {
t.Fatalf("createdBy not rewritten: %s", w.Body.String())
}
if !strings.Contains(w.Body.String(), `"created_by":7`) {
t.Fatalf("created_by not rewritten: %s", w.Body.String())
}
}
func TestGuardOwnedOwnScope(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()

View File

@@ -9,6 +9,14 @@ import (
"github.com/gin-gonic/gin"
)
// The three valid guard names. Use these constants when validating
// the guardName field in role/permission DTOs.
const (
GuardWeb = guardWeb
GuardOperator = guardOperator
GuardAdmin = guardAdmin
)
const (
contextBranchIDs = "branchIds"
contextService = "rbacService"
@@ -43,6 +51,10 @@ func IsOwnScope(c *gin.Context) bool {
return GuardFrom(c) == guardWeb
}
func IsAdminGuard(c *gin.Context) bool {
return GuardFrom(c) == guardAdmin
}
func SkipRecordGuard(c *gin.Context) bool {
return !HasBranchScope(c) && !IsOwnScope(c)
}
@@ -94,6 +106,40 @@ func GuardBranch(c *gin.Context, branchID int64) bool {
return false
}
// GuardNewBranchAssignment guards POST /branch-users: a branch-scoped caller
// may only assign a user who is unbranched or already in one of their own
// branches. Without this, an operator holding users.manage could pull
// another branch's operator into their own branch — the destination-branch
// check alone doesn't catch that, since it never looks at the target's
// current branch.
func GuardNewBranchAssignment(c *gin.Context, targetUserID int64) bool {
if !HasBranchScope(c) {
return true
}
raw, ok := c.Get(contextService)
if !ok {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
service, _ := raw.(Authorizer)
if service == nil {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
currentBranches, err := service.BranchIDs(c.Request.Context(), targetUserID)
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
for _, branchID := range currentBranches {
if !AllowsBranch(c, branchID) {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
}
return true
}
func GuardUser(c *gin.Context, userID int64) bool {
if IsOwnScope(c) {
id := userID
@@ -139,7 +185,8 @@ func UserInBranchSQL(userExpr string, placeholder int) string {
OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d))
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
OR EXISTS (SELECT 1 FROM card_balances cb WHERE cb.created_by = %s AND cb.branch_id = ANY($%d))
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
}
func containsInt64(ids []int64, want int64) bool {

View File

@@ -7,6 +7,7 @@ import (
"strings"
"online-back/internal/identity/role"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -46,7 +47,7 @@ func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.Lis
func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.RoleName != "" {
args = append(args, likePattern(filter.RoleName))
args = append(args, shared.LikePattern(filter.RoleName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n))
}
@@ -58,13 +59,6 @@ func buildListQuery(filter role.ListFilter) (whereClause string, args []interfac
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)
}

View File

@@ -12,15 +12,15 @@ type RoleDTO struct {
}
type CreateRoleDTO struct {
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"`
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
}
type UpdateRoleDTO struct {
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"`
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
}
type ListFilter struct {

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -77,7 +78,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /roles/{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
@@ -141,7 +142,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /roles/{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
@@ -180,7 +181,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /roles/{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
@@ -198,24 +199,10 @@ func (h *handler) delete(c *gin.Context) {
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,
Page: shared.DefaultPage,
Limit: shared.DefaultLimit,
}
if raw := c.Query("page"); raw != "" {
@@ -228,7 +215,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

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/identity/roleusers"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
@@ -50,21 +51,10 @@ func (r *repository) Create(ctx context.Context, dto roleusers.CreateRoleUserDTO
}
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
return genericrepo.Delete(ctx, r.client, "role_user", id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanRoleUser(row scannable) (roleusers.RoleUserDTO, error) {
func scanRoleUser(row genericrepo.Scanner) (roleusers.RoleUserDTO, error) {
var item roleusers.RoleUserDTO
err := row.Scan(

View File

@@ -1,16 +1,12 @@
package roleusers
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/role-users"
@@ -43,20 +39,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @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))
shared.CreateAssoc[CreateRoleUserDTO, RoleUserDTO](c, h.logger, h.repository, "role user")
}
// delete godoc
@@ -72,28 +55,5 @@ func (h *handler) create(c *gin.Context) {
// @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
shared.DeleteAssoc[CreateRoleUserDTO, RoleUserDTO](c, h.logger, h.repository, "role user")
}

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)
}

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/identity/userbranch"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
@@ -61,21 +62,10 @@ func (r *repository) GetByID(ctx context.Context, id int64) (userbranch.UserBran
}
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
return genericrepo.Delete(ctx, r.client, "branch_user", id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanUserBranch(row scannable) (userbranch.UserBranchDTO, error) {
func scanUserBranch(row genericrepo.Scanner) (userbranch.UserBranchDTO, error) {
var item userbranch.UserBranchDTO
var branchNameJSON []byte

View File

@@ -3,11 +3,11 @@ package userbranch
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -50,6 +50,10 @@ func (h *handler) create(c *gin.Context) {
return
}
if !rbac.GuardNewBranchAssignment(c, dto.UserId) {
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create branch user failed: %v", err)
@@ -73,7 +77,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /branch-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
@@ -105,11 +109,3 @@ func (h *handler) delete(c *gin.Context) {
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
}