Dragonfly2

Форк
0
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

17
package middlewares
18

19
import (
20
	"fmt"
21
	"net/http"
22

23
	"github.com/casbin/casbin/v2"
24
	"github.com/gin-gonic/gin"
25

26
	logger "d7y.io/dragonfly/v2/internal/dflog"
27
	"d7y.io/dragonfly/v2/manager/permission/rbac"
28
)
29

30
func RBAC(e *casbin.Enforcer) gin.HandlerFunc {
31
	return func(c *gin.Context) {
32
		action := rbac.HTTPMethodToAction(c.Request.Method)
33
		permission, err := rbac.GetAPIGroupName(c.Request.URL.Path)
34
		if err != nil {
35
			logger.Errorf("get api group name error: %s", err)
36
			c.JSON(http.StatusUnauthorized, gin.H{
37
				"message": "permission validate error!",
38
			})
39
			c.Abort()
40
			return
41
		}
42

43
		id, ok := c.Get("id")
44
		if !ok {
45
			c.JSON(http.StatusUnauthorized, gin.H{
46
				"message": "permission validate error!",
47
			})
48
			c.Abort()
49
			return
50
		}
51

52
		if ok, err := e.Enforce(fmt.Sprint(id.(float64)), permission, action); err != nil {
53
			logger.Errorf("RBAC validate error: %s", err)
54
			c.JSON(http.StatusUnauthorized, gin.H{
55
				"message": "permission validate error!",
56
			})
57
			c.Abort()
58
			return
59
		} else if !ok {
60
			c.JSON(http.StatusUnauthorized, gin.H{
61
				"message": "permission deny",
62
			})
63
			c.Abort()
64
			return
65
		}
66

67
		c.Next()
68
	}
69
}
70

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.