auth.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. "server/config"
  11. "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. type ThirdSession struct {
  23. Enable bool
  24. CookieName string
  25. CheckUrl string
  26. }
  27. var thirdSession = ThirdSession{
  28. Enable: false,
  29. CookieName: "",
  30. CheckUrl: "",
  31. }
  32. func init() {
  33. beego.BConfig.WebConfig.Session.SessionAutoSetCookie = true
  34. thirdSession.Enable = beego.AppConfig.DefaultBool("thirdsessionenable", false)
  35. thirdSession.CookieName = beego.AppConfig.DefaultString("thirdsessionname", "")
  36. thirdSession.CheckUrl = beego.AppConfig.DefaultString("thirdsessioncheckurl", "")
  37. if thirdSession.Enable && (len(thirdSession.CookieName) == 0 || len(thirdSession.CheckUrl) == 0) {
  38. logs.Info("no thirdsessionname or thirdsessioncheckurl info,skip !")
  39. thirdSession.Enable = false
  40. }
  41. }
  42. func checkThirdSession(ctx *context.Context, sess session.Store) {
  43. if !thirdSession.Enable {
  44. return
  45. }
  46. cookie, err := ctx.Request.Cookie(thirdSession.CookieName)
  47. if err != nil {
  48. logs.Warn("no cookie", err)
  49. return
  50. }
  51. req := httplib.Get(thirdSession.CheckUrl)
  52. req.SetEnableCookie(true)
  53. req.SetCookie(cookie)
  54. user := models.User{}
  55. err = req.ToJSON(&user)
  56. if err != nil {
  57. logs.Warn("check third session fail ", err)
  58. return
  59. }
  60. err = sess.Set("user", user)
  61. if err != nil {
  62. logs.Warn("set session data fail ", err)
  63. return
  64. }
  65. logs.Debug("check third session ok ", user)
  66. }
  67. func AuthFilter(ctx *context.Context) {
  68. path := ctx.Request.RequestURI
  69. path = strings.TrimSuffix(path, "/")
  70. path = strings.TrimPrefix(path, config.Config.BaseApi)
  71. if whitelist[path] {
  72. logs.Debug("in whitelist ,skip ", ctx.Request.RequestURI, path)
  73. return
  74. }
  75. logs.Info(fmt.Sprintf("auth: %s,%s", ctx.Request.RequestURI, path))
  76. sess := ctx.Input.CruSession
  77. defer sess.SessionRelease(ctx.ResponseWriter)
  78. data := sess.Get("user")
  79. if data == nil {
  80. checkThirdSession(ctx, sess)
  81. }
  82. data = sess.Get("user")
  83. if data == nil {
  84. WriteForbidden(ctx.ResponseWriter)
  85. return
  86. }
  87. user := data.(models.User)
  88. if len(user.Account) == 0 {
  89. WriteForbidden(ctx.ResponseWriter)
  90. return
  91. }
  92. logs.Info(fmt.Sprintf("request uri: %s, uid: %s", ctx.Request.RequestURI, user.Account))
  93. }
  94. func WriteForbidden(w http.ResponseWriter) {
  95. w.WriteHeader(401)
  96. w.Header().Set("Content-Type", "application/json")
  97. _, err := w.Write([]byte(UnauthorizedResp))
  98. if err != nil {
  99. logs.Warn("writeForbidden write error", err)
  100. return
  101. }
  102. }