广告涉及的mq都放这里
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 2 месеца
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package mw
  2. import (
  3. "applet/app/db"
  4. "applet/app/e"
  5. "applet/app/md"
  6. "applet/app/utils"
  7. "applet/app/utils/cache"
  8. "applet/app/utils/logx"
  9. "errors"
  10. "fmt"
  11. "strings"
  12. "github.com/gin-gonic/gin"
  13. )
  14. // AuthJWT is jwt middleware
  15. func AuthJWT(c *gin.Context) {
  16. authHeader := c.Request.Header.Get("Authorization")
  17. if authHeader == "" {
  18. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 不能为空"))
  19. return
  20. }
  21. // 按空格分割
  22. parts := strings.SplitN(authHeader, " ", 2)
  23. if !(len(parts) == 2 && parts[0] == "Bearer") {
  24. e.OutErr(c, e.ERR_TOKEN_FORMAT, errors.New("token 格式不对"))
  25. return
  26. }
  27. // parts[1]是token
  28. mc, err := utils.ParseToken(parts[1])
  29. if err != nil {
  30. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 过期或无效"))
  31. return
  32. }
  33. //fmt.Println(mc.UID)
  34. // 获取user
  35. u, err := db.UserFindByID(db.DBs[c.GetString("mid")], mc.UID)
  36. if err != nil {
  37. e.OutErr(c, e.ERR_DB_ORM, err)
  38. return
  39. }
  40. if u == nil {
  41. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 过期或无效"))
  42. return
  43. }
  44. // 检验账号是否未激活或被冻结
  45. switch u.State {
  46. case 0:
  47. e.OutErr(c, e.ERR_USER_NO_ACTIVE)
  48. return
  49. case 2:
  50. e.OutErr(c, e.ERR_USER_IS_BAN)
  51. return
  52. }
  53. // 校验是否和缓存的token一致,只能有一个token 是真实有效
  54. key := fmt.Sprintf("%s:token:%s", c.GetString("mid"), u.Username)
  55. //fmt.Println(key)
  56. cjwt, err := cache.GetString(key)
  57. //fmt.Println(cjwt)
  58. if err != nil {
  59. logx.Warn(err)
  60. goto NOCACHE
  61. }
  62. if parts[1] != cjwt {
  63. e.OutErr(c, e.ERR_TOKEN_AUTH, errors.New("token expired"))
  64. return
  65. }
  66. NOCACHE:
  67. // 获取user profile
  68. up, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], mc.UID)
  69. if err != nil {
  70. e.OutErr(c, e.ERR_DB_ORM, err)
  71. return
  72. }
  73. // 获取user 等级
  74. ul, err := db.UserLevelByID(db.DBs[c.GetString("mid")], u.Level)
  75. if err != nil {
  76. e.OutErr(c, e.ERR_DB_ORM, err)
  77. return
  78. }
  79. user := &md.User{
  80. Info: u,
  81. Profile: up,
  82. Level: ul,
  83. }
  84. // 将当前请求的username信息保存到请求的上下文c上
  85. c.Set("user", user)
  86. // 异步处理 有效会员和新会员
  87. c.Next() // 后续的处理函数可以用过c.Get("user")来获取当前请求的用户信息
  88. }