permissions.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package permission
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/kptyun/KPTCOMM/middleware/inject"
  6. jwtGet "github.com/kptyun/KPTCOMM/pkg/util"
  7. "net/http"
  8. "strings"
  9. )
  10. func CasbinMiddleware() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. Authorization := c.GetHeader("Authorization")
  13. token := strings.Split(Authorization, " ")
  14. t, _ := jwt.Parse(token[1], func(*jwt.Token) (interface{}, error) {
  15. return jwtGet.JwtSecret, nil
  16. })
  17. fmt.Println(jwtGet.GetIdFromClaims("username", t.Claims), c.Request.URL.Path, c.Request.Method)
  18. if b, err := inject.Obj.Enforcer.EnforceSafe(jwtGet.GetIdFromClaims("username", t.Claims), c.Request.URL.Path, c.Request.Method); err != nil {
  19. c.JSON(http.StatusUnauthorized, gin.H{
  20. "code": http.StatusOK,
  21. "data": err,
  22. "msg": "ok",
  23. })
  24. c.Abort()
  25. return
  26. } else if !b {
  27. c.JSON(http.StatusUnauthorized, gin.H{
  28. "code": http.StatusForbidden,
  29. "data": "登录用户 没有权限",
  30. "msg": "ok",
  31. })
  32. c.Abort()
  33. return
  34. }
  35. c.Next()
  36. }
  37. }