base_auth.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_mini_crm/models"
  5. "eta/eta_mini_crm/utils"
  6. "fmt"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/beego/beego/v2/client/orm"
  12. "github.com/beego/beego/v2/server/web"
  13. )
  14. type BaseAuthController struct {
  15. web.Controller
  16. SysUser *models.SysUser
  17. Session *models.SysSession
  18. }
  19. func (c *BaseAuthController) Prepare() {
  20. method := c.Ctx.Input.Method()
  21. uri := c.Ctx.Input.URI()
  22. if method != "HEAD" {
  23. if method == "POST" || method == "GET" {
  24. authorization := c.Ctx.Input.Header("authorization")
  25. if authorization == "" {
  26. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  27. c.StopRun()
  28. return
  29. }
  30. tokenStr := authorization
  31. tokenArr := strings.Split(tokenStr, "=")
  32. token := tokenArr[1]
  33. session, err := models.GetSysSessionByToken(token)
  34. if err != nil {
  35. if err == orm.ErrNoRows {
  36. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  37. c.StopRun()
  38. return
  39. }
  40. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  41. c.StopRun()
  42. return
  43. }
  44. if session == nil {
  45. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  46. c.StopRun()
  47. return
  48. }
  49. account := utils.MD5(session.UserName)
  50. if !utils.CheckToken(account, token) {
  51. c.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false)
  52. c.StopRun()
  53. return
  54. }
  55. if time.Now().After(session.ExpiredTime) {
  56. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常"}, false, false)
  57. c.StopRun()
  58. return
  59. }
  60. sysUser, err := models.GetSysUserById(session.SysUserId)
  61. if err != nil {
  62. if err == orm.ErrNoRows {
  63. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取sysUser信息失败: " + strconv.Itoa(session.SysUserId)}, false, false)
  64. c.StopRun()
  65. return
  66. }
  67. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取sysUser信息异常,Err:" + err.Error()}, false, false)
  68. c.StopRun()
  69. return
  70. }
  71. if sysUser == nil {
  72. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sysUser is empty"}, false, false)
  73. c.StopRun()
  74. return
  75. }
  76. if !sysUser.IsEnabled {
  77. c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!"}, false, false)
  78. c.StopRun()
  79. return
  80. }
  81. loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.SysSessionId)
  82. loginInfo, _ := utils.Rc.RedisString(loginKey)
  83. if loginInfo == `` {
  84. c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  85. c.StopRun()
  86. return
  87. }
  88. if loginInfo != "1" {
  89. msg := "在其他网络登录。此客户端已退出登录。"
  90. c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  91. c.StopRun()
  92. return
  93. }
  94. c.SysUser = sysUser
  95. c.Session = session
  96. //接口权限校验
  97. roleId := sysUser.SysRoleId
  98. list, e := models.GetMenuButtonsByRoleId(roleId)
  99. if e != nil {
  100. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  101. c.StopRun()
  102. return
  103. }
  104. var api string
  105. for _, v := range list {
  106. api += v.Api + "&"
  107. }
  108. api = strings.TrimRight(api, "&")
  109. uri = strings.Replace(uri, "/adminapi", "", 1)
  110. uris := strings.Split(uri, "?")
  111. uri = uris[0]
  112. //fmt.Println("uri:", uri)
  113. apis := strings.Split(api, "&")
  114. apiMap := make(map[string]bool, 0)
  115. for _, s := range apis {
  116. apiMap[s] = true
  117. }
  118. if !apiMap[uri] && !utils.NoAuthApiMap[uri] {
  119. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  120. c.StopRun()
  121. return
  122. }
  123. }
  124. }
  125. }
  126. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  127. var (
  128. hasIndent = false
  129. hasEncoding = false
  130. )
  131. if web.BConfig.RunMode == web.PROD {
  132. hasIndent = false
  133. }
  134. if len(encoding) > 0 && encoding[0] == true {
  135. hasEncoding = true
  136. }
  137. if c.Data["json"] == nil {
  138. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  139. fmt.Println(body)
  140. utils.ApiLog.Notice(body)
  141. return
  142. }
  143. baseRes := c.Data["json"].(*models.BaseResponse)
  144. if baseRes != nil && baseRes.Ret != 408 {
  145. body, _ := json.Marshal(baseRes)
  146. var requestBody string
  147. method := c.Ctx.Input.Method()
  148. if method == "GET" {
  149. requestBody = c.Ctx.Request.RequestURI
  150. } else {
  151. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  152. requestBody = string(c.Ctx.Input.RequestBody)
  153. }
  154. if baseRes.Ret != 200 {
  155. body := "URI:" + c.Ctx.Input.URI() + "<br/> " + "Params" + requestBody + " <br/>" + "ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + "<br/>" + c.SysUser.SysRealName
  156. fmt.Println(body)
  157. utils.ApiLog.Notice(body)
  158. }
  159. if baseRes.IsAddLog && c.SysUser != nil {
  160. return
  161. }
  162. }
  163. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  164. }
  165. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  166. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  167. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  168. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  169. // 设置Cookie为HTTPOnly
  170. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  171. var content []byte
  172. var err error
  173. if hasIndent {
  174. content, err = json.MarshalIndent(data, "", " ")
  175. } else {
  176. content, err = json.Marshal(data)
  177. }
  178. if err != nil {
  179. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  180. return err
  181. }
  182. if utils.RunMode != "debug" {
  183. content = utils.DesBase64Encrypt(content, utils.DesKey)
  184. content = []byte(`"` + string(content) + `"`)
  185. }
  186. if coding {
  187. content = []byte(utils.StringsToJSON(string(content)))
  188. }
  189. return c.Ctx.Output.Body(content)
  190. }