base_auth.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_api/cache"
  5. "eta/eta_api/models/system"
  6. "eta/eta_api/services/alarm_msg"
  7. "eta/eta_api/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_api/models"
  16. "eta/eta_api/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/multiple_graph/chart/save": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //批量图表保存接口
  23. //"/adminapi/datamanage/chart_info/detail": data.DeleteChartInfoDataRedis,
  24. "/adminapi/datamanage/chart_info/edit": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表编辑接口
  25. "/adminapi/datamanage/chart_info/refresh": {data.DeleteChartInfoDataRedis}, //图表刷新接口
  26. "/adminapi/datamanage/chart_info/add": {data.DeleteChartClassifyRedis}, //图表添加接口
  27. "/adminapi/datamanage/chart_classify/delete": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表删除、图表分类删除
  28. "/adminapi/datamanage/chart_classify/add": {data.DeleteChartClassifyRedis}, //新增图表分类接口
  29. "/adminapi/datamanage/chart_classify/edit": {data.DeleteChartClassifyRedis}, //编辑图表分类接口
  30. "/adminapi/datamanage/chart_classify/move": {data.DeleteChartClassifyRedis}, //移动图表分类接口
  31. "/adminapi/datamanage/chart_info/move": {data.DeleteChartClassifyRedis}, //移动图表接口
  32. "/adminapi/datamanage/chart_info/copy": {data.DeleteChartClassifyRedis}, //图表另存为接口
  33. }
  34. var AdminOperateRecordMap = map[string]string{
  35. "/adminapi/pptv2/saveLog": "/adminapi/pptv2/saveLog",
  36. "/adminapi/report/saveReportContent": "/adminapi/report/saveReportContent",
  37. "/adminapi/datamanage/chart_info/common/detail/from_unique_code": "/adminapi/datamanage/chart_info/common/detail/from_unique_code",
  38. "/adminapi/english_report/saveReportContent": "/adminapi/english_report/saveReportContent",
  39. "/adminapi/custom/message/listV2": "/adminapi/custom/message/listV2",
  40. "/adminapi/sysuser/check_pwd": "/adminapi/sysuser/check_pwd",
  41. "/adminapi/system/menu/list": "/adminapi/system/menu/list",
  42. }
  43. type BaseAuthController struct {
  44. web.Controller
  45. SysUser *system.Admin
  46. Session *system.SysSession
  47. Lang string `description:"当前语言类型,中文:zh;英文:en;默认:zh"`
  48. }
  49. func (c *BaseAuthController) Prepare() {
  50. //fmt.Println("enter prepare")
  51. method := c.Ctx.Input.Method()
  52. uri := c.Ctx.Input.URI()
  53. //fmt.Println("Url:", uri)
  54. if method != "HEAD" {
  55. if method == "POST" || method == "GET" {
  56. // 当前语言
  57. {
  58. lang := c.Ctx.Input.Header("Lang")
  59. if lang == "" {
  60. lang = utils.ZhLangVersion
  61. }
  62. c.Lang = lang
  63. }
  64. authorization := c.Ctx.Input.Header("authorization")
  65. if authorization == "" {
  66. authorization = c.Ctx.Input.Header("Authorization")
  67. }
  68. if authorization == "" {
  69. newAuthorization := c.GetString("authorization")
  70. if newAuthorization != `` {
  71. authorization = "authorization=" + newAuthorization
  72. } else {
  73. newAuthorization = c.GetString("Authorization")
  74. authorization = "authorization=" + newAuthorization
  75. }
  76. } else {
  77. if strings.Contains(authorization, ";") {
  78. authorization = strings.Replace(authorization, ";", "$", 1)
  79. }
  80. }
  81. if authorization == "" {
  82. strArr := strings.Split(uri, "?")
  83. for k, v := range strArr {
  84. fmt.Println(k, v)
  85. }
  86. if len(strArr) > 1 {
  87. authorization := strArr[1]
  88. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  89. fmt.Println(authorization)
  90. }
  91. }
  92. if authorization == "" {
  93. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  94. c.StopRun()
  95. return
  96. }
  97. //authorizationArr := strings.Split(authorization, "$")
  98. //if len(authorizationArr) <= 1 {
  99. // c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  100. // c.StopRun()
  101. // return
  102. //}
  103. tokenStr := authorization
  104. tokenArr := strings.Split(tokenStr, "=")
  105. token := tokenArr[1]
  106. //accountStr := authorizationArr[1]
  107. //accountArr := strings.Split(accountStr, "=")
  108. //account := accountArr[1]
  109. session, err := system.GetSysSessionByToken(token)
  110. if err != nil {
  111. if utils.IsErrNoRow(err) {
  112. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  113. c.StopRun()
  114. return
  115. }
  116. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  117. c.StopRun()
  118. return
  119. }
  120. if session == nil {
  121. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  122. c.StopRun()
  123. return
  124. }
  125. //校验token是否合法
  126. // JWT校验Token和Account
  127. account := utils.MD5(session.UserName)
  128. if !utils.CheckToken(account, token) {
  129. c.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false)
  130. c.StopRun()
  131. return
  132. }
  133. if time.Now().After(session.ExpiredTime) {
  134. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  135. c.StopRun()
  136. return
  137. }
  138. admin, err := system.GetSysUserById(session.SysUserId)
  139. if err != nil {
  140. if utils.IsErrNoRow(err) {
  141. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false)
  142. c.StopRun()
  143. return
  144. }
  145. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false)
  146. c.StopRun()
  147. return
  148. }
  149. if admin == nil {
  150. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
  151. c.StopRun()
  152. return
  153. }
  154. //如果不是启用状态
  155. if admin.Enabled != 1 {
  156. c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false)
  157. c.StopRun()
  158. return
  159. }
  160. // 如果当前登录态是不可信设备的,那么需要做过期校验
  161. if session.IsRemember != 1 {
  162. loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id)
  163. loginInfo, _ := utils.Rc.RedisString(loginKey)
  164. if loginInfo == `` {
  165. // 超时退出的时候,也记录下当前请求日志,避免数据丢失
  166. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  167. if err != nil {
  168. requestBody = string(c.Ctx.Input.RequestBody)
  169. }
  170. if requestBody == "" {
  171. requestBody = c.Ctx.Input.URI()
  172. }
  173. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s", c.Ctx.Input.URI(), authorization, requestBody)
  174. c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  175. c.StopRun()
  176. return
  177. }
  178. if loginInfo != "1" {
  179. // 超时退出的时候,也记录下当前请求日志,避免数据丢失
  180. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  181. if err != nil {
  182. requestBody = string(c.Ctx.Input.RequestBody)
  183. }
  184. if requestBody == "" {
  185. requestBody = c.Ctx.Input.URI()
  186. }
  187. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s", c.Ctx.Input.URI(), authorization, requestBody)
  188. msg := `该账号于` + admin.LastLoginTime + "在其他网络登录。此客户端已退出登录。"
  189. c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  190. c.StopRun()
  191. return
  192. }
  193. // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
  194. if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` {
  195. utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  196. // 不信任名单也同步更新
  197. noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
  198. utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
  199. }
  200. }
  201. admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
  202. c.SysUser = admin
  203. c.Session = session
  204. //接口权限校验
  205. roleId := admin.RoleId
  206. list, e := system.GetMenuButtonApisByRoleId(roleId)
  207. if e != nil {
  208. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  209. c.StopRun()
  210. return
  211. }
  212. var api string
  213. for _, v := range list {
  214. if v.Api != "" {
  215. api += v.Api + "&"
  216. }
  217. }
  218. api += "&" + models.BusinessConfMap["PublicApi"]
  219. //处理uri请求,去除前缀和参数
  220. api = strings.TrimRight(api, "&")
  221. uri = strings.Replace(uri, "/adminapi", "", 1)
  222. uris := strings.Split(uri, "?")
  223. uri = uris[0]
  224. //fmt.Println("uri:", uri)
  225. apis := strings.Split(api, "&")
  226. apiMap := make(map[string]bool, 0)
  227. for _, s := range apis {
  228. apiMap[s] = true
  229. }
  230. if !apiMap[uri] {
  231. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  232. c.StopRun()
  233. return
  234. }
  235. } else {
  236. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  237. c.StopRun()
  238. return
  239. }
  240. }
  241. }
  242. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  243. urlPath := c.Ctx.Request.URL.Path
  244. // 方法处理完后,需要后置处理的业务逻辑
  245. if handlerList, ok := AfterHandlerUrlMap[urlPath]; ok {
  246. for _, handler := range handlerList {
  247. handler(c.Ctx.Input.RequestBody)
  248. }
  249. }
  250. var (
  251. hasIndent = false
  252. hasEncoding = false
  253. )
  254. if web.BConfig.RunMode == web.PROD {
  255. hasIndent = false
  256. }
  257. if len(encoding) > 0 && encoding[0] == true {
  258. hasEncoding = true
  259. }
  260. if c.Data["json"] == nil {
  261. //go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  262. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  263. go alarm_msg.SendAlarmMsg(body, 1)
  264. return
  265. }
  266. baseRes := c.Data["json"].(*models.BaseResponse)
  267. if baseRes != nil && baseRes.Ret != 408 {
  268. body, _ := json.Marshal(baseRes)
  269. var requestBody string
  270. method := c.Ctx.Input.Method()
  271. if method == "GET" {
  272. requestBody = c.Ctx.Request.RequestURI
  273. } else {
  274. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  275. requestBody = string(c.Ctx.Input.RequestBody)
  276. }
  277. if baseRes.Ret != 200 && baseRes.IsSendEmail {
  278. //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)
  279. 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
  280. go alarm_msg.SendAlarmMsg(body, 1)
  281. }
  282. if baseRes.IsAddLog && c.SysUser != nil {
  283. go cache.RecordNewLogs(c.SysUser.AdminId, requestBody, string(body), c.SysUser.RealName, c.Ctx.Input.IP(), c.Ctx.Input.URI())
  284. }
  285. }
  286. if utils.ViperConfig != nil {
  287. if c.Lang == utils.EnLangVersion {
  288. msg := c.Data["json"].(*models.BaseResponse).Msg
  289. if utils.ViperConfig.InConfig(msg) {
  290. c.Data["json"].(*models.BaseResponse).Msg = utils.ViperConfig.GetString(msg)
  291. }
  292. }
  293. }
  294. //新增uuid记录
  295. {
  296. if _, ok := AdminOperateRecordMap[urlPath]; !ok && !strings.Contains(urlPath, "cygx") {
  297. var adminId int
  298. var realName, params, ip, uriStr string
  299. ip = c.Ctx.Input.IP()
  300. if c.SysUser != nil {
  301. adminId = c.SysUser.AdminId
  302. realName = c.SysUser.RealName
  303. }
  304. uuid := c.Ctx.Input.Header("Uuid")
  305. userAgent := c.Ctx.Input.Header("User-Agent")
  306. uri := c.Ctx.Input.URI()
  307. uriStr, _ = url.PathUnescape(uri)
  308. if uriStr != "" {
  309. uri = uriStr
  310. }
  311. if c.Ctx.Input.Method() == "GET" {
  312. paramsJson, _ := json.Marshal(c.Ctx.Input.Params())
  313. params = string(paramsJson)
  314. } else {
  315. params = string(c.Ctx.Input.RequestBody)
  316. }
  317. header := c.Ctx.Request.Header
  318. headerJson, _ := json.Marshal(header)
  319. headerStr := string(headerJson)
  320. go cache.AdminOperateRecord(adminId, realName, uuid, uri, params, ip, userAgent, headerStr)
  321. }
  322. }
  323. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  324. }
  325. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  326. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  327. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  328. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  329. // 设置Cookie为HTTPOnly
  330. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  331. //fmt.Println(c.Ctx.ResponseWriter.Header().Get("Set-Cookie"))
  332. var content []byte
  333. var err error
  334. if hasIndent {
  335. content, err = json.MarshalIndent(data, "", " ")
  336. } else {
  337. content, err = json.Marshal(data)
  338. }
  339. if err != nil {
  340. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  341. return err
  342. }
  343. ip := c.Ctx.Input.IP()
  344. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  345. if err != nil {
  346. requestBody = string(c.Ctx.Input.RequestBody)
  347. }
  348. if requestBody == "" {
  349. requestBody = c.Ctx.Input.URI()
  350. }
  351. c.logUri(content, requestBody, ip)
  352. // 如果不是debug分支的话,那么需要加密返回
  353. if utils.RunMode != "debug" {
  354. content = utils.DesBase64Encrypt(content, utils.DesKey)
  355. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  356. content = []byte(`"` + string(content) + `"`)
  357. }
  358. if coding {
  359. content = []byte(utils.StringsToJSON(string(content)))
  360. }
  361. return c.Ctx.Output.Body(content)
  362. }
  363. func GetSysUserRoleTypeCode(roleTypeCode string) string {
  364. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
  365. roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
  366. return utils.ROLE_TYPE_CODE_FICC_SELLER
  367. }
  368. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
  369. roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
  370. return utils.ROLE_TYPE_CODE_RAI_SELLER
  371. }
  372. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
  373. return utils.ROLE_TYPE_CODE_RAI_GROUP
  374. }
  375. if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
  376. return utils.ROLE_TYPE_CODE_ADMIN
  377. }
  378. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  379. return utils.ROLE_TYPE_CODE_FICC_ADMIN
  380. }
  381. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
  382. return utils.ROLE_TYPE_CODE_FICC_TEAM
  383. }
  384. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
  385. return utils.ROLE_TYPE_CODE_FICC_GROUP
  386. }
  387. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  388. return utils.ROLE_TYPE_CODE_RAI_ADMIN
  389. }
  390. if roleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
  391. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  392. }
  393. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR {
  394. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  395. }
  396. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR {
  397. return utils.ROLE_TYPE_CODE_RAI_RESEARCHR
  398. }
  399. //合规
  400. if roleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE {
  401. return utils.ROLE_TYPE_CODE_COMPLIANCE
  402. }
  403. //财务
  404. if roleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
  405. return utils.ROLE_TYPE_CODE_FINANCE
  406. }
  407. return ""
  408. }
  409. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  410. authorization := ""
  411. method := c.Ctx.Input.Method()
  412. uri := c.Ctx.Input.URI()
  413. //fmt.Println("Url:", uri)
  414. if method != "HEAD" {
  415. if method == "POST" || method == "GET" {
  416. authorization = c.Ctx.Input.Header("authorization")
  417. if authorization == "" {
  418. authorization = c.Ctx.Input.Header("Authorization")
  419. }
  420. if authorization == "" {
  421. newAuthorization := c.GetString("authorization")
  422. if newAuthorization != `` {
  423. authorization = "authorization=" + newAuthorization
  424. } else {
  425. newAuthorization = c.GetString("Authorization")
  426. authorization = "authorization=" + newAuthorization
  427. }
  428. } else {
  429. if strings.Contains(authorization, ";") {
  430. authorization = strings.Replace(authorization, ";", "$", 1)
  431. }
  432. }
  433. if authorization == "" {
  434. strArr := strings.Split(uri, "?")
  435. for k, v := range strArr {
  436. fmt.Println(k, v)
  437. }
  438. if len(strArr) > 1 {
  439. authorization = strArr[1]
  440. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  441. fmt.Println(authorization)
  442. }
  443. }
  444. }
  445. }
  446. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  447. return
  448. }