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" ) 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.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 *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", }