auth_middleware.go 5.9 KB

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