base_auth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. }
  47. func (c *BaseAuthController) Prepare() {
  48. fmt.Println("enter prepare")
  49. method := c.Ctx.Input.Method()
  50. uri := c.Ctx.Input.URI()
  51. fmt.Println("Url:", uri)
  52. if method != "HEAD" {
  53. if method == "POST" || method == "GET" {
  54. authorization := c.Ctx.Input.Header("authorization")
  55. if authorization == "" {
  56. authorization = c.Ctx.Input.Header("Authorization")
  57. }
  58. if authorization == "" {
  59. newAuthorization := c.GetString("authorization")
  60. if newAuthorization != `` {
  61. authorization = "authorization=" + newAuthorization
  62. } else {
  63. newAuthorization = c.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. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  84. c.StopRun()
  85. return
  86. }
  87. authorizationArr := strings.Split(authorization, "$")
  88. if len(authorizationArr) <= 1 {
  89. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  90. c.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. c.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false)
  103. c.StopRun()
  104. return
  105. }
  106. session, err := system.GetSysSessionByToken(token)
  107. if err != nil {
  108. if err.Error() == utils.ErrNoRow() {
  109. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  110. c.StopRun()
  111. return
  112. }
  113. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  114. c.StopRun()
  115. return
  116. }
  117. if session == nil {
  118. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  119. c.StopRun()
  120. return
  121. }
  122. if time.Now().After(session.ExpiredTime) {
  123. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  124. c.StopRun()
  125. return
  126. }
  127. admin, err := system.GetSysUserById(session.SysUserId)
  128. if err != nil {
  129. if err.Error() == utils.ErrNoRow() {
  130. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false)
  131. c.StopRun()
  132. return
  133. }
  134. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false)
  135. c.StopRun()
  136. return
  137. }
  138. if admin == nil {
  139. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
  140. c.StopRun()
  141. return
  142. }
  143. //如果不是启用状态
  144. if admin.Enabled != 1 {
  145. c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false)
  146. c.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. c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  155. c.StopRun()
  156. return
  157. }
  158. if loginInfo != "1" {
  159. msg := `该账号于` + admin.LastLoginTime + "在其他网络登录。此客户端已退出登录。"
  160. c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  161. c.StopRun()
  162. return
  163. }
  164. // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
  165. if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` {
  166. utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  167. // 不信任名单也同步更新
  168. noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
  169. utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
  170. }
  171. }
  172. admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
  173. c.SysUser = admin
  174. //接口权限校验
  175. roleId := admin.RoleId
  176. list, e := system.GetMenuButtonApisByRoleId(roleId)
  177. if e != nil {
  178. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  179. c.StopRun()
  180. return
  181. }
  182. var api string
  183. for _, v := range list {
  184. api += v.Api + "&"
  185. }
  186. //处理uri请求,去除前缀和参数
  187. api = strings.TrimRight(api, "&")
  188. uri = strings.Replace(uri, "/adminapi", "", 1)
  189. uris := strings.Split(uri, "?")
  190. uri = uris[0]
  191. fmt.Println("uri:", uri)
  192. apis := strings.Split(api, "&")
  193. apiMap := make(map[string]bool, 0)
  194. for _, s := range apis {
  195. apiMap[s] = true
  196. }
  197. if !apiMap[uri] {
  198. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  199. c.StopRun()
  200. return
  201. }
  202. } else {
  203. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  204. c.StopRun()
  205. return
  206. }
  207. }
  208. }
  209. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  210. urlPath := c.Ctx.Request.URL.Path
  211. // 方法处理完后,需要后置处理的业务逻辑
  212. if handlerList, ok := AfterHandlerUrlMap[urlPath]; ok {
  213. for _, handler := range handlerList {
  214. handler(c.Ctx.Input.RequestBody)
  215. }
  216. }
  217. var (
  218. hasIndent = false
  219. hasEncoding = false
  220. )
  221. if web.BConfig.RunMode == web.PROD {
  222. hasIndent = false
  223. }
  224. if len(encoding) > 0 && encoding[0] == true {
  225. hasEncoding = true
  226. }
  227. if c.Data["json"] == nil {
  228. //go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  229. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  230. go alarm_msg.SendAlarmMsg(body, 1)
  231. return
  232. }
  233. baseRes := c.Data["json"].(*models.BaseResponse)
  234. if baseRes != nil && baseRes.Ret != 408 {
  235. body, _ := json.Marshal(baseRes)
  236. var requestBody string
  237. method := c.Ctx.Input.Method()
  238. if method == "GET" {
  239. requestBody = c.Ctx.Request.RequestURI
  240. } else {
  241. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  242. requestBody = string(c.Ctx.Input.RequestBody)
  243. }
  244. if baseRes.Ret != 200 && baseRes.IsSendEmail {
  245. //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)
  246. 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
  247. go alarm_msg.SendAlarmMsg(body, 1)
  248. }
  249. if baseRes.IsAddLog && c.SysUser != nil {
  250. go cache.RecordNewLogs(c.SysUser.AdminId, requestBody, string(body), c.SysUser.RealName, c.Ctx.Input.IP(), c.Ctx.Input.URI())
  251. }
  252. }
  253. //新增uuid记录
  254. {
  255. if _, ok := AdminOperateRecordMap[urlPath]; !ok && !strings.Contains(urlPath, "cygx") {
  256. var adminId int
  257. var realName, params, ip, uriStr string
  258. ip = c.Ctx.Input.IP()
  259. if c.SysUser != nil {
  260. adminId = c.SysUser.AdminId
  261. realName = c.SysUser.RealName
  262. }
  263. uuid := c.Ctx.Input.Header("Uuid")
  264. userAgent := c.Ctx.Input.Header("User-Agent")
  265. uri := c.Ctx.Input.URI()
  266. uriStr, _ = url.PathUnescape(uri)
  267. if uriStr != "" {
  268. uri = uriStr
  269. }
  270. if c.Ctx.Input.Method() == "GET" {
  271. paramsJson, _ := json.Marshal(c.Ctx.Input.Params())
  272. params = string(paramsJson)
  273. } else {
  274. params = string(c.Ctx.Input.RequestBody)
  275. }
  276. header := c.Ctx.Request.Header
  277. headerJson, _ := json.Marshal(header)
  278. headerStr := string(headerJson)
  279. go cache.AdminOperateRecord(adminId, realName, uuid, uri, params, ip, userAgent, headerStr)
  280. }
  281. }
  282. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  283. }
  284. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  285. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  286. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  287. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  288. var content []byte
  289. var err error
  290. if hasIndent {
  291. content, err = json.MarshalIndent(data, "", " ")
  292. } else {
  293. content, err = json.Marshal(data)
  294. }
  295. if err != nil {
  296. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  297. return err
  298. }
  299. ip := c.Ctx.Input.IP()
  300. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  301. if err != nil {
  302. requestBody = string(c.Ctx.Input.RequestBody)
  303. }
  304. if requestBody == "" {
  305. requestBody = c.Ctx.Input.URI()
  306. }
  307. c.logUri(content, requestBody, ip)
  308. // 如果不是debug分支的话,那么需要加密返回
  309. if utils.RunMode != "debug" {
  310. content = utils.DesBase64Encrypt(content, utils.DesKey)
  311. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  312. content = []byte(`"` + string(content) + `"`)
  313. }
  314. if coding {
  315. content = []byte(utils.StringsToJSON(string(content)))
  316. }
  317. return c.Ctx.Output.Body(content)
  318. }
  319. func GetSysUserRoleTypeCode(roleTypeCode string) string {
  320. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
  321. roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
  322. return utils.ROLE_TYPE_CODE_FICC_SELLER
  323. }
  324. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
  325. roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
  326. return utils.ROLE_TYPE_CODE_RAI_SELLER
  327. }
  328. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
  329. return utils.ROLE_TYPE_CODE_RAI_GROUP
  330. }
  331. if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
  332. return utils.ROLE_TYPE_CODE_ADMIN
  333. }
  334. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  335. return utils.ROLE_TYPE_CODE_FICC_ADMIN
  336. }
  337. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
  338. return utils.ROLE_TYPE_CODE_FICC_TEAM
  339. }
  340. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
  341. return utils.ROLE_TYPE_CODE_FICC_GROUP
  342. }
  343. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  344. return utils.ROLE_TYPE_CODE_RAI_ADMIN
  345. }
  346. if roleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
  347. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  348. }
  349. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR {
  350. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  351. }
  352. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR {
  353. return utils.ROLE_TYPE_CODE_RAI_RESEARCHR
  354. }
  355. //合规
  356. if roleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE {
  357. return utils.ROLE_TYPE_CODE_COMPLIANCE
  358. }
  359. //财务
  360. if roleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
  361. return utils.ROLE_TYPE_CODE_FINANCE
  362. }
  363. return ""
  364. }
  365. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  366. authorization := ""
  367. method := c.Ctx.Input.Method()
  368. uri := c.Ctx.Input.URI()
  369. fmt.Println("Url:", uri)
  370. if method != "HEAD" {
  371. if method == "POST" || method == "GET" {
  372. authorization = c.Ctx.Input.Header("authorization")
  373. if authorization == "" {
  374. authorization = c.Ctx.Input.Header("Authorization")
  375. }
  376. if authorization == "" {
  377. newAuthorization := c.GetString("authorization")
  378. if newAuthorization != `` {
  379. authorization = "authorization=" + newAuthorization
  380. } else {
  381. newAuthorization = c.GetString("Authorization")
  382. authorization = "authorization=" + newAuthorization
  383. }
  384. } else {
  385. if strings.Contains(authorization, ";") {
  386. authorization = strings.Replace(authorization, ";", "$", 1)
  387. }
  388. }
  389. if authorization == "" {
  390. strArr := strings.Split(uri, "?")
  391. for k, v := range strArr {
  392. fmt.Println(k, v)
  393. }
  394. if len(strArr) > 1 {
  395. authorization = strArr[1]
  396. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  397. fmt.Println(authorization)
  398. }
  399. }
  400. }
  401. }
  402. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  403. return
  404. }