base_auth.go 14 KB

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