base_auth.go 12 KB

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