base_auth.go 15 KB

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