Dragonfly2
69 строк · 1.7 Кб
1/*
2* Copyright 2020 The Dragonfly Authors
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17package middlewares
18
19import (
20"fmt"
21"net/http"
22
23"github.com/casbin/casbin/v2"
24"github.com/gin-gonic/gin"
25
26logger "d7y.io/dragonfly/v2/internal/dflog"
27"d7y.io/dragonfly/v2/manager/permission/rbac"
28)
29
30func RBAC(e *casbin.Enforcer) gin.HandlerFunc {
31return func(c *gin.Context) {
32action := rbac.HTTPMethodToAction(c.Request.Method)
33permission, err := rbac.GetAPIGroupName(c.Request.URL.Path)
34if err != nil {
35logger.Errorf("get api group name error: %s", err)
36c.JSON(http.StatusUnauthorized, gin.H{
37"message": "permission validate error!",
38})
39c.Abort()
40return
41}
42
43id, ok := c.Get("id")
44if !ok {
45c.JSON(http.StatusUnauthorized, gin.H{
46"message": "permission validate error!",
47})
48c.Abort()
49return
50}
51
52if ok, err := e.Enforce(fmt.Sprint(id.(float64)), permission, action); err != nil {
53logger.Errorf("RBAC validate error: %s", err)
54c.JSON(http.StatusUnauthorized, gin.H{
55"message": "permission validate error!",
56})
57c.Abort()
58return
59} else if !ok {
60c.JSON(http.StatusUnauthorized, gin.H{
61"message": "permission deny",
62})
63c.Abort()
64return
65}
66
67c.Next()
68}
69}
70