base_auth.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. "net/url"
  9. "strconv"
  10. "strings"
  11. "time"
  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. if len(tokenArr) != 2 {
  33. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is fault"}, false, false)
  34. c.StopRun()
  35. return
  36. }
  37. token := tokenArr[1]
  38. session, err := models.GetSysSessionByToken(token)
  39. if err != nil {
  40. if err.Error() == utils.ErrNoRow() {
  41. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  42. c.StopRun()
  43. return
  44. }
  45. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
  46. c.StopRun()
  47. return
  48. }
  49. if session == nil {
  50. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
  51. c.StopRun()
  52. return
  53. }
  54. account := utils.MD5(session.UserName)
  55. if !utils.CheckToken(account, token) {
  56. c.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false)
  57. c.StopRun()
  58. return
  59. }
  60. if time.Now().After(session.ExpiredTime) {
  61. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常"}, false, false)
  62. c.StopRun()
  63. return
  64. }
  65. sysUser, err := models.GetSysUserById(session.SysUserId)
  66. if err != nil {
  67. if err.Error() == utils.ErrNoRow() {
  68. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取sysUser信息失败: " + strconv.Itoa(session.SysUserId)}, false, false)
  69. c.StopRun()
  70. return
  71. }
  72. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取sysUser信息异常,Err:" + err.Error()}, false, false)
  73. c.StopRun()
  74. return
  75. }
  76. if sysUser == nil {
  77. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sysUser is empty"}, false, false)
  78. c.StopRun()
  79. return
  80. }
  81. if !sysUser.IsEnabled {
  82. c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!"}, false, false)
  83. c.StopRun()
  84. return
  85. }
  86. loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.SysSessionId)
  87. loginInfo, _ := utils.Rc.RedisString(loginKey)
  88. if loginInfo == `` {
  89. c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false)
  90. c.StopRun()
  91. return
  92. }
  93. if loginInfo != "1" {
  94. msg := "在其他网络登录。此客户端已退出登录。"
  95. c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
  96. c.StopRun()
  97. return
  98. }
  99. // 有操作则延续token
  100. utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  101. noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, sysUser.SysUserId)
  102. utils.Rc.Put(noTrustLoginKey, session.SysSessionId, utils.LoginCacheTime*time.Minute)
  103. c.SysUser = sysUser
  104. c.Session = session
  105. //接口权限校验
  106. roleId := sysUser.SysRoleId
  107. list, e := models.GetMenuButtonsByRoleId(roleId)
  108. if e != nil {
  109. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  110. c.StopRun()
  111. return
  112. }
  113. var api string
  114. for _, v := range list {
  115. api += v.Api + "&"
  116. }
  117. api = strings.TrimRight(api, "&")
  118. uri = strings.Replace(uri, "/adminapi", "", 1)
  119. uris := strings.Split(uri, "?")
  120. uri = uris[0]
  121. //fmt.Println("uri:", uri)
  122. apis := strings.Split(api, "&")
  123. apiMap := make(map[string]bool, 0)
  124. for _, s := range apis {
  125. apiMap[s] = true
  126. }
  127. if !apiMap[uri] && !utils.NoAuthApiMap[uri] {
  128. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  129. c.StopRun()
  130. return
  131. }
  132. }
  133. }
  134. }
  135. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  136. var (
  137. hasIndent = false
  138. hasEncoding = false
  139. )
  140. if web.BConfig.RunMode == web.PROD {
  141. hasIndent = false
  142. }
  143. if len(encoding) > 0 && encoding[0] == true {
  144. hasEncoding = true
  145. }
  146. if c.Data["json"] == nil {
  147. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  148. fmt.Println(body)
  149. utils.ApiLog.Notice(body)
  150. return
  151. }
  152. baseRes := c.Data["json"].(*models.BaseResponse)
  153. if baseRes != nil && baseRes.Ret != 408 {
  154. body, _ := json.Marshal(baseRes)
  155. var requestBody string
  156. method := c.Ctx.Input.Method()
  157. if method == "GET" {
  158. requestBody = c.Ctx.Request.RequestURI
  159. } else {
  160. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  161. requestBody = string(c.Ctx.Input.RequestBody)
  162. }
  163. if baseRes.Ret != 200 {
  164. 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
  165. fmt.Println(body)
  166. utils.ApiLog.Notice(body)
  167. }
  168. }
  169. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  170. }
  171. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  172. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  173. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  174. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  175. // 设置Cookie为HTTPOnly
  176. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  177. var content []byte
  178. var err error
  179. if hasIndent {
  180. content, err = json.MarshalIndent(data, "", " ")
  181. } else {
  182. content, err = json.Marshal(data)
  183. }
  184. if err != nil {
  185. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  186. return err
  187. }
  188. ip := c.Ctx.Input.IP()
  189. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  190. if err != nil {
  191. utils.ApiLog.Info("err:%s", err.Error())
  192. }
  193. c.logUri(content, requestBody, ip)
  194. if utils.RunMode != "debug" {
  195. content = utils.DesBase64Encrypt(content, utils.DesKey)
  196. content = []byte(`"` + string(content) + `"`)
  197. }
  198. if coding {
  199. content = []byte(utils.StringsToJSON(string(content)))
  200. }
  201. return c.Ctx.Output.Body(content)
  202. }
  203. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  204. authorization := ""
  205. method := c.Ctx.Input.Method()
  206. uri := c.Ctx.Input.URI()
  207. if method != "HEAD" {
  208. if method == "POST" || method == "GET" {
  209. authorization = c.Ctx.Input.Header("authorization")
  210. if authorization == "" {
  211. authorization = c.Ctx.Input.Header("Authorization")
  212. }
  213. if authorization == "" {
  214. newAuthorization := c.GetString("authorization")
  215. if newAuthorization != `` {
  216. authorization = "authorization=" + newAuthorization
  217. } else {
  218. newAuthorization = c.GetString("Authorization")
  219. authorization = "authorization=" + newAuthorization
  220. }
  221. } else {
  222. if strings.Contains(authorization, ";") {
  223. authorization = strings.Replace(authorization, ";", "$", 1)
  224. }
  225. }
  226. if authorization == "" {
  227. strArr := strings.Split(uri, "?")
  228. for k, v := range strArr {
  229. fmt.Println(k, v)
  230. }
  231. if len(strArr) > 1 {
  232. authorization = strArr[1]
  233. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  234. fmt.Println(authorization)
  235. }
  236. }
  237. }
  238. }
  239. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  240. return
  241. }