Files
online-backend/internal/identity/rbac/middleware.go
GuwandykA 28509eb4ca
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled
Add backups, currencies and dashboard APIs, and scope access by guard_name.
Web users may only CRUD their own records, operators stay in assigned branches, and admin/manager/superadmin keep full access.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 18:14:47 +05:00

458 lines
10 KiB
Go

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"
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:
c.Next()
return
}
}
}
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) {
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 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:
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":
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
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))
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",
}
var userSelfPrefixes = []string{
"/profile",
"/file",
}
var userOwnedPrefixes = []string{
"/cards",
"/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 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) {
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",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/loan-orders",
"/loans-repayment",
"/loan-paid-off-letters",
}
var operatorGetPrefixes = []string{
"/profile",
"/file",
"/dashboard",
"/users",
"/cards",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
"/loan-orders",
"/loan-types",
"/loans-documents",
"/loans-repayment",
"/loan-paid-off-letters",
"/provinces",
"/branches",
"/currencies",
}