/
middleware.go
240 lines (213 loc) · 6 KB
/
middleware.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package login
import (
"context"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
type ContextUserKey int
const (
UserKey ContextUserKey = iota
loginWIPKey
)
type MiddlewareConfig interface {
middlewareConfig()
}
// LoginNotRequired executes the next handler regardless of whether the user is logged in or not
type LoginNotRequired struct{}
func (*LoginNotRequired) middlewareConfig() {}
// DisableAutoRedirectToHomePage makes it possible to visit login page when user is logged in
type DisableAutoRedirectToHomePage struct{}
func (*DisableAutoRedirectToHomePage) middlewareConfig() {}
func (b *Builder) Middleware(cfgs ...MiddlewareConfig) func(next http.Handler) http.Handler {
mustLogin := true
autoRedirectToHomePage := true
for _, cfg := range cfgs {
switch cfg.(type) {
case *LoginNotRequired:
mustLogin = false
case *DisableAutoRedirectToHomePage:
autoRedirectToHomePage = false
}
}
whiteList := map[string]struct{}{
b.oauthBeginURL: {},
b.oauthCallbackURL: {},
b.oauthCallbackCompleteURL: {},
b.passwordLoginURL: {},
b.forgetPasswordPageURL: {},
b.sendResetPasswordLinkURL: {},
b.resetPasswordLinkSentPageURL: {},
b.resetPasswordURL: {},
b.resetPasswordPageURL: {},
b.validateTOTPURL: {},
}
staticFileRe := regexp.MustCompile(`\.(css|js|gif|jpg|jpeg|png|ico|svg|ttf|eot|woff|woff2)$`)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if staticFileRe.MatchString(strings.ToLower(r.URL.Path)) {
next.ServeHTTP(w, r)
return
}
if _, ok := whiteList[r.URL.Path]; ok {
next.ServeHTTP(w, r)
return
}
path := strings.TrimRight(r.URL.Path, "/")
claims, err := parseUserClaimsFromCookie(r, b.authCookieName, b.secret)
if err != nil {
if !mustLogin {
next.ServeHTTP(w, r)
return
}
if r.Method == http.MethodGet {
b.setContinueURL(w, r)
}
if path == b.loginPageURL {
next.ServeHTTP(w, r)
} else {
http.Redirect(w, r, b.loginPageURL, http.StatusFound)
}
return
}
var user interface{}
var secureSalt string
if b.userModel != nil {
var err error
user, err = b.findUserByID(claims.UserID)
if err == nil {
if claims.Provider == "" {
if user.(UserPasser).GetPasswordUpdatedAt() != claims.PassUpdatedAt {
err = ErrPasswordChanged
}
if user.(UserPasser).GetLocked() {
err = ErrUserLocked
}
} else {
user.(OAuthUser).SetAvatar(claims.AvatarURL)
}
}
if err != nil {
if !mustLogin {
next.ServeHTTP(w, r)
return
}
switch err {
case ErrUserNotFound:
setFailCodeFlash(w, FailCodeUserNotFound)
case ErrUserLocked:
setFailCodeFlash(w, FailCodeUserLocked)
case ErrPasswordChanged:
isSelfChange := false
if c, err := r.Cookie(infoCodeFlashCookieName); err == nil {
v, _ := strconv.Atoi(c.Value)
if InfoCode(v) == InfoCodePasswordSuccessfullyChanged {
isSelfChange = true
}
}
if !isSelfChange {
setWarnCodeFlash(w, WarnCodePasswordHasBeenChanged)
}
default:
panic(err)
}
if path == b.LogoutURL {
next.ServeHTTP(w, r)
} else {
http.Redirect(w, r, b.LogoutURL, http.StatusFound)
}
return
}
if b.sessionSecureEnabled {
secureSalt = user.(SessionSecurer).GetSecure()
_, err := parseBaseClaimsFromCookie(r, b.authSecureCookieName, b.secret+secureSalt)
if err != nil {
if !mustLogin {
next.ServeHTTP(w, r)
return
}
if path == b.LogoutURL {
next.ServeHTTP(w, r)
} else {
http.Redirect(w, r, b.LogoutURL, http.StatusFound)
}
return
}
}
} else {
user = claims
}
if b.autoExtendSession && time.Now().Sub(claims.IssuedAt.Time).Seconds() > float64(b.sessionMaxAge)/10 {
oldSessionToken := b.mustGetSessionToken(*claims)
claims.RegisteredClaims = b.genBaseSessionClaim(claims.UserID)
b.setAuthCookiesFromUserClaims(w, claims, secureSalt)
if b.afterExtendSessionHook != nil {
setCookieForRequest(r, &http.Cookie{Name: b.authCookieName, Value: b.mustGetSessionToken(*claims)})
if herr := b.afterExtendSessionHook(r, user, oldSessionToken); herr != nil {
if !mustLogin {
next.ServeHTTP(w, r)
return
}
setNoticeOrPanic(w, herr)
http.Redirect(w, r, b.LogoutURL, http.StatusFound)
return
}
}
}
r = r.WithContext(context.WithValue(r.Context(), UserKey, user))
if path == b.LogoutURL {
next.ServeHTTP(w, r)
return
}
if claims.Provider == "" && b.totpEnabled {
if !user.(UserPasser).GetIsTOTPSetup() {
if path == b.loginPageURL {
next.ServeHTTP(w, r)
return
}
r = r.WithContext(context.WithValue(r.Context(), loginWIPKey, true))
if path == b.totpSetupPageURL {
next.ServeHTTP(w, r)
return
}
http.Redirect(w, r, b.totpSetupPageURL, http.StatusFound)
return
}
if !claims.TOTPValidated {
if path == b.loginPageURL {
next.ServeHTTP(w, r)
return
}
r = r.WithContext(context.WithValue(r.Context(), loginWIPKey, true))
if path == b.totpValidatePageURL {
next.ServeHTTP(w, r)
return
}
http.Redirect(w, r, b.totpValidatePageURL, http.StatusFound)
return
}
}
if autoRedirectToHomePage {
if path == b.loginPageURL || path == b.totpSetupPageURL || path == b.totpValidatePageURL {
http.Redirect(w, r, b.homePageURLFunc(r, user), http.StatusFound)
return
}
}
next.ServeHTTP(w, r)
})
}
}
func GetCurrentUser(r *http.Request) (u interface{}) {
return r.Context().Value(UserKey)
}
// IsLoginWIP indicates whether the user is in an intermediate step of login process,
// such as on the TOTP validation page
func IsLoginWIP(r *http.Request) bool {
v, ok := r.Context().Value(loginWIPKey).(bool)
if !ok {
return false
}
return v
}