token.go 1.4 KB

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