base_auth.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_mini_crm_ht/models"
  5. "eta/eta_mini_crm_ht/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. c.SysUser = sysUser
  100. c.Session = session
  101. //接口权限校验
  102. roleId := sysUser.SysRoleId
  103. list, e := models.GetMenuButtonsByRoleId(roleId)
  104. if e != nil {
  105. c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false)
  106. c.StopRun()
  107. return
  108. }
  109. var api string
  110. for _, v := range list {
  111. api += v.Api + "&"
  112. }
  113. api = strings.TrimRight(api, "&")
  114. uri = strings.Replace(uri, "/adminapi", "", 1)
  115. uris := strings.Split(uri, "?")
  116. uri = uris[0]
  117. //fmt.Println("uri:", uri)
  118. apis := strings.Split(api, "&")
  119. apiMap := make(map[string]bool, 0)
  120. for _, s := range apis {
  121. apiMap[s] = true
  122. }
  123. if !apiMap[uri] && !utils.NoAuthApiMap[uri] {
  124. c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
  125. c.StopRun()
  126. return
  127. }
  128. }
  129. }
  130. }
  131. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  132. var (
  133. hasIndent = false
  134. hasEncoding = false
  135. )
  136. if web.BConfig.RunMode == web.PROD {
  137. hasIndent = false
  138. }
  139. if len(encoding) > 0 && encoding[0] == true {
  140. hasEncoding = true
  141. }
  142. if c.Data["json"] == nil {
  143. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  144. fmt.Println(body)
  145. utils.ApiLog.Notice(body)
  146. return
  147. }
  148. baseRes := c.Data["json"].(*models.BaseResponse)
  149. if baseRes != nil && baseRes.Ret != 408 {
  150. body, _ := json.Marshal(baseRes)
  151. var requestBody string
  152. method := c.Ctx.Input.Method()
  153. if method == "GET" {
  154. requestBody = c.Ctx.Request.RequestURI
  155. } else {
  156. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  157. requestBody = string(c.Ctx.Input.RequestBody)
  158. }
  159. if baseRes.Ret != 200 {
  160. 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
  161. fmt.Println(body)
  162. utils.ApiLog.Notice(body)
  163. }
  164. }
  165. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  166. }
  167. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  168. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  169. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  170. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  171. // 设置Cookie为HTTPOnly
  172. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  173. var content []byte
  174. var err error
  175. if hasIndent {
  176. content, err = json.MarshalIndent(data, "", " ")
  177. } else {
  178. content, err = json.Marshal(data)
  179. }
  180. if err != nil {
  181. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  182. return err
  183. }
  184. ip := c.Ctx.Input.IP()
  185. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  186. if err != nil {
  187. utils.ApiLog.Info("err:%s", err.Error())
  188. }
  189. c.logUri(content, requestBody, ip)
  190. if utils.RunMode != "debug" {
  191. content = utils.DesBase64Encrypt(content, utils.DesKey)
  192. content = []byte(`"` + string(content) + `"`)
  193. }
  194. if coding {
  195. content = []byte(utils.StringsToJSON(string(content)))
  196. }
  197. return c.Ctx.Output.Body(content)
  198. }
  199. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  200. authorization := ""
  201. method := c.Ctx.Input.Method()
  202. uri := c.Ctx.Input.URI()
  203. if method != "HEAD" {
  204. if method == "POST" || method == "GET" {
  205. authorization = c.Ctx.Input.Header("authorization")
  206. if authorization == "" {
  207. authorization = c.Ctx.Input.Header("Authorization")
  208. }
  209. if authorization == "" {
  210. newAuthorization := c.GetString("authorization")
  211. if newAuthorization != `` {
  212. authorization = "authorization=" + newAuthorization
  213. } else {
  214. newAuthorization = c.GetString("Authorization")
  215. authorization = "authorization=" + newAuthorization
  216. }
  217. } else {
  218. if strings.Contains(authorization, ";") {
  219. authorization = strings.Replace(authorization, ";", "$", 1)
  220. }
  221. }
  222. if authorization == "" {
  223. strArr := strings.Split(uri, "?")
  224. for k, v := range strArr {
  225. fmt.Println(k, v)
  226. }
  227. if len(strArr) > 1 {
  228. authorization = strArr[1]
  229. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  230. fmt.Println(authorization)
  231. }
  232. }
  233. }
  234. }
  235. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  236. return
  237. }