token.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package token
  2. import (
  3. "errors"
  4. "fmt"
  5. "mtp2_if/rediscli"
  6. "net/http"
  7. "strings"
  8. "github.com/gin-gonic/gin"
  9. )
  10. // CheckToken Token校验
  11. func CheckToken(loginid string, token string) error {
  12. key := fmt.Sprintf("monitor:online_loginid::%s", loginid)
  13. field := "Token"
  14. realToken, err := rediscli.GetRedisClient().HGet(key, field).Result()
  15. if err != nil {
  16. return err
  17. }
  18. if realToken != token {
  19. return errors.New("token is invalid")
  20. }
  21. return nil
  22. }
  23. // Auth Token校验中间件
  24. func Auth() gin.HandlerFunc {
  25. return func(c *gin.Context) {
  26. var code int
  27. var msg string
  28. var data interface{}
  29. code = 0
  30. token := c.GetHeader("token")
  31. if token == "" {
  32. code = 3001
  33. msg = "缺少token"
  34. } else {
  35. // 获取loginid
  36. s := strings.Split(token, "_")
  37. loginid := s[0]
  38. if err := CheckToken(loginid, token); err != nil {
  39. code = 3002
  40. msg = "token校验失败"
  41. }
  42. }
  43. // Token检验失败
  44. if code != 0 {
  45. c.JSON(http.StatusUnauthorized, gin.H{
  46. "code": code,
  47. "msg": msg,
  48. "data": data,
  49. })
  50. c.Abort()
  51. return
  52. }
  53. // Token检验成功
  54. c.Next()
  55. }
  56. }