permissions.go 1.0 KB

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