base_auth.go 13 KB

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