base_auth.go 13 KB

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