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:
guwandykandCursor committed 2026-08-24 18:24:43 +05:00
1 parent 427d5b4e07
commit 1fd0abbcb2
57 files changed
+1281 -657

No files matched your search

+340 -7
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",
}
+104
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
}
+61 -14
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
}
-56
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")
}
}