base_auth.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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, token, resp := checkToken(c)
  474. if !isOk {
  475. _ = c.JSON(resp, false, false)
  476. c.StopRun()
  477. return
  478. }
  479. //accountStr := authorizationArr[1]
  480. //accountArr := strings.Split(accountStr, "=")
  481. //account := accountArr[1]
  482. session, err := system.GetSysSessionByToken(token)
  483. //fmt.Println("session:", session)
  484. if err != nil {
  485. if utils.IsErrNoRow(err) {
  486. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  487. c.StopRun()
  488. return
  489. }
  490. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  491. c.StopRun()
  492. return
  493. }
  494. if session == nil {
  495. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  496. c.StopRun()
  497. return
  498. }
  499. //校验token是否合法
  500. // JWT校验Token和Account
  501. account := utils.MD5(session.UserName)
  502. if !utils.CheckToken(account, token) {
  503. c.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false)
  504. c.StopRun()
  505. return
  506. }
  507. if time.Now().After(session.ExpiredTime) {
  508. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  509. c.StopRun()
  510. return
  511. }
  512. admin, err := system.GetSysUserById(session.SysUserId)
  513. if err != nil {
  514. if utils.IsErrNoRow(err) {
  515. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false)
  516. c.StopRun()
  517. return
  518. }
  519. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false)
  520. c.StopRun()
  521. return
  522. }
  523. if admin == nil {
  524. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
  525. c.StopRun()
  526. return
  527. }
  528. //如果不是启用状态
  529. if admin.Enabled != 1 {
  530. c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false)
  531. c.StopRun()
  532. return
  533. }
  534. // 如果当前登录态是不可信设备的,那么需要做过期校验
  535. if session.IsRemember != 1 {
  536. loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id)
  537. loginInfo, _ := utils.Rc.RedisString(loginKey)
  538. if loginInfo == `` {
  539. c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  540. c.StopRun()
  541. return
  542. }
  543. //if loginInfo != "1" {
  544. // lastLoginTime := admin.LastLoginTime
  545. //
  546. // lastLoginTimeObj, err := time.Parse(utils.FormatDateWallWithLoc, lastLoginTime)
  547. // fmt.Println(lastLoginTimeObj, err)
  548. //
  549. // msg := `该账号于` + lastLoginTimeObj.Format(utils.FormatDateTime) + "在其他网络登录。此客户端已退出登录。"
  550. // c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  551. // c.StopRun()
  552. // return
  553. //}
  554. // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
  555. if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` {
  556. utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  557. // 不信任名单也同步更新
  558. noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
  559. utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
  560. }
  561. }
  562. admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
  563. c.SysUser = admin
  564. c.Session = session
  565. //接口权限校验
  566. roleId := admin.RoleId
  567. list, e := system.GetMenuButtonApisByRoleId(roleId)
  568. if e != nil {
  569. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  570. c.StopRun()
  571. return
  572. }
  573. var api string
  574. for _, v := range list {
  575. if v.Api != "" {
  576. api += v.Api + "&"
  577. }
  578. }
  579. //fmt.Println(api)
  580. //处理uri请求,去除前缀和参数
  581. api = strings.TrimRight(api, "&")
  582. uri = strings.Replace(uri, "/adminapi", "", 1)
  583. uris := strings.Split(uri, "?")
  584. uri = uris[0]
  585. //fmt.Println("uri:", uri)
  586. apis := strings.Split(api, "&")
  587. apiMap := make(map[string]bool, 0)
  588. for _, s := range apis {
  589. apiMap[s] = true
  590. }
  591. //fmt.Println("uri:", uri)
  592. //fmt.Println(apiMap)
  593. if !apiMap[uri] {
  594. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  595. c.StopRun()
  596. return
  597. }
  598. }
  599. // checkToken
  600. // @Description: 校验token
  601. // @author: Roc
  602. // @datetime 2024-10-30 11:29:37
  603. // @param c *BaseAuthController
  604. // @return isOk bool
  605. // @return token string
  606. // @return resp models.BaseResponse
  607. func checkToken(c *BaseAuthController) (isOk bool, token string, resp models.BaseResponse) {
  608. // 是否校验成功
  609. isOk = true
  610. uri := c.Ctx.Input.URI()
  611. authorization := c.Ctx.Input.Header("authorization")
  612. if authorization == "" {
  613. authorization = c.Ctx.Input.Header("Authorization")
  614. }
  615. if authorization == "" {
  616. newAuthorization := c.GetString("authorization")
  617. if newAuthorization != `` {
  618. authorization = "authorization=" + newAuthorization
  619. } else {
  620. newAuthorization = c.GetString("Authorization")
  621. authorization = "authorization=" + newAuthorization
  622. }
  623. } else {
  624. if strings.Contains(authorization, ";") {
  625. authorization = strings.Replace(authorization, ";", "$", 1)
  626. }
  627. }
  628. if authorization == "" {
  629. strArr := strings.Split(uri, "?")
  630. //for k, v := range strArr {
  631. // fmt.Println(k, v)
  632. //}
  633. if len(strArr) > 1 {
  634. authorization = strArr[1]
  635. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  636. //fmt.Println(authorization)
  637. }
  638. }
  639. if authorization != "" {
  640. tokenStr := authorization
  641. tokenArr := strings.Split(tokenStr, "=")
  642. token = tokenArr[1]
  643. }
  644. // 单点登录逻辑
  645. aiUser := c.Ctx.GetCookie("ai_user")
  646. if aiUser == `` {
  647. aiUser = c.Ctx.GetCookie("ai_token")
  648. }
  649. fmt.Println("ai_user:", aiUser)
  650. //fmt.Println("token:", token)
  651. if aiUser != "" {
  652. // Token空了, 以Cookie为准重新登录
  653. if token == `` {
  654. newLogin, e := services.UserLoginChange(aiUser)
  655. if e != nil {
  656. resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)}
  657. } else {
  658. resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin}
  659. }
  660. isOk = false
  661. return
  662. }
  663. // todo 将aiUser与session进行关联
  664. // token不为空, 那么去校验一下token是否过期, 以及和cookieVal是否匹配
  665. // 找不到session, 也直接切CookieValue中的用户登录
  666. session, err := system.GetSysSessionByToken(token)
  667. if err != nil {
  668. newLogin, e := services.UserLoginChange(aiUser)
  669. if e != nil {
  670. resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)}
  671. } else {
  672. resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin}
  673. }
  674. isOk = false
  675. return
  676. }
  677. // CookieVal不匹配、token验证失败、session以及redis中的token过期,那么以cookieVal的用户去登录并返回4014
  678. account := utils.MD5(session.UserName)
  679. loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id)
  680. loginCache, _ := utils.Rc.RedisString(loginKey)
  681. if session.UserName != aiUser || !utils.CheckToken(account, token) || time.Now().After(session.ExpiredTime) || (session.IsRemember != 1 && loginCache == ``) {
  682. newLogin, e := services.UserLoginChange(aiUser)
  683. if e != nil {
  684. resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)}
  685. } else {
  686. resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin}
  687. }
  688. isOk = false
  689. return
  690. }
  691. }
  692. // 正常逻辑
  693. if token == "" {
  694. resp = models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}
  695. isOk = false
  696. return
  697. }
  698. return
  699. }