32 lines
618 B
Go
32 lines
618 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
"github.com/muyuqingfeng/iloom/shared/pkg/response"
|
||
|
|
)
|
||
|
|
|
||
|
|
func RoleRequired(roles ...string) gin.HandlerFunc {
|
||
|
|
allowed := make(map[string]bool, len(roles))
|
||
|
|
for _, r := range roles {
|
||
|
|
allowed[r] = true
|
||
|
|
}
|
||
|
|
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
role, exists := c.Get("role")
|
||
|
|
if !exists {
|
||
|
|
response.Forbidden(c, "role not found in context")
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
roleStr, ok := role.(string)
|
||
|
|
if !ok || !allowed[roleStr] {
|
||
|
|
response.Error(c, 403, response.ErrCodeRoleMismatch, "insufficient role permission")
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|