admin_middleware.go 814 B

1234567891011121314151617181920212223242526272829303132
  1. package middlewares
  2. import (
  3. "github.com/bytedance/sonic"
  4. "github.com/gin-gonic/gin"
  5. "project_management/app/e"
  6. "project_management/nats"
  7. "strings"
  8. "time"
  9. )
  10. func AdminMiddleware() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. header := c.GetHeader("Authorization")
  13. split := strings.Split(header, ":")
  14. request, err := nats.Nats.Request("login_token_validation", []byte(split[1]), 3*time.Second)
  15. if err != nil {
  16. e.ResponseWithMsg(c, e.TokenIsInvalid, e.TokenIsInvalid.GetMsg())
  17. } else {
  18. var response UserResponse
  19. sonic.Unmarshal(request.Data, &response)
  20. users := response.User.(map[string]interface{})
  21. role := users["role"].(string)
  22. if role == "admin" {
  23. c.Next()
  24. } else {
  25. e.ResponseWithMsg(c, e.TokenIsInvalid, e.TokenIsInvalid.GetMsg())
  26. c.Abort()
  27. }
  28. }
  29. }
  30. }