auth.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. "/ldap/login": true,
  21. "/ldap/server/active": true,
  22. }
  23. var UnauthorizedResp = `{"code": 401, "msg":"未登录或者登录已过期!"}`
  24. func init() {
  25. beego.BConfig.WebConfig.Session.SessionAutoSetCookie = true
  26. }
  27. func checkThirdSession(ctx *context.Context, sess session.Store) {
  28. cfg := config.Config
  29. if !cfg.ThirdSession {
  30. return
  31. }
  32. cookie, err := ctx.Request.Cookie(cfg.ThirdSessionName)
  33. if err != nil {
  34. logs.Warn("no cookie", err)
  35. return
  36. }
  37. req := httplib.Get(cfg.ThirdSessionCheckUrl)
  38. req.SetEnableCookie(true)
  39. req.SetCookie(cookie)
  40. user := models.User{}
  41. err = req.ToJSON(&user)
  42. if err != nil {
  43. logs.Warn("check third session fail ", err)
  44. return
  45. }
  46. err = sess.Set("user", user)
  47. if err != nil {
  48. logs.Warn("set session data fail ", err)
  49. return
  50. }
  51. logs.Debug("check third session ok ", user)
  52. }
  53. func AuthFilter(ctx *context.Context) {
  54. path := ctx.Request.URL.Path
  55. path = strings.TrimSuffix(path, "/")
  56. path = strings.TrimPrefix(path, config.Config.BaseApi)
  57. if whitelist[path] {
  58. logs.Debug("in whitelist ,skip ", ctx.Request.RequestURI, path)
  59. return
  60. }
  61. logs.Info(fmt.Sprintf("auth: %s,%s", ctx.Request.RequestURI, path))
  62. sess := ctx.Input.CruSession
  63. if sess == nil {
  64. logs.Warn("no session found in request")
  65. return
  66. }
  67. defer sess.SessionRelease(ctx.ResponseWriter)
  68. data := sess.Get("user")
  69. if data == nil {
  70. checkThirdSession(ctx, sess)
  71. }
  72. data = sess.Get("user")
  73. if data == nil {
  74. WriteForbidden(ctx.ResponseWriter)
  75. return
  76. }
  77. user := data.(models.User)
  78. if len(user.Account) == 0 {
  79. WriteForbidden(ctx.ResponseWriter)
  80. return
  81. }
  82. logs.Info(fmt.Sprintf("request uri: %s, uid: %s", ctx.Request.RequestURI, user.Account))
  83. }
  84. func WriteForbidden(w http.ResponseWriter) {
  85. w.WriteHeader(401)
  86. w.Header().Set("Content-Type", "application/json")
  87. _, err := w.Write([]byte(UnauthorizedResp))
  88. if err != nil {
  89. logs.Warn("writeForbidden write error", err)
  90. return
  91. }
  92. }