base_auth.go 26 KB

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