base_auth.go 16 KB

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