package rbac import ( "bytes" "encoding/json" "io" "net/http" "strconv" "strings" "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 ( roleUser = "user" roleOperator = "operator" roleSuperadmin = "superadmin" guardWeb = "web" guardOperator = "operator" guardAdmin = "admin" adminPrefix = "/api/admin" contextRole = "role" contextGuard = "guard" ) func RequirePermission(service Authorizer, code string) gin.HandlerFunc { return func(c *gin.Context) { rawID, exists := c.Get("id") if !exists { c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) return } userID, err := strconv.ParseInt(rawID.(string), 10, 64) if err != nil { 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.ErrForbidden) return } c.Next() } } func Guard(service Authorizer) 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, guardName, err := service.RoleLookup(c.Request.Context(), userID) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } guard := effectiveGuard(code, guardName) c.Set("id", strconv.FormatInt(userID, 10)) c.Set(contextRole, code) c.Set(contextGuard, guard) c.Set(contextService, service) switch guard { case guardOperator: enforceOperator(c, service, userID) return case guardWeb: if code == "" { c.Set(contextRole, roleUser) } if !userRoleAllows(c.Request.Method, c.Request.URL.Path) { c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) return } scopeOwnedLists(c, userID) if !enforceOwnWrites(c, userID) { return } c.Next() return default: enforceAdmin(c, service, userID, code) return } } } // enforceAdmin gates the admin guard: only the superadmin role code is // unconditionally trusted (kept as one deliberately unrestricted role by // design). Every other admin-guard role (admin, manager, currency_maintainer, // or any future role with guard_name=admin) is checked against its actual // permission_role grants, mirroring enforceOperator's module/code checks — // so who can do what is decided by role/permission assignment (managed by // superadmin via the Role/Permission/Permission-Role APIs), not by role code. func enforceAdmin(c *gin.Context, service Authorizer, userID int64, code string) { if strings.EqualFold(strings.TrimSpace(code), roleSuperadmin) { c.Next() return } if module := operatorPathModule(c.Request.Method, c.Request.URL.Path); module != "" { granted, err := service.HasModuleAccess(c.Request.Context(), userID, module) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } if !granted { abortForbidden(c, "missing module access for admin path", logrus.Fields{"userId": userID, "module": module}) return } } if perm := adminPathPermission(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 admin path", logrus.Fields{"userId": userID, "permission": perm}) return } } c.Next() } func enforceOperator(c *gin.Context, service Authorizer, 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) { abortForbidden(c, "route not in operator allow-list", logrus.Fields{"userId": userID}) return } 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 module := operatorPathModule(c.Request.Method, c.Request.URL.Path); module != "" { granted, err := service.HasModuleAccess(c.Request.Context(), userID, module) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } if !granted { abortForbidden(c, "missing module access for operator path", logrus.Fields{"userId": userID, "module": module}) 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 } 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)) switch code { case "admin", "superadmin", "manager": return guardAdmin case roleOperator, "operatot": return guardOperator } switch guard { case guardWeb, guardOperator, guardAdmin: return guard } if code == roleUser || code == "" { return guardWeb } return guardAdmin } 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", adminPrefix + "/visa-master-payment-orders/callback": return true default: return false } } func userRoleAllows(method, path string) bool { rest := adminREST(path) if rest == "" { return false } if matchesPrefix(rest, userCatalogPrefixes) { return method == http.MethodGet } if matchesPrefix(rest, userSelfPrefixes) { if rest == "/profile" || strings.HasPrefix(rest, "/profile/") { return method == http.MethodGet || method == http.MethodPut || method == http.MethodPatch } return method == http.MethodGet || method == http.MethodPost } if matchesPrefix(rest, userOwnedPrefixes) { switch method { case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: return true } } return false } func matchesPrefix(rest string, prefixes []string) bool { for _, prefix := range prefixes { if rest == prefix || strings.HasPrefix(rest, prefix+"/") { return true } } return false } func enforceOwnWrites(c *gin.Context, userID int64) bool { if !matchesPrefix(adminREST(c.Request.URL.Path), userOwnedPrefixes) { return true } switch c.Request.Method { case http.MethodPost, http.MethodPut, http.MethodPatch: default: 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 map[string]interface{} if err := json.Unmarshal(body, &payload); err != nil { return true } payload["userId"] = userID payload["user_id"] = userID payload["createdBy"] = userID payload["created_by"] = userID rewritten, err := json.Marshal(payload) if err != nil { return true } c.Request.Body = io.NopCloser(bytes.NewBuffer(rewritten)) c.Request.ContentLength = int64(len(rewritten)) return true } 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)) query.Set("created_by", 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 userCatalogPrefixes = []string{ "/payment-cards", "/reasons-cards", "/loan-types", "/loans-documents", "/currencies", "/branches", "/provinces", "/users/clients", } var userSelfPrefixes = []string{ "/profile", "/file", } var userOwnedPrefixes = []string{ "/cards", "/card-balances", "/card-orders", "/card-pin-orders", "/card-rekwizit-orders", "/visa-master-payment-orders", "/loan-orders", "/loans-repayment", "/loan-paid-off-letters", } 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 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: 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) { 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 { c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) return false } if !visible { abortForbidden(c, "payload userId not visible in operator's branches", logrus.Fields{ "requestedUserId": *payload.UserId, "allowedBranchIds": branchIDs, }) 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 } // operatorPathModule returns the permission module ("cards" or "loans") that // guards a saha endpoint. Matching by module rather than a fixed code lets an // admin grant access under a new permission code created in that module // (via the existing Permission/Permission-Role APIs) without a code change // here. Shared by both enforceOperator and enforceAdmin — the cards/loans // grouping is the same regardless of which guard is calling. func operatorPathModule(_, 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-history", "/payment-cards", "/reasons-cards", }): return "cards" case matchesPrefix(rest, []string{ "/loan-orders", "/loans-repayment", "/loan-paid-off-letters", "/loan-types", "/loans-documents", }): return "loans" } return "" } // operatorPathPermission returns the exact permission code required for // endpoints that distinguish view vs. manage access. 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{"/users/clients"}): return "" case matchesPrefix(rest, []string{"/users", "/branch-users"}): if method == http.MethodGet { return "users.view" } return "users.manage" } return "" } // adminPathPermission returns the ".view"/".manage" code // required for admin-guard saha that split read vs. write access (unlike // cards/loans, which stay module-based via operatorPathModule). Empty // string: no permission required (dashboard, profile, file, public routes). func adminPathPermission(method, path string) string { rest := adminREST(path) switch { case matchesPrefix(rest, []string{"/users", "/branch-users"}): return viewOrManage(method, "users") case matchesPrefix(rest, []string{"/roles", "/permissions", "/permission-roles", "/role-users"}): return viewOrManage(method, "roles") case matchesPrefix(rest, []string{"/branches"}): return viewOrManage(method, "branches") case matchesPrefix(rest, []string{"/provinces"}): return viewOrManage(method, "provinces") case matchesPrefix(rest, []string{"/activity-logs"}): return "activity-logs.view" case matchesPrefix(rest, []string{"/backups"}): return viewOrManage(method, "backups") case matchesPrefix(rest, []string{"/currencies"}): return viewOrManage(method, "currencies") case matchesPrefix(rest, []string{"/payment-settings"}): return viewOrManage(method, "payment-settings") } return "" } func viewOrManage(method, module string) string { if method == http.MethodGet { return module + ".view" } return module + ".manage" } 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{ "/profile", "/file", "/dashboard", "/users", "/cards", "/card-balances", "/card-orders", "/card-pin-orders", "/card-rekwizit-orders", "/payment-cards", "/reasons-cards", "/visa-master-payment-orders", "/payment-history", "/loan-orders", "/loan-types", "/loans-documents", "/loans-repayment", "/loan-paid-off-letters", "/provinces", "/branches", "/currencies", "/payment-settings", }