Bind permissions to roles and scope operator access by branch.

Replace permission_user with permission_role, enforce RBAC on admin routes, and limit operators to their assigned branches.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-24 18:24:43 +05:00
parent 427d5b4e07
commit 1fd0abbcb2
57 changed files with 1281 additions and 657 deletions

View File

@@ -7,6 +7,7 @@ var (
ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002")
ErrNotFound = NewAppError(nil, "The requested resource was not found.", "SE-00003")
ErrInternalServer = NewAppError(nil, "An internal server error occurred. Please try again later.", "SE-00004")
ErrForbidden = NewAppError(nil, "Sana rugsat yok.", "SE-00011")
ErrNotAcceptable = NewAppError(nil, "The request could not be processed.", "SE-00007")
ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008")
ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009")

View File

@@ -7,6 +7,7 @@ import (
"time"
"online-back/internal/cards/cardorder"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -110,7 +111,9 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
}
if filter.BranchId != nil {
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
}

View File

@@ -212,6 +212,7 @@ type UpdateCardOrderDTO struct {
type ListFilter struct {
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
CardStateId *int64
CardTypeId *int64

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -98,6 +99,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -153,6 +157,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateCardOrderDTO
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
h.logger.Errorf("update card order bind failed: %v", err)
@@ -193,6 +201,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -276,9 +288,26 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Region = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {

View File

@@ -6,6 +6,7 @@ import (
"strings"
"online-back/internal/cards/cardpinorders"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -77,7 +78,9 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args [
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
}
if filter.BranchId != nil {
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
}

View File

@@ -74,6 +74,7 @@ type UpdateCardPinOrderDTO struct {
type ListFilter struct {
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
CardTypeId *int64
Region string

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -97,6 +98,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -151,6 +155,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateCardPinOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -190,6 +198,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -270,5 +282,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Region = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
}

View File

@@ -6,6 +6,7 @@ import (
"strings"
"online-back/internal/cards/cards"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -68,6 +69,11 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
args = append(args, filter.BranchIds)
conditions = append(conditions, rbac.UserInBranchSQL("user_id", len(args)))
}
if filter.Type != nil {
args = append(args, *filter.Type)
conditions = append(conditions, fmt.Sprintf("type = $%d", len(args)))

View File

@@ -33,10 +33,11 @@ type UpdateCardDTO struct {
}
type ListFilter struct {
UserId *int64
Type *string
Page int
Limit int
UserId *int64
BranchIds []int64
Type *string
Page int
Limit int
}
type ListCardDTO struct {

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -94,6 +95,13 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if item.UserId != nil && !rbac.GuardUser(c, *item.UserId) {
return
}
if item.UserId == nil && rbac.HasBranchScope(c) {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -148,6 +156,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if !h.guardCardByID(c, id) {
return
}
var dto UpdateCardDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -187,6 +199,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if !h.guardCardByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -247,5 +263,26 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Limit = limit
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardCardByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
if item.UserId == nil {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
return rbac.GuardUser(c, *item.UserId)
}

View File

@@ -7,6 +7,7 @@ import (
"strings"
"online-back/internal/cards/visamaster"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -159,7 +160,9 @@ func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []in
conditions = append(conditions, fmt.Sprintf("o.status = $%d", len(args)))
}
if filter.BranchId != nil {
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "o.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("o.branch_id = $%d", len(args)))
}

View File

@@ -116,13 +116,14 @@ type UpdateVisaMasterPaymentOrderDTO struct {
}
type ListFilter struct {
Name string
Status *string
BranchId *int64
UserId *int64
Region string
Page int
Limit int
Name string
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
Region string
Page int
Limit int
}
type ListVisaMasterPaymentOrderDTO struct {

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -97,6 +98,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -151,6 +155,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateVisaMasterPaymentOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -190,6 +198,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -266,5 +278,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.UserId = &id
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
}

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/identity"
"online-back/internal/identity/activitylog"
activitylogdb "online-back/internal/identity/activitylog/db"
"online-back/internal/identity/rbac"
"online-back/internal/lending"
"online-back/internal/org"
"online-back/pkg/logging"
@@ -52,6 +53,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
adminGroup := router.Group(adminAPIPrefix)
adminGroup.Use(activitylog.Record(activitylogdb.NewRepository(client, logger), logger))
adminGroup.Use(rbac.Guard(rbac.NewService(client)))
// Each bounded context registers its own modules' handlers.
// Add new modules inside the relevant context's router.go rather than here.

View File

@@ -67,8 +67,19 @@ const profileBranchesJSON = `COALESCE((
) b
), '[]'::json)`
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
), '[]'::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 + profileFromClause + ` WHERE u.id = $1`
r.id, r.code, r.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)
@@ -125,6 +136,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
var roleID sql.NullInt64
var roleCode, roleName sql.NullString
var branchesJSON []byte
var permissionsJSON []byte
err := row.Scan(
&profile.Id,
@@ -138,6 +150,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
&roleCode,
&roleName,
&branchesJSON,
&permissionsJSON,
)
if err != nil {
return auth.UserProfileDTO{}, err
@@ -151,12 +164,18 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
}
}
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
profile.Branches = []auth.ProfileBranchDTO{}
return profile, nil
profile.Branches = []auth.ProfileBranchDTO{}
if len(branchesJSON) > 0 && string(branchesJSON) != "null" {
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
return auth.UserProfileDTO{}, err
}
}
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
return auth.UserProfileDTO{}, err
profile.Permissions = []auth.ProfilePermissionDTO{}
if len(permissionsJSON) > 0 && string(permissionsJSON) != "null" {
if err := json.Unmarshal(permissionsJSON, &profile.Permissions); err != nil {
return auth.UserProfileDTO{}, err
}
}
return profile, nil
}

View File

@@ -30,16 +30,23 @@ type ProfileBranchDTO struct {
Name LocalizedText `json:"name"`
}
type ProfilePermissionDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
}
type UserProfileDTO struct {
Id int `json:"id"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
Role *ProfileRoleDTO `json:"role"`
Branches []ProfileBranchDTO `json:"branches"`
CreatedAt time.Time `json:"createdAt"`
Id int `json:"id"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
Role *ProfileRoleDTO `json:"role"`
Branches []ProfileBranchDTO `json:"branches"`
Permissions []ProfilePermissionDTO `json:"permissions"`
CreatedAt time.Time `json:"createdAt"`
}
type UpdateProfileDTO struct {

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 and branches
// @Description Returns the authenticated user's profile with role, branches, and permissions
// @Tags auth
// @Produce json
// @Security BearerAuth

View File

@@ -0,0 +1,69 @@
package db
import (
"context"
"errors"
"online-back/internal/identity/permissionrole"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) permissionrole.Repository {
return &repository{client: client, logger: logger}
}
func (r *repository) Create(ctx context.Context, dto permissionrole.CreatePermissionRoleDTO) (permissionrole.PermissionRoleDTO, error) {
query := `
WITH upserted AS (
INSERT INTO permission_role (permission_id, role_id)
VALUES ($1, $2)
ON CONFLICT (permission_id, role_id) DO UPDATE SET
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
RETURNING id, permission_id, role_id, created_at, updated_at
)
SELECT upserted.id, upserted.permission_id, p.name, upserted.role_id, r.name, upserted.created_at, upserted.updated_at
FROM upserted
JOIN permissions p ON p.id = upserted.permission_id
JOIN roles r ON r.id = upserted.role_id`
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.RoleId)
return scanPermissionRole(row)
}
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
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPermissionRole(row scannable) (permissionrole.PermissionRoleDTO, error) {
var item permissionrole.PermissionRoleDTO
err := row.Scan(
&item.Id, &item.PermissionId, &item.PermissionName, &item.RoleId, &item.RoleName, &item.CreatedAt, &item.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return permissionrole.PermissionRoleDTO{}, err
}
if err != nil {
return permissionrole.PermissionRoleDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,18 @@
package permissionrole
import "time"
type PermissionRoleDTO struct {
Id int64 `json:"id"`
RoleId int64 `json:"roleId"`
RoleName string `json:"roleName"`
PermissionId int64 `json:"permissionId"`
PermissionName string `json:"permissionName"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreatePermissionRoleDTO struct {
PermissionId int64 `json:"permissionId" binding:"required"`
RoleId int64 `json:"roleId" binding:"required"`
}

View File

@@ -0,0 +1,99 @@
package permissionrole
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/permission-roles"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.POST("", h.create)
group.DELETE("/:id", h.delete)
}
// create godoc
// @Summary Assign permission to role
// @Description Creates a permission-role assignment, or updates the existing pair if already assigned
// @Tags permission-roles
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreatePermissionRoleDTO true "Permission-role payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @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))
}
// delete godoc
// @Summary Remove permission from role
// @Description Deletes a permission-role assignment
// @Tags permission-roles
// @Produce json
// @Security BearerAuth
// @Param id path int true "Permission-role ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @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
}

View File

@@ -0,0 +1,8 @@
package permissionrole
import "context"
type Repository interface {
Create(ctx context.Context, dto CreatePermissionRoleDTO) (PermissionRoleDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -1,132 +0,0 @@
package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/identity/permissionuser"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) permissionuser.Repository {
return &repository{client: client, logger: logger}
}
const permissionUserFromClause = ` FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
JOIN users u ON u.id = pu.user_id`
const permissionUserSelectColumns = `pu.id, pu.permission_id, p.name, pu.user_id, u.name, pu.created_at, pu.updated_at`
func (r *repository) List(ctx context.Context, filter permissionuser.ListFilter) (permissionuser.ListPermissionUserDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+permissionUserFromClause+whereClause, args...).Scan(&count); err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
query := `SELECT ` + permissionUserSelectColumns + permissionUserFromClause + whereClause + ` ORDER BY pu.id DESC`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
defer rows.Close()
var items []permissionuser.PermissionUserDTO
for rows.Next() {
item, err := scanPermissionUser(rows)
if err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
return permissionuser.ListPermissionUserDTO{Count: count, Items: items}, nil
}
func buildListQuery(filter permissionuser.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("pu.user_id = $%d", len(args)))
}
if filter.PermissionName != "" {
args = append(args, likePattern(filter.PermissionName))
conditions = append(conditions, fmt.Sprintf("p.name ILIKE $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) {
query := `
WITH inserted AS (
INSERT INTO permission_user (permission_id, user_id)
VALUES ($1, $2)
RETURNING id, permission_id, user_id, created_at, updated_at
)
SELECT inserted.id, inserted.permission_id, p.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
FROM inserted
JOIN permissions p ON p.id = inserted.permission_id
JOIN users u ON u.id = inserted.user_id`
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId)
return scanPermissionUser(row)
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM permission_user WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) {
var item permissionuser.PermissionUserDTO
err := row.Scan(
&item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return permissionuser.PermissionUserDTO{}, err
}
if err != nil {
return permissionuser.PermissionUserDTO{}, err
}
return item, nil
}

View File

@@ -1,28 +0,0 @@
package permissionuser
import "time"
type PermissionUserDTO struct {
Id int64 `json:"id"`
UserId int64 `json:"userId"`
UserName string `json:"userName"`
PermissionId int64 `json:"permissionId"`
PermissionName string `json:"permissionName"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type ListPermissionUserDTO struct {
Count int64 `json:"count"`
Items []PermissionUserDTO `json:"items"`
}
type ListFilter struct {
UserId *int64
PermissionName string
}
type CreatePermissionUserDTO struct {
PermissionId int64 `json:"permissionId" binding:"required"`
UserId int64 `json:"userId" binding:"required"`
}

View File

@@ -1,152 +0,0 @@
package permissionuser
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/permission-users"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.POST("", h.create)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List permission users
// @Description Returns the authenticated user's permission-user assignments with the related user and permission
// @Tags permission-users
// @Produce json
// @Security BearerAuth
// @Param permission_name query string false "Filter by permission name"
// @Success 200 {object} appresult.AppSuccess
// @Failure 401 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-users [get]
func (h *handler) list(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
filter := ListFilter{
UserId: &userID,
PermissionName: strings.TrimSpace(c.Query("permission_name")),
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list permission users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// create godoc
// @Summary Assign user to permission
// @Description Creates a permission-user assignment
// @Tags permission-users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreatePermissionUserDTO true "Permission-user payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-users [post]
func (h *handler) create(c *gin.Context) {
var dto CreatePermissionUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create permission user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Remove user from permission
// @Description Deletes a permission-user assignment
// @Tags permission-users
// @Produce json
// @Security BearerAuth
// @Param id path int true "Permission-user ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-users/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete permission user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("permission user removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
func currentUserID(c *gin.Context) (int64, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
switch id := rawID.(type) {
case int64:
return id, id > 0
case int:
return int64(id), id > 0
case string:
return parseID(id)
default:
return 0, false
}
}

View File

@@ -1,9 +0,0 @@
package permissionuser
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListPermissionUserDTO, error)
Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -1,38 +1,371 @@
package rbac
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
const (
roleUser = "user"
roleOperator = "operator"
adminPrefix = "/api/admin"
contextRole = "role"
)
// RequirePermission returns a gin middleware that 403s unless the
// authenticated user (set by appresult.JwtTokenCheck, which must run first)
// has been directly granted the given permission code. Not currently
// attached to any route.
func RequirePermission(service *Service, code string) gin.HandlerFunc {
return func(c *gin.Context) {
rawID, exists := c.Get("id")
if !exists {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
if err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
granted, err := service.HasPermission(c.Request.Context(), userID, code)
if err != nil || !granted {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
c.Next()
}
}
func Guard(service *Service) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) {
c.Next()
return
}
userID, ok := requestUserID(c)
if !ok {
c.Next()
return
}
code, err := service.RoleCode(c.Request.Context(), userID)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.Set("id", strconv.FormatInt(userID, 10))
c.Set(contextRole, code)
c.Set(contextService, service)
switch code {
case roleOperator:
enforceOperator(c, service, userID)
return
case roleUser, "":
if !userRoleAllows(c.Request.Method, c.Request.URL.Path) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
scopeOwnedLists(c, userID)
c.Next()
return
default:
c.Next()
return
}
}
}
func enforceOperator(c *gin.Context, service *Service, userID int64) {
ids, err := service.BranchIDs(c.Request.Context(), userID)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.Set(contextBranchIDs, ids)
if !operatorRoleAllows(c.Request.Method, c.Request.URL.Path) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
if !operatorProfileOrFile(c.Request.URL.Path) && len(ids) == 0 {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
if !operatorWriteAllowed(c, service, ids) {
return
}
c.Next()
}
func isPublicAdminPath(path string) bool {
switch strings.TrimSuffix(path, "/") {
case adminPrefix + "/login",
adminPrefix + "/token",
adminPrefix + "/register",
adminPrefix + "/register/verify",
adminPrefix + "/forgot-password",
adminPrefix + "/forgot-password/verify":
return true
default:
return false
}
}
func userRoleAllows(method, path string) bool {
if method != http.MethodGet {
return false
}
rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/")
if rest == "" {
return false
}
if !strings.HasPrefix(rest, "/") {
rest = "/" + rest
}
for _, prefix := range userRolePrefixes {
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
return true
}
}
return false
}
func scopeOwnedLists(c *gin.Context, userID int64) {
rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/")
if rest == "" {
return
}
if !strings.HasPrefix(rest, "/") {
rest = "/" + rest
}
owned := false
for _, prefix := range userOwnedPrefixes {
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
owned = true
break
}
}
if !owned {
return
}
query := c.Request.URL.Query()
query.Set("user_id", strconv.FormatInt(userID, 10))
c.Request.URL.RawQuery = query.Encode()
}
func requestUserID(c *gin.Context) (int64, bool) {
if id, ok := parseContextUserID(c); ok {
return id, true
}
token := bearerToken(c.GetHeader("Authorization"))
if token == "" {
return 0, false
}
claims, err := appresult.TokenClaims(token, config.GetConfig().JwtKey)
if err != nil {
return 0, false
}
return claimUserID(claims)
}
func parseContextUserID(c *gin.Context) (int64, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
switch id := rawID.(type) {
case int64:
return id, id > 0
case int:
return int64(id), id > 0
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}
func claimUserID(claims jwt.MapClaims) (int64, bool) {
switch id := claims["id"].(type) {
case float64:
return int64(id), id > 0
case int64:
return id, id > 0
case int:
return int64(id), id > 0
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}
func bearerToken(header string) string {
const prefix = "Bearer "
if strings.HasPrefix(header, prefix) {
return strings.TrimSpace(header[len(prefix):])
}
return strings.TrimSpace(header)
}
var userRolePrefixes = []string{
"/profile",
"/cards",
"/card-orders",
"/card-pin-orders",
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
"/loan-orders",
"/loan-types",
"/loans-documents",
"/loans-repayment",
"/loan-paid-off-letters",
}
var userOwnedPrefixes = []string{
"/cards",
"/card-orders",
"/card-pin-orders",
"/visa-master-payment-orders",
"/loan-orders",
}
func operatorRoleAllows(method, path string) bool {
rest := adminREST(path)
if rest == "" {
return false
}
if method == http.MethodGet {
for _, prefix := range operatorGetPrefixes {
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
return true
}
}
}
for _, prefix := range operatorWritePrefixes {
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
return true
}
}
return false
}
func operatorProfileOrFile(path string) bool {
rest := adminREST(path)
return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/")
}
func operatorWriteAllowed(c *gin.Context, service *Service, branchIDs []int64) bool {
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
default:
return true
}
if operatorProfileOrFile(c.Request.URL.Path) || len(branchIDs) == 0 {
return true
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
return false
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
if len(bytes.TrimSpace(body)) == 0 {
return true
}
var payload struct {
BranchId *int64 `json:"branchId"`
UserId *int64 `json:"userId"`
}
if err := json.Unmarshal(body, &payload); err != nil {
return true
}
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
if payload.UserId != nil && *payload.UserId > 0 {
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
if !visible {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
}
return true
}
func adminREST(path string) string {
rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/")
if rest == "" {
return ""
}
if !strings.HasPrefix(rest, "/") {
rest = "/" + rest
}
return rest
}
var operatorWritePrefixes = []string{
"/profile",
"/file",
"/users",
"/branch-users",
"/cards",
"/card-orders",
"/card-pin-orders",
"/visa-master-payment-orders",
"/loan-orders",
"/loans-repayment",
"/loan-paid-off-letters",
}
var operatorGetPrefixes = []string{
"/profile",
"/file",
"/users",
"/cards",
"/card-orders",
"/card-pin-orders",
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
"/loan-orders",
"/loan-types",
"/loans-documents",
"/loans-repayment",
"/loan-paid-off-letters",
"/provinces",
"/branches",
}

View File

@@ -0,0 +1,104 @@
package rbac
import (
"fmt"
"net/http"
"online-back/internal/appresult"
"github.com/gin-gonic/gin"
)
const (
contextBranchIDs = "branchIds"
contextService = "rbacService"
)
func BranchIDsFrom(c *gin.Context) []int64 {
raw, ok := c.Get(contextBranchIDs)
if !ok {
return nil
}
ids, _ := raw.([]int64)
return ids
}
func HasBranchScope(c *gin.Context) bool {
return len(BranchIDsFrom(c)) > 0
}
func AllowsBranch(c *gin.Context, branchID int64) bool {
ids := BranchIDsFrom(c)
if len(ids) == 0 {
return true
}
return containsInt64(ids, branchID)
}
func BindBranchIDs(c *gin.Context, dest *[]int64) {
ids := BranchIDsFrom(c)
if len(ids) == 0 {
return
}
*dest = ids
}
func GuardBranch(c *gin.Context, branchID int64) bool {
if AllowsBranch(c, branchID) {
return true
}
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
func GuardUser(c *gin.Context, userID int64) bool {
ids := BranchIDsFrom(c)
if len(ids) == 0 {
return true
}
raw, ok := c.Get(contextService)
if !ok {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
service, _ := raw.(*Service)
if service == nil {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
visible, err := service.UserVisibleInBranches(c.Request.Context(), userID, ids)
if err != nil || !visible {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
return true
}
func AppendBranchIDs(conditions []string, args []interface{}, column string, ids []int64) ([]string, []interface{}) {
if len(ids) == 0 {
return conditions, args
}
args = append(args, ids)
conditions = append(conditions, fmt.Sprintf("%s = ANY($%d)", column, len(args)))
return conditions, args
}
func UserInBranchSQL(userExpr string, placeholder int) string {
return fmt.Sprintf(`(
EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = %s AND bu.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM card_orders co WHERE co.user_id = %s AND co.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM loan_orders lo WHERE lo.user_id = %s AND lo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM card_pin_orders cpo WHERE cpo.user_id = %s AND cpo.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)
}
func containsInt64(ids []int64, want int64) bool {
for _, id := range ids {
if id == want {
return true
}
}
return false
}

View File

@@ -1,18 +1,12 @@
// Package rbac provides permission-check capability on top of the existing
// permissions/permission_user tables. It is not wired into any route yet —
// today every route is still gated only by appresult.JwtTokenCheck()'s
// admin-claim check. RequirePermission is available for routes to opt into
// once permission data is populated and specific routes are chosen.
//
// Note: the schema has no role_permission pivot table, so role-based
// permission resolution isn't possible yet — HasPermission only resolves
// permissions granted directly via permission_user.
package rbac
import (
"context"
"errors"
"online-back/pkg/client/postgresql"
"github.com/jackc/pgx/v4"
)
type Service struct {
@@ -23,15 +17,14 @@ func NewService(client postgresql.Client) *Service {
return &Service{client: client}
}
// HasPermission reports whether userID has been directly granted the
// permission identified by code (permissions.code) via permission_user.
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
WHERE pu.user_id = $1 AND p.code = $2
FROM role_user ru
JOIN permission_role pr ON pr.role_id = ru.role_id
JOIN permissions p ON p.id = pr.permission_id
WHERE ru.user_id = $1 AND p.code = $2
)`
var granted bool
@@ -40,3 +33,57 @@ func (s *Service) HasPermission(ctx context.Context, userID int64, code string)
}
return granted, nil
}
func (s *Service) RoleCode(ctx context.Context, userID int64) (string, error) {
const query = `
SELECT r.code
FROM role_user ru
JOIN roles r ON r.id = ru.role_id
WHERE ru.user_id = $1
ORDER BY ru.id
LIMIT 1`
var code string
err := s.client.QueryRow(ctx, query, userID).Scan(&code)
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
}
return code, err
}
func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error) {
const query = `
SELECT bu.branch_id
FROM branch_user bu
WHERE bu.user_id = $1
ORDER BY bu.id`
rows, err := s.client.Query(ctx, query, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (s *Service) UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error) {
if len(branchIDs) == 0 {
return false, nil
}
query := `SELECT ` + UserInBranchSQL("u.id", 2) + ` FROM users u WHERE u.id = $1`
var ok bool
err := s.client.QueryRow(ctx, query, userID, branchIDs).Scan(&ok)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
return ok, err
}

View File

@@ -1,56 +0,0 @@
package rbac
import (
"context"
"testing"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type fakeClient struct {
granted bool
}
func (f *fakeClient) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) {
return nil, nil
}
func (f *fakeClient) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {
return nil, nil
}
func (f *fakeClient) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
return fakeRow{granted: f.granted}
}
func (f *fakeClient) Begin(ctx context.Context) (pgx.Tx, error) {
return nil, nil
}
type fakeRow struct {
granted bool
}
func (r fakeRow) Scan(dest ...interface{}) error {
*dest[0].(*bool) = r.granted
return nil
}
func TestHasPermission(t *testing.T) {
granted, err := NewService(&fakeClient{granted: true}).HasPermission(context.Background(), 1, "province.write")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !granted {
t.Fatal("expected permission to be granted")
}
granted, err = NewService(&fakeClient{granted: false}).HasPermission(context.Background(), 1, "province.write")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if granted {
t.Fatal("expected permission to not be granted")
}
}

View File

@@ -1,6 +1,3 @@
// Package identity groups authentication, users, and RBAC (roles,
// permissions, and their user/branch assignments) under one bounded
// context, replacing the flat internal/admin/* listing.
package identity
import (
@@ -11,8 +8,8 @@ import (
authdb "online-back/internal/identity/auth/db"
"online-back/internal/identity/permission"
permissiondb "online-back/internal/identity/permission/db"
"online-back/internal/identity/permissionuser"
permissionuserdb "online-back/internal/identity/permissionuser/db"
"online-back/internal/identity/permissionrole"
permissionroledb "online-back/internal/identity/permissionrole/db"
"online-back/internal/identity/role"
roledb "online-back/internal/identity/role/db"
"online-back/internal/identity/roleusers"
@@ -28,7 +25,6 @@ import (
"github.com/gin-gonic/gin"
)
func Register(router *gin.RouterGroup, engine *gin.Engine, client postgresql.Client, logger *logging.Logger) {
userH := user.NewHandler(logger, userdb.NewRepository(client, logger))
userH.Register(router)
@@ -46,7 +42,7 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl
role.NewHandler(logger, roledb.NewRepository(client, logger)),
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)),
permissionrole.NewHandler(logger, permissionroledb.NewRepository(client, logger)),
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
}
}

View File

@@ -8,6 +8,7 @@ import (
"fmt"
"strings"
"online-back/internal/identity/rbac"
"online-back/internal/identity/user"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -98,7 +99,13 @@ func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (use
}
func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`}
var conditions []string
if len(filter.BranchIds) > 0 {
args = append(args, filter.BranchIds)
conditions = append(conditions, fmt.Sprintf(`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d))`, len(args)))
} else {
conditions = append(conditions, `EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`)
}
conditions, args = appendNameSearch(conditions, args, filter.Search)
return " WHERE " + strings.Join(conditions, " AND "), args
}
@@ -145,17 +152,22 @@ func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause
var conditions []string
conditions, args = appendNameSearch(conditions, args, filter.Search)
if len(roles) == 1 {
args = append(args, roles[0])
n := len(args)
conditions = append(conditions, fmt.Sprintf(`r.code = $%d`, n))
} else if len(roles) > 0 {
if len(roles) > 0 {
placeholders := make([]string, len(roles))
for i, role := range roles {
args = append(args, role)
placeholders[i] = fmt.Sprintf("$%d", len(args))
}
conditions = append(conditions, fmt.Sprintf(`r.code IN (%s)`, strings.Join(placeholders, ", ")))
if len(roles) == 1 {
conditions = append(conditions, fmt.Sprintf(`r.code = %s`, placeholders[0]))
} else {
conditions = append(conditions, fmt.Sprintf(`r.code IN (%s)`, strings.Join(placeholders, ", ")))
}
}
if len(filter.BranchIds) > 0 {
args = append(args, filter.BranchIds)
conditions = append(conditions, rbac.UserInBranchSQL("u.id", len(args)))
}
if len(conditions) == 0 {
@@ -187,11 +199,13 @@ func likePattern(term string) string {
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
excludeStaff := `NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`
if whereClause == "" {
whereClause = " WHERE " + excludeStaff
} else {
whereClause += " AND " + excludeStaff
if len(filter.BranchIds) == 0 {
excludeStaff := `NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`
if whereClause == "" {
whereClause = " WHERE " + excludeStaff
} else {
whereClause += " AND " + excludeStaff
}
}
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
}

View File

@@ -57,9 +57,10 @@ type UpdateUserDTO struct {
}
type ListFilter struct {
Search string
Page int
Limit int
Search string
BranchIds []int64
Page int
Limit int
}
type ListUserDTO struct {

View File

@@ -13,6 +13,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/config"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
minioUpload "online-back/pkg/minio"
@@ -180,6 +181,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardUser(c, item.Id) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -234,6 +238,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if rbac.HasBranchScope(c) && !rbac.GuardUser(c, id) {
return
}
var dto UpdateUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -273,6 +281,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if rbac.HasBranchScope(c) && !rbac.GuardUser(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -327,6 +339,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Search = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}

View File

@@ -50,6 +50,16 @@ func (r *repository) Create(ctx context.Context, dto userbranch.CreateUserBranch
return scanUserBranch(row)
}
func (r *repository) GetByID(ctx context.Context, id int64) (userbranch.UserBranchDTO, error) {
query := `
SELECT bu.id, bu.branch_id, b.name, bu.user_id, u.name, bu.created_at, bu.updated_at
FROM branch_user bu
JOIN branches b ON b.id = bu.branch_id
JOIN users u ON u.id = bu.user_id
WHERE bu.id = $1`
return scanUserBranch(r.client.QueryRow(ctx, query, id))
}
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 {

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -78,6 +79,21 @@ func (h *handler) delete(c *gin.Context) {
return
}
if rbac.HasBranchScope(c) {
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
return
}
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return

View File

@@ -4,5 +4,6 @@ import "context"
type Repository interface {
Create(ctx context.Context, dto CreateUserBranchDTO) (UserBranchDTO, error)
GetByID(ctx context.Context, id int64) (UserBranchDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"strings"
"online-back/internal/identity/rbac"
"online-back/internal/lending/loanorders"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -161,7 +162,9 @@ func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []in
conditions = append(conditions, fmt.Sprintf("lo.status = $%d", len(args)))
}
if filter.BranchId != nil {
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "lo.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("lo.branch_id = $%d", len(args)))
}

View File

@@ -227,13 +227,14 @@ type UpdateLoanOrderDTO struct {
}
type ListFilter struct {
Status *string
BranchId *int64
UserId *int64
Source string
Region string
Page int
Limit int
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
Source string
Region string
Page int
Limit int
}
type ListLoanOrderDTO struct {

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -126,6 +127,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -180,6 +184,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateLoanOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -219,6 +227,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -291,5 +303,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Region = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
}

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"strings"
"online-back/internal/identity/rbac"
"online-back/internal/lending/loanpaidletter"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -137,7 +138,9 @@ func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args
conditions = append(conditions, fmt.Sprintf("l.status = $%d", len(args)))
}
if filter.BranchId != nil {
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "l.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("l.branch_id = $%d", len(args)))
}

View File

@@ -80,6 +80,7 @@ type ListFilter struct {
Name string
Status *string
BranchId *int64
BranchIds []int64
Region string
Page int
Limit int

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -137,6 +138,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -191,6 +195,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateLoanPaidLetterDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -230,6 +238,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -302,5 +314,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.BranchId = &id
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
}

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"strings"
"online-back/internal/identity/rbac"
"online-back/internal/lending/loansrepayment"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -81,6 +82,11 @@ func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args
conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
args = append(args, filter.BranchIds)
conditions = append(conditions, rbac.UserInBranchSQL("l.user_id", len(args)))
}
if len(conditions) == 0 {
return "", args
}

View File

@@ -29,6 +29,7 @@ type UpdateLoanRepaymentDTO struct {
type ListFilter struct {
PassportId string
BranchIds []int64
Page int
Limit int
}

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
@@ -93,6 +94,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardUser(c, item.UserId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -147,6 +151,10 @@ func (h *handler) update(c *gin.Context) {
return
}
if !h.guardUserByID(c, id) {
return
}
var dto UpdateLoanRepaymentDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -186,6 +194,10 @@ func (h *handler) delete(c *gin.Context) {
return
}
if !h.guardUserByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -238,5 +250,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.PassportId = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardUserByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardUser(c, item.UserId)
}

View File

@@ -7,6 +7,7 @@ import (
"fmt"
"strings"
"online-back/internal/identity/rbac"
"online-back/internal/org/branches"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -125,6 +126,10 @@ func buildListQuery(filter branches.ListFilter) (whereClause string, args []inte
conditions = append(conditions, fmt.Sprintf("b.unique_code ILIKE $%d", n))
}
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "b.id", filter.BranchIds)
}
if len(conditions) == 0 {
return "", args
}

View File

@@ -7,23 +7,23 @@ type LocalizedText struct {
}
type BranchDTO struct {
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name LocalizedText `json:"name"`
Address LocalizedText `json:"address"`
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
ProvinceName LocalizedText `json:"provinceName"`
PhoneNumbers string `json:"phoneNumbers"`
BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"`
BillingSberUsername string `json:"billingSberUsername"`
BillingSberPassword string `json:"billingSberPassword"`
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
BillingSwiftUsername string `json:"billingSwiftUsername"`
BillingSwiftPassword string `json:"billingSwiftPassword"`
Active bool `json:"active"`
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name LocalizedText `json:"name"`
Address LocalizedText `json:"address"`
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
ProvinceName LocalizedText `json:"provinceName"`
PhoneNumbers string `json:"phoneNumbers"`
BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"`
BillingSberUsername string `json:"billingSberUsername"`
BillingSberPassword string `json:"billingSberPassword"`
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
BillingSwiftUsername string `json:"billingSwiftUsername"`
BillingSwiftPassword string `json:"billingSwiftPassword"`
Active bool `json:"active"`
}
type CreateBranchDTO struct {
@@ -67,6 +67,7 @@ type ListFilter struct {
ProvinceName string
BranchName string
UniqueCode string
BranchIds []int64
Page int
Limit int
}

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/org/province"
"online-back/pkg/logging"
@@ -163,6 +164,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.Id) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -349,5 +353,6 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.UniqueCode = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}