base_auth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 err.Error() == utils.ErrNoRow() {
  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 err.Error() == utils.ErrNoRow() {
  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. c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  166. c.StopRun()
  167. return
  168. }
  169. if loginInfo != "1" {
  170. msg := `该账号于` + admin.LastLoginTime + "在其他网络登录。此客户端已退出登录。"
  171. c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  172. c.StopRun()
  173. return
  174. }
  175. // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
  176. if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` {
  177. utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  178. // 不信任名单也同步更新
  179. noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
  180. utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
  181. }
  182. }
  183. admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
  184. c.SysUser = admin
  185. c.Session = session
  186. //接口权限校验
  187. roleId := admin.RoleId
  188. list, e := system.GetMenuButtonApisByRoleId(roleId)
  189. if e != nil {
  190. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  191. c.StopRun()
  192. return
  193. }
  194. var api string
  195. for _, v := range list {
  196. if v.Api != "" {
  197. api += v.Api + "&"
  198. }
  199. }
  200. api += "&" + models.BusinessConfMap["PublicApi"]
  201. //处理uri请求,去除前缀和参数
  202. api = strings.TrimRight(api, "&")
  203. uri = strings.Replace(uri, "/adminapi", "", 1)
  204. uris := strings.Split(uri, "?")
  205. uri = uris[0]
  206. //fmt.Println("uri:", uri)
  207. apis := strings.Split(api, "&")
  208. apiMap := make(map[string]bool, 0)
  209. for _, s := range apis {
  210. apiMap[s] = true
  211. }
  212. if !apiMap[uri] {
  213. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  214. c.StopRun()
  215. return
  216. }
  217. } else {
  218. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  219. c.StopRun()
  220. return
  221. }
  222. }
  223. }
  224. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  225. urlPath := c.Ctx.Request.URL.Path
  226. // 方法处理完后,需要后置处理的业务逻辑
  227. if handlerList, ok := AfterHandlerUrlMap[urlPath]; ok {
  228. for _, handler := range handlerList {
  229. handler(c.Ctx.Input.RequestBody)
  230. }
  231. }
  232. var (
  233. hasIndent = false
  234. hasEncoding = false
  235. )
  236. if web.BConfig.RunMode == web.PROD {
  237. hasIndent = false
  238. }
  239. if len(encoding) > 0 && encoding[0] == true {
  240. hasEncoding = true
  241. }
  242. if c.Data["json"] == nil {
  243. //go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  244. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  245. go alarm_msg.SendAlarmMsg(body, 1)
  246. return
  247. }
  248. baseRes := c.Data["json"].(*models.BaseResponse)
  249. if baseRes != nil && baseRes.Ret != 408 {
  250. body, _ := json.Marshal(baseRes)
  251. var requestBody string
  252. method := c.Ctx.Input.Method()
  253. if method == "GET" {
  254. requestBody = c.Ctx.Request.RequestURI
  255. } else {
  256. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  257. requestBody = string(c.Ctx.Input.RequestBody)
  258. }
  259. if baseRes.Ret != 200 && baseRes.IsSendEmail {
  260. //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)
  261. 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
  262. go alarm_msg.SendAlarmMsg(body, 1)
  263. }
  264. if baseRes.IsAddLog && c.SysUser != nil {
  265. go cache.RecordNewLogs(c.SysUser.AdminId, requestBody, string(body), c.SysUser.RealName, c.Ctx.Input.IP(), c.Ctx.Input.URI())
  266. }
  267. }
  268. if utils.ViperConfig != nil {
  269. if c.Lang == utils.EnLangVersion {
  270. msg := c.Data["json"].(*models.BaseResponse).Msg
  271. if utils.ViperConfig.InConfig(msg) {
  272. c.Data["json"].(*models.BaseResponse).Msg = utils.ViperConfig.GetString(msg)
  273. }
  274. }
  275. }
  276. //新增uuid记录
  277. {
  278. if _, ok := AdminOperateRecordMap[urlPath]; !ok && !strings.Contains(urlPath, "cygx") {
  279. var adminId int
  280. var realName, params, ip, uriStr string
  281. ip = c.Ctx.Input.IP()
  282. if c.SysUser != nil {
  283. adminId = c.SysUser.AdminId
  284. realName = c.SysUser.RealName
  285. }
  286. uuid := c.Ctx.Input.Header("Uuid")
  287. userAgent := c.Ctx.Input.Header("User-Agent")
  288. uri := c.Ctx.Input.URI()
  289. uriStr, _ = url.PathUnescape(uri)
  290. if uriStr != "" {
  291. uri = uriStr
  292. }
  293. if c.Ctx.Input.Method() == "GET" {
  294. paramsJson, _ := json.Marshal(c.Ctx.Input.Params())
  295. params = string(paramsJson)
  296. } else {
  297. params = string(c.Ctx.Input.RequestBody)
  298. }
  299. header := c.Ctx.Request.Header
  300. headerJson, _ := json.Marshal(header)
  301. headerStr := string(headerJson)
  302. go cache.AdminOperateRecord(adminId, realName, uuid, uri, params, ip, userAgent, headerStr)
  303. }
  304. }
  305. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  306. }
  307. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  308. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  309. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  310. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  311. // 设置Cookie为HTTPOnly
  312. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  313. //fmt.Println(c.Ctx.ResponseWriter.Header().Get("Set-Cookie"))
  314. var content []byte
  315. var err error
  316. if hasIndent {
  317. content, err = json.MarshalIndent(data, "", " ")
  318. } else {
  319. content, err = json.Marshal(data)
  320. }
  321. if err != nil {
  322. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  323. return err
  324. }
  325. ip := c.Ctx.Input.IP()
  326. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  327. if err != nil {
  328. requestBody = string(c.Ctx.Input.RequestBody)
  329. }
  330. if requestBody == "" {
  331. requestBody = c.Ctx.Input.URI()
  332. }
  333. c.logUri(content, requestBody, ip)
  334. // 如果不是debug分支的话,那么需要加密返回
  335. if utils.RunMode != "debug" {
  336. content = utils.DesBase64Encrypt(content, utils.DesKey)
  337. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  338. content = []byte(`"` + string(content) + `"`)
  339. }
  340. if coding {
  341. content = []byte(utils.StringsToJSON(string(content)))
  342. }
  343. return c.Ctx.Output.Body(content)
  344. }
  345. func GetSysUserRoleTypeCode(roleTypeCode string) string {
  346. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
  347. roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
  348. return utils.ROLE_TYPE_CODE_FICC_SELLER
  349. }
  350. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
  351. roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
  352. return utils.ROLE_TYPE_CODE_RAI_SELLER
  353. }
  354. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
  355. return utils.ROLE_TYPE_CODE_RAI_GROUP
  356. }
  357. if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
  358. return utils.ROLE_TYPE_CODE_ADMIN
  359. }
  360. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  361. return utils.ROLE_TYPE_CODE_FICC_ADMIN
  362. }
  363. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
  364. return utils.ROLE_TYPE_CODE_FICC_TEAM
  365. }
  366. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
  367. return utils.ROLE_TYPE_CODE_FICC_GROUP
  368. }
  369. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  370. return utils.ROLE_TYPE_CODE_RAI_ADMIN
  371. }
  372. if roleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
  373. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  374. }
  375. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR {
  376. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  377. }
  378. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR {
  379. return utils.ROLE_TYPE_CODE_RAI_RESEARCHR
  380. }
  381. //合规
  382. if roleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE {
  383. return utils.ROLE_TYPE_CODE_COMPLIANCE
  384. }
  385. //财务
  386. if roleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
  387. return utils.ROLE_TYPE_CODE_FINANCE
  388. }
  389. return ""
  390. }
  391. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  392. authorization := ""
  393. method := c.Ctx.Input.Method()
  394. uri := c.Ctx.Input.URI()
  395. //fmt.Println("Url:", uri)
  396. if method != "HEAD" {
  397. if method == "POST" || method == "GET" {
  398. authorization = c.Ctx.Input.Header("authorization")
  399. if authorization == "" {
  400. authorization = c.Ctx.Input.Header("Authorization")
  401. }
  402. if authorization == "" {
  403. newAuthorization := c.GetString("authorization")
  404. if newAuthorization != `` {
  405. authorization = "authorization=" + newAuthorization
  406. } else {
  407. newAuthorization = c.GetString("Authorization")
  408. authorization = "authorization=" + newAuthorization
  409. }
  410. } else {
  411. if strings.Contains(authorization, ";") {
  412. authorization = strings.Replace(authorization, ";", "$", 1)
  413. }
  414. }
  415. if authorization == "" {
  416. strArr := strings.Split(uri, "?")
  417. for k, v := range strArr {
  418. fmt.Println(k, v)
  419. }
  420. if len(strArr) > 1 {
  421. authorization = strArr[1]
  422. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  423. fmt.Println(authorization)
  424. }
  425. }
  426. }
  427. }
  428. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  429. return
  430. }