package rbac import ( "fmt" "net/http" "online-back/internal/appresult" "online-back/internal/identity/rbac/perm" "github.com/gin-gonic/gin" ) // PrincipalFrom returns the caller loaded by Guard, or nil on public routes. func PrincipalFrom(c *gin.Context) *Principal { raw, ok := c.Get(contextPrincipal) if !ok { return nil } p, _ := raw.(*Principal) return p } func serviceFrom(c *gin.Context) Authorizer { raw, ok := c.Get(contextService) if !ok { return nil } service, _ := raw.(Authorizer) return service } // Can reports whether the caller holds code (always true for superadmin). func Can(c *gin.Context, code perm.Code) bool { return PrincipalFrom(c).Can(code) } // BranchIDsFrom returns the caller's branches when their scope is branch, // nil otherwise (all and own scopes are not narrowed by branch). func BranchIDsFrom(c *gin.Context) []int64 { p := PrincipalFrom(c) if p == nil || p.Scope != ScopeBranch { return nil } return p.BranchIDs } func HasBranchScope(c *gin.Context) bool { return len(BranchIDsFrom(c)) > 0 } func IsOwnScope(c *gin.Context) bool { p := PrincipalFrom(c) return p != nil && p.Scope == ScopeOwn } func IsSuper(c *gin.Context) bool { p := PrincipalFrom(c) return p != nil && p.IsSuper } func HasAllScope(c *gin.Context) bool { p := PrincipalFrom(c) return p != nil && p.Scope == ScopeAll } // SkipRecordGuard: all-scope callers see every record, so handlers can skip // the extra owner/branch lookup. func SkipRecordGuard(c *gin.Context) bool { return HasAllScope(c) } func CurrentUserID(c *gin.Context) (int64, bool) { if p := PrincipalFrom(c); p != nil { return p.UserID, true } return parseContextUserID(c) } func GuardOwned(c *gin.Context, ownerID *int64) bool { if !IsOwnScope(c) { return true } current, ok := CurrentUserID(c) if !ok || ownerID == nil || *ownerID != current { c.JSON(http.StatusForbidden, appresult.ErrForbidden) return false } return true } func GuardOrder(c *gin.Context, ownerID *int64, branchID int64) bool { if IsOwnScope(c) { return GuardOwned(c, ownerID) } return GuardBranch(c, branchID) } 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 } // 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 } service := serviceFrom(c) 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 return GuardOwned(c, &id) } ids := BranchIDsFrom(c) if len(ids) == 0 { return true } service := serviceFrom(c) 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) AND bu.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM card_orders co WHERE co.user_id = %s AND co.branch_id = ANY($%d) AND co.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM loan_orders lo WHERE lo.user_id = %s AND lo.branch_id = ANY($%d) AND lo.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM card_pin_orders cpo WHERE cpo.user_id = %s AND cpo.branch_id = ANY($%d) AND cpo.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d) AND cro.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d) AND vmo.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d) AND lpl.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM card_balances cb WHERE cb.created_by = %s AND cb.branch_id = ANY($%d) AND cb.deleted_at IS NULL) )`, userExpr, placeholder, userExpr, placeholder, 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 }