auth.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/astaxie/beego"
  5. "github.com/astaxie/beego/context"
  6. "github.com/astaxie/beego/logs"
  7. "github.com/astaxie/beego/session"
  8. "github.com/beego/beego/v2/client/httplib"
  9. "net/http"
  10. "nginx-ui/server/config"
  11. "nginx-ui/server/models"
  12. "strings"
  13. )
  14. // 白名单,不需要登录即可访问
  15. var whitelist = map[string]bool{
  16. "/user/login": true,
  17. "/user/register": true,
  18. "/oauth2": true,
  19. "/oauth2/callback": true,
  20. }
  21. var UnauthorizedResp = `{"code": 401, "msg":"未登录或者登录已过期!"}`
  22. func init() {
  23. beego.BConfig.WebConfig.Session.SessionAutoSetCookie = true
  24. }
  25. func checkThirdSession(ctx *context.Context, sess session.Store) {
  26. cfg := config.Config
  27. if !cfg.ThirdSession {
  28. return
  29. }
  30. cookie, err := ctx.Request.Cookie(cfg.ThirdSessionName)
  31. if err != nil {
  32. logs.Warn("no cookie", err)
  33. return
  34. }
  35. req := httplib.Get(cfg.ThirdSessionCheckUrl)
  36. req.SetEnableCookie(true)
  37. req.SetCookie(cookie)
  38. user := models.User{}
  39. err = req.ToJSON(&user)
  40. if err != nil {
  41. logs.Warn("check third session fail ", err)
  42. return
  43. }
  44. err = sess.Set("user", user)
  45. if err != nil {
  46. logs.Warn("set session data fail ", err)
  47. return
  48. }
  49. logs.Debug("check third session ok ", user)
  50. }
  51. func AuthFilter(ctx *context.Context) {
  52. path := ctx.Request.URL.Path
  53. path = strings.TrimSuffix(path, "/")
  54. path = strings.TrimPrefix(path, config.Config.BaseApi)
  55. if whitelist[path] {
  56. logs.Debug("in whitelist ,skip ", ctx.Request.RequestURI, path)
  57. return
  58. }
  59. logs.Info(fmt.Sprintf("auth: %s,%s", ctx.Request.RequestURI, path))
  60. sess := ctx.Input.CruSession
  61. if sess == nil {
  62. logs.Warn("no session found in request")
  63. return
  64. }
  65. defer sess.SessionRelease(ctx.ResponseWriter)
  66. data := sess.Get("user")
  67. if data == nil {
  68. checkThirdSession(ctx, sess)
  69. }
  70. data = sess.Get("user")
  71. if data == nil {
  72. WriteForbidden(ctx.ResponseWriter)
  73. return
  74. }
  75. user := data.(models.User)
  76. if len(user.Account) == 0 {
  77. WriteForbidden(ctx.ResponseWriter)
  78. return
  79. }
  80. logs.Info(fmt.Sprintf("request uri: %s, uid: %s", ctx.Request.RequestURI, user.Account))
  81. }
  82. func WriteForbidden(w http.ResponseWriter) {
  83. w.WriteHeader(401)
  84. w.Header().Set("Content-Type", "application/json")
  85. _, err := w.Write([]byte(UnauthorizedResp))
  86. if err != nil {
  87. logs.Warn("writeForbidden write error", err)
  88. return
  89. }
  90. }