token.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package token
  2. import (
  3. "errors"
  4. "fmt"
  5. "mtp2_if/global/e"
  6. "mtp2_if/rediscli"
  7. "net/http"
  8. "strings"
  9. "github.com/gin-gonic/gin"
  10. )
  11. // CheckToken Token校验
  12. func CheckToken(loginid string, token string) error {
  13. key := fmt.Sprintf("monitor:online_loginid::%s", loginid)
  14. field := "Token"
  15. realToken, err := rediscli.GetRedisClient().HGet(key, field).Result()
  16. if err != nil {
  17. return err
  18. }
  19. if realToken != token {
  20. return errors.New("token is invalid")
  21. }
  22. return nil
  23. }
  24. // Auth Token校验中间件
  25. func Auth() gin.HandlerFunc {
  26. return func(c *gin.Context) {
  27. var code int
  28. var data interface{}
  29. code = e.SUCCESS
  30. token := c.GetHeader("Authorization")
  31. if token == "" {
  32. // Token缺失
  33. code = e.ERROR_AUTH_CHECK_TOKEN_MISSING
  34. } else {
  35. // 获取loginid
  36. s := strings.Split(token, "_")
  37. loginid := s[0]
  38. if err := CheckToken(loginid, token); err != nil {
  39. // Token错误
  40. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  41. }
  42. }
  43. // Token检验失败
  44. if code != e.SUCCESS {
  45. c.JSON(http.StatusUnauthorized, gin.H{
  46. "code": code,
  47. "msg": e.GetMsg(code),
  48. "data": data,
  49. })
  50. c.Abort()
  51. return
  52. }
  53. // FIXME: - 针对POST接口,应判断传入TOKEN对应的用户是否正确(比如判断UserID或AccountID是否对得上等),后期处理
  54. // Token检验成功
  55. c.Next()
  56. }
  57. }