changed role permission
This commit is contained in:
1 parent
f0ecf23879
commit
323e131216
74 files changed
+2915
-4713
No files matched your search
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -18,291 +19,176 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
roleUser = "user"
|
||||
roleOperator = "operator"
|
||||
roleSuperadmin = "superadmin"
|
||||
guardWeb = "web"
|
||||
guardOperator = "operator"
|
||||
guardAdmin = "admin"
|
||||
adminPrefix = "/api/admin"
|
||||
contextRole = "role"
|
||||
contextGuard = "guard"
|
||||
contextPrincipal = "rbacPrincipal"
|
||||
contextService = "rbacService"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
// Public: no token (login, register, payment callback).
|
||||
func Public() Policy {
|
||||
return Policy{name: "public", read: rule{kind: rulePublic}, write: rule{kind: rulePublic}}
|
||||
}
|
||||
|
||||
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Authenticated: any logged-in user, clients included (profile, file).
|
||||
func Authenticated() Policy {
|
||||
return Policy{name: "authenticated", read: rule{kind: ruleAuthenticated}, write: rule{kind: ruleAuthenticated}}
|
||||
}
|
||||
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, code)
|
||||
if err != nil || !granted {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Staff: any logged-in user whose role scope is not own.
|
||||
func Staff() Policy {
|
||||
return Policy{name: "staff", read: rule{kind: ruleStaff}, write: rule{kind: ruleStaff}}
|
||||
}
|
||||
|
||||
c.Next()
|
||||
// Require: code for every method. Own-scope callers are limited to their
|
||||
// own records, branch-scope callers to their branches.
|
||||
func Require(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code)}
|
||||
return Policy{name: "require:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// RequireStaff: Require, but never for own-scope callers.
|
||||
func RequireStaff(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code), staffOnly: true}
|
||||
return Policy{name: "require-staff:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// Catalog: reference data every logged-in user reads (loan types, branches,
|
||||
// currencies, ...); writes need code and a staff scope.
|
||||
func Catalog(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "catalog:" + string(code),
|
||||
read: rule{kind: ruleAuthenticated},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
// StaffRead: any staff member reads, writes need code.
|
||||
func StaffRead(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "staff-read:" + string(code),
|
||||
read: rule{kind: ruleStaff},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
// Guard runs on every /api/admin request before the route's group
|
||||
// middleware: it resolves the route's policy (deny if none), and for
|
||||
// non-public routes loads the caller's principal into the context.
|
||||
func Guard(service Authorizer) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) {
|
||||
if c.Request.Method == http.MethodOptions || c.FullPath() == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
policy, ok := routes.lookup(c.FullPath())
|
||||
if !ok {
|
||||
abortForbidden(c, "route has no rbac policy", nil)
|
||||
return
|
||||
}
|
||||
if policy.public() {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := requestUserID(c)
|
||||
if !ok {
|
||||
// The group's JwtTokenCheck answers with the proper 401/403.
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
code, guardName, err := service.RoleLookup(c.Request.Context(), userID)
|
||||
principal, err := service.Load(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
logging.GetLogger().Errorf("rbac: load principal %d failed: %v", userID, err)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if principal == nil {
|
||||
abortForbidden(c, "user or role not found", logrus.Fields{"userId": userID})
|
||||
return
|
||||
}
|
||||
|
||||
guard := effectiveGuard(code, guardName)
|
||||
c.Set("id", strconv.FormatInt(userID, 10))
|
||||
c.Set(contextRole, code)
|
||||
c.Set(contextGuard, guard)
|
||||
c.Set(contextPrincipal, principal)
|
||||
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)
|
||||
func (p Policy) handler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
r := p.ruleFor(c.Request.Method)
|
||||
principal := PrincipalFrom(c)
|
||||
if principal == nil {
|
||||
abortForbidden(c, "no principal", nil)
|
||||
return
|
||||
}
|
||||
if !granted {
|
||||
abortForbidden(c, "missing module access for operator path", logrus.Fields{"userId": userID, "module": module})
|
||||
|
||||
switch r.kind {
|
||||
case ruleAuthenticated:
|
||||
case ruleStaff:
|
||||
if principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID})
|
||||
return
|
||||
}
|
||||
case rulePermission:
|
||||
if !principal.Can(perm.Code(r.perm)) {
|
||||
abortForbidden(c, "missing permission", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if r.staffOnly && principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if !enforceScope(c, principal) {
|
||||
return
|
||||
}
|
||||
default:
|
||||
abortForbidden(c, "unknown rule", nil)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
|
||||
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":
|
||||
// enforceScope applies the role's data scope to a permission-gated request.
|
||||
// own: list queries and write bodies are pinned to the caller's user id.
|
||||
// branch: the caller must have branches, and write bodies may only name
|
||||
// those branches (and, on update, users visible in them).
|
||||
func enforceScope(c *gin.Context, p *Principal) bool {
|
||||
switch p.Scope {
|
||||
case ScopeAll:
|
||||
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
|
||||
case ScopeOwn:
|
||||
pinOwnQuery(c, p.UserID)
|
||||
return pinOwnBody(c, p.UserID)
|
||||
case ScopeBranch:
|
||||
if len(p.BranchIDs) == 0 {
|
||||
abortForbidden(c, "branch scope without assigned branches", logrus.Fields{"userId": p.UserID})
|
||||
return false
|
||||
}
|
||||
return branchWriteAllowed(c, p.BranchIDs)
|
||||
}
|
||||
abortForbidden(c, "unknown scope", logrus.Fields{"userId": p.UserID, "scope": p.Scope})
|
||||
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 pinOwnQuery(c *gin.Context, userID int64) {
|
||||
query := c.Request.URL.Query()
|
||||
id := strconv.FormatInt(userID, 10)
|
||||
query.Set("user_id", id)
|
||||
query.Set("created_by", id)
|
||||
c.Request.URL.RawQuery = query.Encode()
|
||||
}
|
||||
|
||||
func enforceOwnWrites(c *gin.Context, userID int64) bool {
|
||||
if !matchesPrefix(adminREST(c.Request.URL.Path), userOwnedPrefixes) {
|
||||
func pinOwnBody(c *gin.Context, userID int64) bool {
|
||||
if !isWrite(c.Request.Method) || c.Request.Method == http.MethodDelete {
|
||||
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)
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
@@ -324,30 +210,92 @@ func enforceOwnWrites(c *gin.Context, userID int64) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func scopeOwnedLists(c *gin.Context, userID int64) {
|
||||
rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/")
|
||||
if rest == "" {
|
||||
return
|
||||
func branchWriteAllowed(c *gin.Context, branchIDs []int64) bool {
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
if !strings.HasPrefix(rest, "/") {
|
||||
rest = "/" + rest
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
owned := false
|
||||
for _, prefix := range userOwnedPrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
owned = true
|
||||
break
|
||||
}
|
||||
var payload struct {
|
||||
BranchId *int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
}
|
||||
if !owned {
|
||||
return
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
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()
|
||||
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
|
||||
abortForbidden(c, "payload branchId not in caller's branches", logrus.Fields{
|
||||
"requestedBranchId": *payload.BranchId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
// A new order's customer has no record in the branch yet; the branchId
|
||||
// check above already scopes the create, so only reassignment (PUT/PATCH)
|
||||
// has to name a user visible in the caller's branches.
|
||||
if c.Request.Method == http.MethodPost || payload.UserId == nil || *payload.UserId <= 0 {
|
||||
return true
|
||||
}
|
||||
service := serviceFrom(c)
|
||||
if service == nil {
|
||||
abortForbidden(c, "no rbac service", nil)
|
||||
return false
|
||||
}
|
||||
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 caller's branches", logrus.Fields{
|
||||
"requestedUserId": *payload.UserId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func readBody(c *gin.Context) ([]byte, bool) {
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return nil, false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
return body, true
|
||||
}
|
||||
|
||||
func isWrite(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// abortForbidden logs which rbac check denied the request before writing the
|
||||
// 403, since appresult.ErrForbidden alone doesn't say.
|
||||
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)
|
||||
}
|
||||
|
||||
func requestUserID(c *gin.Context) (int64, bool) {
|
||||
@@ -408,278 +356,3 @@ func bearerToken(header string) string {
|
||||
}
|
||||
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 "<module>.view"/"<module>.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",
|
||||
}
|
||||
Reference in new issue
Block a user