base_auth.go 16 KB

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