-
Notifications
You must be signed in to change notification settings - Fork 1
/
permission_require_decorator.go
49 lines (42 loc) · 1.11 KB
/
permission_require_decorator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package meta_gin
import (
"net/http"
"github.com/gin-gonic/gin"
)
type PermissionDecorator struct {
}
func NewPermissionDecorator() *PermissionDecorator {
return &PermissionDecorator{}
}
func (d *PermissionDecorator) Decorate(handler gin.HandlerFunc) gin.HandlerFunc {
requiredPermission := ""
return func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet:
requiredPermission = "can_view"
case http.MethodPost:
requiredPermission = "can_edit"
case http.MethodDelete:
requiredPermission = "can_delete"
case http.MethodPut:
requiredPermission = "can_edit"
case http.MethodPatch:
requiredPermission = "can_edit"
case http.MethodOptions:
requiredPermission = "can_view"
default:
requiredPermission = "can_view"
}
permissions, exists := c.Get("permissions")
if !exists {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Permissions not found"})
return
}
perms := permissions.(map[string]bool)
if !perms[requiredPermission] {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Insufficient permissions"})
return
}
handler(c)
}
}