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