39 lines
966 B
Go
39 lines
966 B
Go
package rbac
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"online-back/internal/appresult"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// 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)
|
|
return
|
|
}
|
|
|
|
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
|
return
|
|
}
|
|
|
|
granted, err := service.HasPermission(c.Request.Context(), userID, code)
|
|
if err != nil || !granted {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|