base_auth.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta_gn/eta_api/cache"
  5. "eta_gn/eta_api/models/system"
  6. "eta_gn/eta_api/services"
  7. "eta_gn/eta_api/services/alarm_msg"
  8. "eta_gn/eta_api/services/data"
  9. "fmt"
  10. "net/http"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/beego/beego/v2/server/web"
  16. "eta_gn/eta_api/models"
  17. "eta_gn/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. Session *system.SysSession
  48. Lang string `description:"当前语言类型,中文:zh;英文:en;默认:zh"`
  49. }
  50. //func (c *BaseAuthController) Prepare() {
  51. // //fmt.Println("enter prepare")
  52. // method := c.Ctx.Input.Method()
  53. // uri := c.Ctx.Input.URI()
  54. // //fmt.Println("Url:", uri)
  55. // if method != "HEAD" {
  56. // if method == "POST" || method == "GET" {
  57. // // 当前语言
  58. // {
  59. // lang := c.Ctx.Input.Header("Lang")
  60. // if lang == "" {
  61. // lang = utils.ZhLangVersion
  62. // }
  63. // c.Lang = lang
  64. // }
  65. //
  66. // authorization := c.Ctx.Input.Header("authorization")
  67. // if authorization == "" {
  68. // authorization = c.Ctx.Input.Header("Authorization")
  69. // }
  70. // if authorization == "" {
  71. // newAuthorization := c.GetString("authorization")
  72. // if newAuthorization != `` {
  73. // authorization = "authorization=" + newAuthorization
  74. // } else {
  75. // newAuthorization = c.GetString("Authorization")
  76. // authorization = "authorization=" + newAuthorization
  77. // }
  78. // } else {
  79. // if strings.Contains(authorization, ";") {
  80. // authorization = strings.Replace(authorization, ";", "$", 1)
  81. // }
  82. // }
  83. // if authorization == "" {
  84. // strArr := strings.Split(uri, "?")
  85. // for k, v := range strArr {
  86. // fmt.Println(k, v)
  87. // }
  88. // if len(strArr) > 1 {
  89. // authorization := strArr[1]
  90. // authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  91. // fmt.Println(authorization)
  92. // }
  93. // }
  94. // if authorization == "" {
  95. // c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  96. // c.StopRun()
  97. // return
  98. // }
  99. // //authorizationArr := strings.Split(authorization, "$")
  100. // //if len(authorizationArr) <= 1 {
  101. // // c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  102. // // c.StopRun()
  103. // // return
  104. // //}
  105. // tokenStr := authorization
  106. // tokenArr := strings.Split(tokenStr, "=")
  107. // token := tokenArr[1]
  108. //
  109. // //accountStr := authorizationArr[1]
  110. // //accountArr := strings.Split(accountStr, "=")
  111. // //account := accountArr[1]
  112. //
  113. // session, err := system.GetSysSessionByToken(token)
  114. // if err != nil {
  115. // if utils.IsErrNoRow(err) {
  116. // c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  117. // c.StopRun()
  118. // return
  119. // }
  120. // c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  121. // c.StopRun()
  122. // return
  123. // }
  124. // if session == nil {
  125. // c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  126. // c.StopRun()
  127. // return
  128. // }
  129. // //校验token是否合法
  130. // // JWT校验Token和Account
  131. // account := utils.MD5(session.UserName)
  132. // if !utils.CheckToken(account, token) {
  133. // c.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false)
  134. // c.StopRun()
  135. // return
  136. // }
  137. // if time.Now().After(session.ExpiredTime) {
  138. // c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  139. // c.StopRun()
  140. // return
  141. // }
  142. // admin, err := system.GetSysUserById(session.SysUserId)
  143. // if err != nil {
  144. // if utils.IsErrNoRow(err) {
  145. // c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false)
  146. // c.StopRun()
  147. // return
  148. // }
  149. // c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false)
  150. // c.StopRun()
  151. // return
  152. // }
  153. // if admin == nil {
  154. // c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
  155. // c.StopRun()
  156. // return
  157. // }
  158. // //如果不是启用状态
  159. // if admin.Enabled != 1 {
  160. // c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false)
  161. // c.StopRun()
  162. // return
  163. // }
  164. //
  165. // // 如果当前登录态是不可信设备的,那么需要做过期校验
  166. // if session.IsRemember != 1 {
  167. // loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id)
  168. // loginInfo, _ := utils.Rc.RedisString(loginKey)
  169. // if loginInfo == `` {
  170. // c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  171. // c.StopRun()
  172. // return
  173. // }
  174. //
  175. // if loginInfo != "1" {
  176. // lastLoginTime := admin.LastLoginTime
  177. //
  178. // lastLoginTimeObj, err := time.Parse(utils.FormatDateWallWithLoc, lastLoginTime)
  179. // fmt.Println(lastLoginTimeObj, err)
  180. //
  181. // msg := `该账号于` + lastLoginTimeObj.Format(utils.FormatDateTime) + "在其他网络登录。此客户端已退出登录。"
  182. // c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  183. // c.StopRun()
  184. // return
  185. // }
  186. //
  187. // // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
  188. // if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` {
  189. // utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  190. // // 不信任名单也同步更新
  191. // noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
  192. // utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
  193. // }
  194. // }
  195. //
  196. // admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
  197. // c.SysUser = admin
  198. // c.Session = session
  199. //
  200. // //接口权限校验
  201. // roleId := admin.RoleId
  202. // list, e := system.GetMenuButtonApisByRoleId(roleId)
  203. // if e != nil {
  204. // c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  205. // c.StopRun()
  206. // return
  207. // }
  208. // var api string
  209. // for _, v := range list {
  210. // if v.Api != "" {
  211. // api += v.Api + "&"
  212. // }
  213. // }
  214. //
  215. // //fmt.Println(api)
  216. // //处理uri请求,去除前缀和参数
  217. // api = strings.TrimRight(api, "&")
  218. // uri = strings.Replace(uri, "/adminapi", "", 1)
  219. // uris := strings.Split(uri, "?")
  220. // uri = uris[0]
  221. // //fmt.Println("uri:", uri)
  222. // apis := strings.Split(api, "&")
  223. // apiMap := make(map[string]bool, 0)
  224. // for _, s := range apis {
  225. // apiMap[s] = true
  226. // }
  227. //
  228. // fmt.Println("uri:", uri)
  229. //
  230. // //fmt.Println(apiMap)
  231. // if !apiMap[uri] {
  232. // c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  233. // c.StopRun()
  234. // return
  235. // }
  236. // } else {
  237. // c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  238. // c.StopRun()
  239. // return
  240. // }
  241. // }
  242. //}
  243. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  244. urlPath := c.Ctx.Request.URL.Path
  245. // 方法处理完后,需要后置处理的业务逻辑
  246. if handlerList, ok := AfterHandlerUrlMap[urlPath]; ok {
  247. for _, handler := range handlerList {
  248. handler(c.Ctx.Input.RequestBody)
  249. }
  250. }
  251. var (
  252. hasIndent = false
  253. hasEncoding = false
  254. )
  255. if web.BConfig.RunMode == web.PROD {
  256. hasIndent = false
  257. }
  258. if len(encoding) > 0 && encoding[0] == true {
  259. hasEncoding = true
  260. }
  261. if c.Data["json"] == nil {
  262. //go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  263. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  264. go alarm_msg.SendAlarmMsg(body, 1)
  265. return
  266. }
  267. baseRes := c.Data["json"].(*models.BaseResponse)
  268. if baseRes != nil && baseRes.Ret != 408 {
  269. body, _ := json.Marshal(baseRes)
  270. var requestBody string
  271. method := c.Ctx.Input.Method()
  272. if method == "GET" {
  273. requestBody = c.Ctx.Request.RequestURI
  274. } else {
  275. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  276. requestBody = string(c.Ctx.Input.RequestBody)
  277. }
  278. if baseRes.Ret != 200 && baseRes.IsSendEmail {
  279. //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)
  280. 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
  281. go alarm_msg.SendAlarmMsg(body, 1)
  282. }
  283. if baseRes.IsAddLog && c.SysUser != nil {
  284. go cache.RecordNewLogs(c.SysUser.AdminId, requestBody, string(body), c.SysUser.RealName, c.Ctx.Input.IP(), c.Ctx.Input.URI())
  285. }
  286. }
  287. if utils.ViperConfig != nil {
  288. if c.Lang == utils.EnLangVersion {
  289. msg := c.Data["json"].(*models.BaseResponse).Msg
  290. if utils.ViperConfig.InConfig(msg) {
  291. c.Data["json"].(*models.BaseResponse).Msg = utils.ViperConfig.GetString(msg)
  292. }
  293. }
  294. }
  295. //新增uuid记录
  296. {
  297. if _, ok := AdminOperateRecordMap[urlPath]; !ok && !strings.Contains(urlPath, "cygx") {
  298. var adminId int
  299. var realName, params, ip, uriStr string
  300. ip = c.Ctx.Input.IP()
  301. if c.SysUser != nil {
  302. adminId = c.SysUser.AdminId
  303. realName = c.SysUser.RealName
  304. }
  305. uuid := c.Ctx.Input.Header("Uuid")
  306. userAgent := c.Ctx.Input.Header("User-Agent")
  307. uri := c.Ctx.Input.URI()
  308. uriStr, _ = url.PathUnescape(uri)
  309. if uriStr != "" {
  310. uri = uriStr
  311. }
  312. if c.Ctx.Input.Method() == "GET" {
  313. paramsJson, _ := json.Marshal(c.Ctx.Input.Params())
  314. params = string(paramsJson)
  315. } else {
  316. params = string(c.Ctx.Input.RequestBody)
  317. }
  318. header := c.Ctx.Request.Header
  319. headerJson, _ := json.Marshal(header)
  320. headerStr := string(headerJson)
  321. go cache.AdminOperateRecord(adminId, realName, uuid, uri, params, ip, userAgent, headerStr)
  322. }
  323. }
  324. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  325. }
  326. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  327. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  328. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  329. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  330. // 设置Cookie为HTTPOnly
  331. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  332. //fmt.Println(c.Ctx.ResponseWriter.Header().Get("Set-Cookie"))
  333. var content []byte
  334. var err error
  335. if hasIndent {
  336. content, err = json.MarshalIndent(data, "", " ")
  337. } else {
  338. content, err = json.Marshal(data)
  339. }
  340. if err != nil {
  341. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  342. return err
  343. }
  344. ip := c.Ctx.Input.IP()
  345. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  346. if err != nil {
  347. requestBody = string(c.Ctx.Input.RequestBody)
  348. }
  349. if requestBody == "" {
  350. requestBody = c.Ctx.Input.URI()
  351. }
  352. c.logUri(content, requestBody, ip)
  353. // 如果不是debug分支的话,那么需要加密返回
  354. if utils.RunMode != "debug" {
  355. content = utils.DesBase64Encrypt(content, utils.DesKey)
  356. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  357. content = []byte(`"` + string(content) + `"`)
  358. }
  359. if coding {
  360. content = []byte(utils.StringsToJSON(string(content)))
  361. }
  362. return c.Ctx.Output.Body(content)
  363. }
  364. func GetSysUserRoleTypeCode(roleTypeCode string) string {
  365. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
  366. roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
  367. return utils.ROLE_TYPE_CODE_FICC_SELLER
  368. }
  369. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
  370. roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
  371. return utils.ROLE_TYPE_CODE_RAI_SELLER
  372. }
  373. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
  374. return utils.ROLE_TYPE_CODE_RAI_GROUP
  375. }
  376. if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
  377. return utils.ROLE_TYPE_CODE_ADMIN
  378. }
  379. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  380. return utils.ROLE_TYPE_CODE_FICC_ADMIN
  381. }
  382. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
  383. return utils.ROLE_TYPE_CODE_FICC_TEAM
  384. }
  385. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
  386. return utils.ROLE_TYPE_CODE_FICC_GROUP
  387. }
  388. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  389. return utils.ROLE_TYPE_CODE_RAI_ADMIN
  390. }
  391. if roleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
  392. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  393. }
  394. if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR {
  395. return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
  396. }
  397. if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR {
  398. return utils.ROLE_TYPE_CODE_RAI_RESEARCHR
  399. }
  400. //合规
  401. if roleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE {
  402. return utils.ROLE_TYPE_CODE_COMPLIANCE
  403. }
  404. //财务
  405. if roleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
  406. return utils.ROLE_TYPE_CODE_FINANCE
  407. }
  408. return ""
  409. }
  410. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  411. authorization := ""
  412. method := c.Ctx.Input.Method()
  413. uri := c.Ctx.Input.URI()
  414. //fmt.Println("Url:", uri)
  415. if method != "HEAD" {
  416. if method == "POST" || method == "GET" {
  417. authorization = c.Ctx.Input.Header("authorization")
  418. if authorization == "" {
  419. authorization = c.Ctx.Input.Header("Authorization")
  420. }
  421. if authorization == "" {
  422. newAuthorization := c.GetString("authorization")
  423. if newAuthorization != `` {
  424. authorization = "authorization=" + newAuthorization
  425. } else {
  426. newAuthorization = c.GetString("Authorization")
  427. authorization = "authorization=" + newAuthorization
  428. }
  429. } else {
  430. if strings.Contains(authorization, ";") {
  431. authorization = strings.Replace(authorization, ";", "$", 1)
  432. }
  433. }
  434. if authorization == "" {
  435. strArr := strings.Split(uri, "?")
  436. for k, v := range strArr {
  437. fmt.Println(k, v)
  438. }
  439. if len(strArr) > 1 {
  440. authorization = strArr[1]
  441. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  442. fmt.Println(authorization)
  443. }
  444. }
  445. }
  446. }
  447. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  448. return
  449. }
  450. func (c *BaseAuthController) Prepare() {
  451. //fmt.Println("enter prepare")
  452. method := c.Ctx.Input.Method()
  453. if method == `HEAD` {
  454. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  455. c.StopRun()
  456. return
  457. }
  458. if method != "POST" && method != "GET" {
  459. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  460. c.StopRun()
  461. return
  462. }
  463. uri := c.Ctx.Input.URI()
  464. //fmt.Println("Url:", uri)
  465. // 当前语言
  466. {
  467. lang := c.Ctx.Input.Header("Lang")
  468. if lang == "" {
  469. lang = utils.ZhLangVersion
  470. }
  471. c.Lang = lang
  472. }
  473. isOk, session, resp := checkToken(c)
  474. if !isOk {
  475. _ = c.JSON(resp, false, false)
  476. c.StopRun()
  477. return
  478. }
  479. if session == nil {
  480. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  481. c.StopRun()
  482. return
  483. }
  484. //校验token是否合法
  485. // JWT校验Token和Account
  486. admin, err := system.GetSysUserById(session.SysUserId)
  487. if err != nil {
  488. if utils.IsErrNoRow(err) {
  489. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false)
  490. c.StopRun()
  491. return
  492. }
  493. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false)
  494. c.StopRun()
  495. return
  496. }
  497. if admin == nil {
  498. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
  499. c.StopRun()
  500. return
  501. }
  502. //如果不是启用状态
  503. if admin.Enabled != 1 {
  504. c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false)
  505. c.StopRun()
  506. return
  507. }
  508. //// 如果当前登录态是不可信设备的,那么需要做过期校验
  509. //if session.IsRemember != 1 {
  510. // loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id)
  511. // loginInfo, _ := utils.Rc.RedisString(loginKey)
  512. // if loginInfo == `` {
  513. // c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  514. // c.StopRun()
  515. // return
  516. // }
  517. //
  518. // //if loginInfo != "1" {
  519. // // lastLoginTime := admin.LastLoginTime
  520. // //
  521. // // lastLoginTimeObj, err := time.Parse(utils.FormatDateWallWithLoc, lastLoginTime)
  522. // // fmt.Println(lastLoginTimeObj, err)
  523. // //
  524. // // msg := `该账号于` + lastLoginTimeObj.Format(utils.FormatDateTime) + "在其他网络登录。此客户端已退出登录。"
  525. // // c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  526. // // c.StopRun()
  527. // // return
  528. // //}
  529. //
  530. // // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
  531. // if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` {
  532. // utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  533. // // 不信任名单也同步更新
  534. // noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
  535. // utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
  536. // }
  537. //}
  538. admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
  539. c.SysUser = admin
  540. c.Session = session
  541. //接口权限校验
  542. roleId := admin.RoleId
  543. list, e := system.GetMenuButtonApisByRoleId(roleId)
  544. if e != nil {
  545. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  546. c.StopRun()
  547. return
  548. }
  549. var api string
  550. for _, v := range list {
  551. if v.Api != "" {
  552. api += v.Api + "&"
  553. }
  554. }
  555. if publicApi, ok := models.BusinessConfMap["PublicApi"]; ok {
  556. api += "&" + publicApi
  557. }
  558. //fmt.Println(api)
  559. //处理uri请求,去除前缀和参数
  560. api = strings.TrimRight(api, "&")
  561. uri = strings.Replace(uri, "/adminapi", "", 1)
  562. uris := strings.Split(uri, "?")
  563. uri = uris[0]
  564. //fmt.Println("uri:", uri)
  565. apis := strings.Split(api, "&")
  566. apiMap := make(map[string]bool, 0)
  567. for _, s := range apis {
  568. apiMap[s] = true
  569. }
  570. //fmt.Println("uri:", uri)
  571. //fmt.Println(apiMap)
  572. if !apiMap[uri] {
  573. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  574. c.StopRun()
  575. return
  576. }
  577. }
  578. // checkToken
  579. // @Description: 校验token
  580. // @author: Roc
  581. // @datetime 2024-10-30 11:29:37
  582. // @param c *BaseAuthController
  583. // @return isOk bool
  584. // @return session system.SysSession
  585. // @return resp models.BaseResponse
  586. func checkToken(c *BaseAuthController) (isOk bool, session *system.SysSession, resp models.BaseResponse) {
  587. // 是否校验成功
  588. isOk = true
  589. uri := c.Ctx.Input.URI()
  590. var token string
  591. // 单点登录逻辑
  592. aiUser := c.Ctx.GetCookie("ai_user")
  593. if aiUser == `` {
  594. aiUser = c.Ctx.GetCookie("ai_token")
  595. }
  596. //fmt.Println("ai_user:", aiUser)
  597. // 如果cookie里面没有这个,那么就过期重新登录
  598. if aiUser == `` {
  599. resp = models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "ai_user or ai_token empty"}
  600. isOk = false
  601. return
  602. }
  603. // cookie过期逻辑
  604. {
  605. aiUserExpireStr := c.Ctx.GetCookie("expire")
  606. if aiUserExpireStr == `` {
  607. resp = models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "expire empty"}
  608. isOk = false
  609. return
  610. }
  611. aiUserExpire, err := strconv.Atoi(aiUserExpireStr)
  612. if err != nil {
  613. resp = models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "expire 异常"}
  614. isOk = false
  615. return
  616. }
  617. // 将毫秒时间戳转换为秒和纳秒
  618. seconds := int64(aiUserExpire) / 1000
  619. nanoseconds := (int64(aiUserExpire) % 1000) * 1e6
  620. aiUserExpireTime := time.Unix(seconds, nanoseconds)
  621. if aiUserExpireTime.Before(time.Now()) {
  622. resp = models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "cookie已过期"}
  623. isOk = false
  624. return
  625. }
  626. }
  627. // 获取eta的token
  628. authorization := c.Ctx.Input.Header("authorization")
  629. if authorization == "" {
  630. authorization = c.Ctx.Input.Header("Authorization")
  631. }
  632. if authorization == "" {
  633. newAuthorization := c.GetString("authorization")
  634. if newAuthorization != `` {
  635. authorization = "authorization=" + newAuthorization
  636. } else {
  637. newAuthorization = c.GetString("Authorization")
  638. authorization = "authorization=" + newAuthorization
  639. }
  640. } else {
  641. if strings.Contains(authorization, ";") {
  642. authorization = strings.Replace(authorization, ";", "$", 1)
  643. }
  644. }
  645. if authorization == "" {
  646. strArr := strings.Split(uri, "?")
  647. //for k, v := range strArr {
  648. // fmt.Println(k, v)
  649. //}
  650. if len(strArr) > 1 {
  651. authorization = strArr[1]
  652. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  653. //fmt.Println(authorization)
  654. }
  655. }
  656. if authorization != "" {
  657. tokenStr := authorization
  658. tokenArr := strings.Split(tokenStr, "=")
  659. token = tokenArr[1]
  660. }
  661. //fmt.Println("token:", token)
  662. // Token空了, 以Cookie为准重新登录
  663. if token == `` {
  664. newLogin, e := services.UserLoginChange(aiUser)
  665. if e != nil {
  666. resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)}
  667. } else {
  668. resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin}
  669. }
  670. isOk = false
  671. return
  672. }
  673. // todo 将aiUser与session进行关联
  674. // token不为空, 那么去校验一下token是否过期, 以及和cookieVal是否匹配
  675. // 找不到session, 也直接切CookieValue中的用户登录
  676. session, err := system.GetSysSessionByToken(token)
  677. if err != nil {
  678. newLogin, e := services.UserLoginChange(aiUser)
  679. if e != nil {
  680. resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)}
  681. } else {
  682. resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin}
  683. }
  684. isOk = false
  685. return
  686. }
  687. // CookieVal不匹配、token验证失败、session以及redis中的token过期,那么以cookieVal的用户去登录并返回4014
  688. account := utils.MD5(session.UserName)
  689. //if session.UserName != aiUser || !utils.CheckToken(account, token) || time.Now().After(session.ExpiredTime){
  690. if session.UserName != aiUser || !utils.CheckToken(account, token) {
  691. newLogin, e := services.UserLoginChange(aiUser)
  692. if e != nil {
  693. resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)}
  694. } else {
  695. resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin}
  696. }
  697. isOk = false
  698. return
  699. }
  700. //account := utils.MD5(session.UserName)
  701. //if !utils.CheckToken(account, token) {
  702. // resp = models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}
  703. // isOk = false
  704. // return
  705. //}
  706. //if time.Now().After(session.ExpiredTime) {
  707. // resp = models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Err:" + err.Error()}
  708. // isOk = false
  709. // return
  710. //}
  711. // 正常逻辑
  712. if token == "" {
  713. resp = models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}
  714. isOk = false
  715. return
  716. }
  717. return
  718. }