auth_middleware.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package middleware
  2. import (
  3. "eta/eta_mini_ht_api/common/component/cache"
  4. logger "eta/eta_mini_ht_api/common/component/log"
  5. "eta/eta_mini_ht_api/common/exception"
  6. "eta/eta_mini_ht_api/common/utils/jwt"
  7. "eta/eta_mini_ht_api/common/utils/redis"
  8. stringUtils "eta/eta_mini_ht_api/common/utils/string"
  9. "eta/eta_mini_ht_api/controllers"
  10. "eta/eta_mini_ht_api/service/user"
  11. "github.com/beego/beego/v2/server/web"
  12. "github.com/beego/beego/v2/server/web/context"
  13. "github.com/google/uuid"
  14. "strings"
  15. )
  16. var (
  17. rdCache *cache.RedisCache
  18. )
  19. const (
  20. ILLEGALUSER = "用户信息异常"
  21. UNAUTHORIZED = "请重新登录"
  22. TOKENEXPIRED = "token过期"
  23. LOGINREQURED = "重新登录"
  24. FORBIDDEN = "禁止访问"
  25. NOTFOUND = "未找到"
  26. authorization = "Authorization"
  27. baseUrl = "/htapi"
  28. Bearer = "Bearer"
  29. )
  30. func rd() *cache.RedisCache {
  31. if rdCache == nil {
  32. rdCache = cache.GetInstance()
  33. }
  34. return rdCache
  35. }
  36. var detailRoutes = []string{
  37. "/media/media",
  38. "/report/report",
  39. "/media/list",
  40. "/report/list",
  41. "/media/search",
  42. "/report/search",
  43. "/report/hotRankedList",
  44. "/report/publishRankedList",
  45. "/home/search",
  46. }
  47. var publicRoutes = []string{
  48. "/auth/areaCodes",
  49. "/auth/wxAppid",
  50. "/auth/notice",
  51. "/auth/disclaimer",
  52. "/auth/refreshToken",
  53. "/auth/sendCode",
  54. "/user/bind_gzh",
  55. "/user/wx/notify",
  56. "/webhook/*",
  57. }
  58. var privateRoutes = []string{
  59. "/user/profile",
  60. "/user/followAnalyst",
  61. "/user/followAnalysts",
  62. "/user/followingAnalystList",
  63. "/user/readMessages",
  64. "/user/readMessage",
  65. "/user/feedback",
  66. "/webhook/*",
  67. "/user/checkFollowStatus",
  68. "/user/followingAnalysts",
  69. "/user/message",
  70. "/analyst/analystDetail",
  71. "/analyst/list",
  72. "/analyst/reportList",
  73. "/analyst/mediaList",
  74. "/media/count",
  75. "/report/count",
  76. "/product/*",
  77. "/order/*",
  78. "/user/order/*",
  79. }
  80. func AuthMiddleware() web.FilterFunc {
  81. return func(ctx *context.Context) {
  82. threadId := strings.ReplaceAll(uuid.New().String(), "-", "")
  83. ctx.Input.SetData("threadId", threadId)
  84. path := ctx.Input.URL()
  85. logger.Info("请求路径:%v", path)
  86. if !allowed(path) {
  87. rep := unAuthorized()
  88. auth := ctx.Input.Header(authorization)
  89. if auth == "" {
  90. logger.Error("token信息不存在")
  91. _ = ctx.JSONResp(rep)
  92. return
  93. }
  94. parts := strings.Split(auth, " ")
  95. if len(parts) != 2 || parts[0] != Bearer {
  96. logger.Error("token参数不符合格式" + auth)
  97. _ = ctx.JSONResp(rep)
  98. return
  99. }
  100. info, err := jwt.CheckToken(parts[1])
  101. if err != nil {
  102. logger.Error("token无效:%v", err)
  103. _ = ctx.JSONResp(rep)
  104. return
  105. }
  106. //组装用户信息
  107. var userInfo user.User
  108. userInfo, err = user.GetUserByOpenId(info.OpenId)
  109. if err != nil {
  110. logger.Error("获取用户信息失败:%v", err)
  111. _ = ctx.JSONResp(illegalUser())
  112. return
  113. }
  114. //校验redis中是否合法
  115. redisToken := rd().GetString(redis.GenerateTokenKey(info.OpenId))
  116. if redisToken == "" {
  117. logger.Error("token无效:token已失效")
  118. //重置用户状态为登出
  119. //err = userService.UserLogout(userInfo.Id)
  120. //if err != nil {
  121. // logger.Error("重置用户状态失败:%v", err)
  122. //}
  123. _ = ctx.JSONResp(tokenExpired())
  124. return
  125. }
  126. if redisToken != parts[1] {
  127. logger.Error("token无效:用户token已刷新")
  128. _ = ctx.JSONResp(tokenExpired())
  129. return
  130. }
  131. if needCheckLoginStatus(path) {
  132. if info.TokenType != jwt.AccessToken || info.Mobile == "-" || info.Mobile == "" {
  133. logger.Error("token信息异常,当前token类型为:%v", jwt.GuestToken)
  134. _ = ctx.JSONResp(LoginRequired())
  135. return
  136. }
  137. }
  138. //详情信息需要登录token才能看到全部
  139. if loginForDetail(path) {
  140. if info.TokenType != jwt.AccessToken || info.Mobile == "-" || info.Mobile == "" {
  141. ctx.Input.SetData("detailType", "logout")
  142. } else {
  143. ctx.Input.SetData("detailType", "login")
  144. }
  145. }
  146. //if userInfo.Mobile == "-" && path != baseUrl+"/auth/login" {
  147. // logger.Error("用户手机号为空:%v", err)
  148. // _ = ctx.JSONResp(illegalUser())
  149. // return
  150. //}
  151. ctx.Input.SetData("user", userInfo)
  152. return
  153. }
  154. return
  155. }
  156. }
  157. func unAuthorized() controllers.BaseResponse {
  158. return controllers.BaseResponse{
  159. Ret: 401,
  160. Msg: UNAUTHORIZED,
  161. ErrMsg: exception.GetMsg(exception.Unauthorized),
  162. }
  163. }
  164. func webhookSysErr(message string) controllers.BaseResponse {
  165. return controllers.BaseResponse{
  166. Ret: 401,
  167. Msg: message,
  168. ErrMsg: exception.GetMsg(exception.SysError),
  169. }
  170. }
  171. func webhookUnauthorized(message string) controllers.BaseResponse {
  172. return controllers.BaseResponse{
  173. Ret: 401,
  174. Msg: message,
  175. ErrMsg: exception.GetMsg(exception.Unauthorized),
  176. }
  177. }
  178. func tokenExpired() controllers.BaseResponse {
  179. return controllers.BaseResponse{
  180. Ret: 401,
  181. Msg: TOKENEXPIRED,
  182. ErrMsg: exception.GetMsg(exception.Unauthorized),
  183. }
  184. }
  185. func LoginRequired() controllers.BaseResponse {
  186. return controllers.BaseResponse{
  187. Ret: 408,
  188. Msg: LOGINREQURED,
  189. ErrMsg: exception.GetMsg(exception.Unauthorized),
  190. }
  191. }
  192. func illegalUser() controllers.BaseResponse {
  193. return controllers.BaseResponse{
  194. Ret: 401,
  195. Msg: ILLEGALUSER,
  196. ErrMsg: exception.GetMsg(exception.Unauthorized),
  197. }
  198. }
  199. func allowed(path string) bool {
  200. for _, p := range publicRoutes {
  201. if stringUtils.IsBlank(p) {
  202. continue
  203. }
  204. src := baseUrl + p
  205. if strings.HasSuffix(p, "*") {
  206. target := src[:len(src)-1]
  207. if strings.HasPrefix(path, target) {
  208. return true
  209. }
  210. } else {
  211. if src == path {
  212. return true
  213. }
  214. }
  215. }
  216. return false
  217. }
  218. func loginForDetail(path string) bool {
  219. for _, p := range detailRoutes {
  220. if stringUtils.IsBlank(p) {
  221. continue
  222. }
  223. src := baseUrl + p
  224. if strings.HasSuffix(p, "*") {
  225. target := src[:len(src)-1]
  226. if strings.HasPrefix(path, target) {
  227. return true
  228. }
  229. } else {
  230. if src == path {
  231. return true
  232. }
  233. }
  234. }
  235. return false
  236. }
  237. func needCheckLoginStatus(path string) bool {
  238. for _, p := range privateRoutes {
  239. if stringUtils.IsBlank(p) {
  240. continue
  241. }
  242. src := baseUrl + p
  243. if strings.HasSuffix(p, "*") {
  244. target := src[:len(src)-1]
  245. if strings.HasPrefix(path, target) {
  246. return true
  247. }
  248. } else {
  249. if src == path {
  250. return true
  251. }
  252. }
  253. }
  254. return false
  255. }