base_auth.go 16 KB

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