filter.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package xweb
  2. import (
  3. "net/http"
  4. "net/url"
  5. "regexp"
  6. )
  7. type Filter interface {
  8. Do(http.ResponseWriter, *http.Request) bool
  9. }
  10. type LoginFilter struct {
  11. App *App
  12. SessionName string
  13. AnonymousUrls []*regexp.Regexp
  14. AskLoginUrls []*regexp.Regexp
  15. Redirect string
  16. OriUrlName string
  17. }
  18. func NewLoginFilter(app *App, name string, redirect string) *LoginFilter {
  19. filter := &LoginFilter{App: app, SessionName: name,
  20. AnonymousUrls: make([]*regexp.Regexp, 0),
  21. AskLoginUrls: make([]*regexp.Regexp, 0),
  22. Redirect: redirect,
  23. }
  24. filter.AddAnonymousUrls("/favicon.ico", redirect)
  25. return filter
  26. }
  27. func (s *LoginFilter) AddAnonymousUrls(urls ...string) {
  28. for _, r := range urls {
  29. cr, err := regexp.Compile(r)
  30. if err == nil {
  31. s.AnonymousUrls = append(s.AnonymousUrls, cr)
  32. }
  33. }
  34. }
  35. func (s *LoginFilter) AddAskLoginUrls(urls ...string) {
  36. for _, r := range urls {
  37. cr, err := regexp.Compile(r)
  38. if err == nil {
  39. s.AskLoginUrls = append(s.AskLoginUrls, cr)
  40. }
  41. }
  42. }
  43. func (s *LoginFilter) Do(w http.ResponseWriter, req *http.Request) bool {
  44. requestPath := removeStick(req.URL.Path)
  45. session := s.App.SessionManager.Session(req, w)
  46. id := session.Get(s.SessionName)
  47. has := (id != nil && id != "")
  48. var redirect = s.Redirect
  49. if s.OriUrlName != "" {
  50. redirect = redirect + "?" + s.OriUrlName + "=" + url.QueryEscape(req.URL.String())
  51. }
  52. for _, cr := range s.AskLoginUrls {
  53. if !cr.MatchString(requestPath) {
  54. continue
  55. }
  56. match := cr.FindStringSubmatch(requestPath)
  57. if len(match[0]) != len(requestPath) {
  58. continue
  59. }
  60. if !has {
  61. s.App.Redirect(w, requestPath, redirect)
  62. }
  63. return has
  64. }
  65. if len(s.AnonymousUrls) == 0 {
  66. return true
  67. }
  68. for _, cr := range s.AnonymousUrls {
  69. if !cr.MatchString(requestPath) {
  70. continue
  71. }
  72. match := cr.FindStringSubmatch(requestPath)
  73. if len(match[0]) != len(requestPath) {
  74. continue
  75. }
  76. return true
  77. }
  78. if !has {
  79. s.App.Redirect(w, requestPath, redirect)
  80. }
  81. return has
  82. }