base_auth.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_mobile/cache"
  5. "eta/eta_mobile/models/system"
  6. "eta/eta_mobile/services/alarm_msg"
  7. "eta/eta_mobile/services/data"
  8. "fmt"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/beego/beego/v2/server/web"
  15. "eta/eta_mobile/models"
  16. "eta/eta_mobile/utils"
  17. )
  18. type AfterHandle func(bodyByte []byte) error
  19. // AfterHandlerUrlMap 结束后待处理的url
  20. var AfterHandlerUrlMap = map[string][]AfterHandle{
  21. "/adminapi/datamanage/chart_info/save": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表保存接口
  22. //"/adminapi/datamanage/chart_info/detail": data.DeleteChartInfoDataRedis,
  23. "/adminapi/datamanage/chart_info/edit": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表编辑接口
  24. "/adminapi/datamanage/chart_info/refresh": {data.DeleteChartInfoDataRedis}, //图表刷新接口
  25. "/adminapi/datamanage/chart_info/add": {data.DeleteChartClassifyRedis}, //图表添加接口
  26. "/adminapi/datamanage/chart_classify/delete": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表删除、图表分类删除
  27. "/adminapi/datamanage/chart_classify/add": {data.DeleteChartClassifyRedis}, //新增图表分类接口
  28. "/adminapi/datamanage/chart_classify/edit": {data.DeleteChartClassifyRedis}, //编辑图表分类接口
  29. "/adminapi/datamanage/chart_classify/move": {data.DeleteChartClassifyRedis}, //移动图表分类接口
  30. "/adminapi/datamanage/chart_info/move": {data.DeleteChartClassifyRedis}, //移动图表接口
  31. "/adminapi/datamanage/chart_info/copy": {data.DeleteChartClassifyRedis}, //图表另存为接口
  32. }
  33. type BaseAuthController struct {
  34. web.Controller
  35. SysUser *system.Admin
  36. }
  37. func (this *BaseAuthController) Prepare() {
  38. fmt.Println("enter prepare")
  39. method := this.Ctx.Input.Method()
  40. uri := this.Ctx.Input.URI()
  41. fmt.Println("Url:", uri)
  42. if method != "HEAD" {
  43. if method == "POST" || method == "GET" {
  44. authorization := this.Ctx.Input.Header("authorization")
  45. if authorization == "" {
  46. authorization = this.Ctx.Input.Header("Authorization")
  47. }
  48. if authorization == "" {
  49. newAuthorization := this.GetString("authorization")
  50. if newAuthorization != `` {
  51. authorization = "authorization=" + newAuthorization
  52. } else {
  53. newAuthorization = this.GetString("Authorization")
  54. authorization = "authorization=" + newAuthorization
  55. }
  56. } else {
  57. if strings.Contains(authorization, ";") {
  58. authorization = strings.Replace(authorization, ";", "$", 1)
  59. }
  60. }
  61. if authorization == "" {
  62. strArr := strings.Split(uri, "?")
  63. for k, v := range strArr {
  64. fmt.Println(k, v)
  65. }
  66. if len(strArr) > 1 {
  67. authorization := strArr[1]
  68. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  69. fmt.Println(authorization)
  70. }
  71. }
  72. if authorization == "" {
  73. this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  74. this.StopRun()
  75. return
  76. }
  77. authorizationArr := strings.Split(authorization, "$")
  78. if len(authorizationArr) <= 1 {
  79. this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  80. this.StopRun()
  81. return
  82. }
  83. tokenStr := authorizationArr[0]
  84. tokenArr := strings.Split(tokenStr, "=")
  85. token := tokenArr[1]
  86. accountStr := authorizationArr[1]
  87. accountArr := strings.Split(accountStr, "=")
  88. account := accountArr[1]
  89. //校验token是否合法
  90. // JWT校验Token和Account
  91. if !utils.CheckToken(account, token) {
  92. this.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false)
  93. this.StopRun()
  94. return
  95. }
  96. session, err := system.GetSysSessionByToken(token)
  97. if err != nil {
  98. if err.Error() == utils.ErrNoRow() {
  99. this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  100. this.StopRun()
  101. return
  102. }
  103. this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  104. this.StopRun()
  105. return
  106. }
  107. if session == nil {
  108. this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  109. this.StopRun()
  110. return
  111. }
  112. if time.Now().After(session.ExpiredTime) {
  113. this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  114. this.StopRun()
  115. return
  116. }
  117. admin, err := system.GetSysUserById(session.SysUserId)
  118. if err != nil {
  119. if err.Error() == utils.ErrNoRow() {
  120. this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false)
  121. this.StopRun()
  122. return
  123. }
  124. this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false)
  125. this.StopRun()
  126. return
  127. }
  128. if admin == nil {
  129. this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
  130. this.StopRun()
  131. return
  132. }
  133. //如果不是启用状态
  134. if admin.Enabled != 1 {
  135. this.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false)
  136. this.StopRun()
  137. return
  138. }
  139. // 如果当前登录态是不可信设备的,那么需要做过期校验
  140. if session.IsRemember != 1 {
  141. loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id)
  142. loginInfo, _ := utils.Rc.RedisString(loginKey)
  143. if loginInfo == `` {
  144. this.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  145. this.StopRun()
  146. return
  147. }
  148. if loginInfo != "1" {
  149. msg := `该账号于` + admin.LastLoginTime + "在其他网络登录。此客户端已退出登录。"
  150. this.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  151. this.StopRun()
  152. return
  153. }
  154. utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  155. // 不信任名单也同步更新
  156. noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
  157. utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
  158. }
  159. admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
  160. this.SysUser = admin
  161. } else {
  162. this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  163. this.StopRun()
  164. return
  165. }
  166. }
  167. }
  168. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  169. // 方法处理完后,需要后置处理的业务逻辑
  170. if handlerList, ok := AfterHandlerUrlMap[c.Ctx.Request.URL.Path]; ok {
  171. for _, handler := range handlerList {
  172. handler(c.Ctx.Input.RequestBody)
  173. }
  174. }
  175. var (
  176. hasIndent = false
  177. hasEncoding = false
  178. )
  179. if web.BConfig.RunMode == web.PROD {
  180. hasIndent = false
  181. }
  182. if len(encoding) > 0 && encoding[0] == true {
  183. hasEncoding = true
  184. }
  185. if c.Data["json"] == nil {
  186. //go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  187. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  188. go alarm_msg.SendAlarmMsg(body, 1)
  189. return
  190. }
  191. baseRes := c.Data["json"].(*models.BaseResponse)
  192. if baseRes != nil && baseRes.Ret != 408 {
  193. body, _ := json.Marshal(baseRes)
  194. var requestBody string
  195. method := c.Ctx.Input.Method()
  196. if method == "GET" {
  197. requestBody = c.Ctx.Request.RequestURI
  198. } else {
  199. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  200. requestBody = string(c.Ctx.Input.RequestBody)
  201. }
  202. if baseRes.Ret != 200 && baseRes.IsSendEmail {
  203. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"<br/> "+"Params"+requestBody+" <br/>"+"ErrMsg:"+baseRes.ErrMsg+";<br/>Msg:"+baseRes.Msg+";<br/> Body:"+string(body)+"<br/>"+c.SysUser.RealName, utils.EmailSendToUsers)
  204. body := "URI:" + c.Ctx.Input.URI() + "<br/> " + "Params" + requestBody + " <br/>" + "ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + "<br/>" + c.SysUser.RealName
  205. go alarm_msg.SendAlarmMsg(body, 1)
  206. }
  207. if baseRes.IsAddLog && c.SysUser != nil {
  208. go cache.RecordNewLogs(c.SysUser.AdminId, requestBody, string(body), c.SysUser.RealName, c.Ctx.Input.IP(), c.Ctx.Input.URI())
  209. }
  210. }
  211. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  212. }
  213. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  214. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  215. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  216. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  217. var content []byte
  218. var err error
  219. if hasIndent {
  220. content, err = json.MarshalIndent(data, "", " ")
  221. } else {
  222. content, err = json.Marshal(data)
  223. }
  224. if err != nil {
  225. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  226. return err
  227. }
  228. ip := c.Ctx.Input.IP()
  229. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  230. if err != nil {
  231. requestBody = string(c.Ctx.Input.RequestBody)
  232. }
  233. if requestBody == "" {
  234. requestBody = c.Ctx.Input.URI()
  235. }
  236. c.logUri(content, requestBody, ip)
  237. if coding {
  238. content = []byte(utils.StringsToJSON(string(content)))
  239. }
  240. // 如果不是debug分支的话,那么需要加密返回
  241. if utils.RunMode != "debug" {
  242. content = utils.DesBase64Encrypt(content, utils.DesKey)
  243. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  244. content = []byte(`"` + string(content) + `"`)
  245. }
  246. if coding {
  247. content = []byte(utils.StringsToJSON(string(content)))
  248. }
  249. return c.Ctx.Output.Body(content)
  250. }
  251. func GetSysUserRoleTypeCode(roleTypeCode string) string {
  252. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
  253. roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
  254. return utils.ROLE_TYPE_CODE_FICC_SELLER
  255. }
  256. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
  257. roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
  258. return utils.ROLE_TYPE_CODE_RAI_SELLER
  259. }
  260. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
  261. return utils.ROLE_TYPE_CODE_RAI_GROUP
  262. }
  263. if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
  264. return utils.ROLE_TYPE_CODE_ADMIN
  265. }
  266. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  267. return utils.ROLE_TYPE_CODE_FICC_ADMIN
  268. }
  269. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
  270. return utils.ROLE_TYPE_CODE_FICC_TEAM
  271. }
  272. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
  273. return utils.ROLE_TYPE_CODE_FICC_GROUP
  274. }
  275. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  276. return utils.ROLE_TYPE_CODE_RAI_ADMIN
  277. }
  278. if roleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
  279. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  280. }
  281. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR {
  282. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  283. }
  284. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR {
  285. return utils.ROLE_TYPE_CODE_RAI_RESEARCHR
  286. }
  287. //合规
  288. if roleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE {
  289. return utils.ROLE_TYPE_CODE_COMPLIANCE
  290. }
  291. //财务
  292. if roleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
  293. return utils.ROLE_TYPE_CODE_FINANCE
  294. }
  295. return ""
  296. }
  297. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  298. authorization := ""
  299. method := c.Ctx.Input.Method()
  300. uri := c.Ctx.Input.URI()
  301. fmt.Println("Url:", uri)
  302. if method != "HEAD" {
  303. if method == "POST" || method == "GET" {
  304. authorization = c.Ctx.Input.Header("authorization")
  305. if authorization == "" {
  306. authorization = c.Ctx.Input.Header("Authorization")
  307. }
  308. if authorization == "" {
  309. newAuthorization := c.GetString("authorization")
  310. if newAuthorization != `` {
  311. authorization = "authorization=" + newAuthorization
  312. } else {
  313. newAuthorization = c.GetString("Authorization")
  314. authorization = "authorization=" + newAuthorization
  315. }
  316. } else {
  317. if strings.Contains(authorization, ";") {
  318. authorization = strings.Replace(authorization, ";", "$", 1)
  319. }
  320. }
  321. if authorization == "" {
  322. strArr := strings.Split(uri, "?")
  323. for k, v := range strArr {
  324. fmt.Println(k, v)
  325. }
  326. if len(strArr) > 1 {
  327. authorization = strArr[1]
  328. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  329. fmt.Println(authorization)
  330. }
  331. }
  332. }
  333. }
  334. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  335. return
  336. }