auth_middleware.go 6.8 KB

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