-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathauthentication.go
More file actions
220 lines (204 loc) · 6.19 KB
/
authentication.go
File metadata and controls
220 lines (204 loc) · 6.19 KB
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
package main
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"strings"
"github.com/pquerna/otp/totp"
"go.goblog.app/app/pkgs/bodylimit"
"go.goblog.app/app/pkgs/bufferpool"
"go.goblog.app/app/pkgs/contenttype"
)
const (
loggedInKey contextKey = "loggedIn"
loginPath = "/login"
logoutPath = "/logout"
)
// Check if credentials are correct
func (a *goBlog) checkCredentials(username, password, totpPasscode string) bool {
// Check username
if username != a.cfg.User.Nick {
return false
}
// Check password
if pwdValid, _ := a.checkPassword(password); !pwdValid {
return false
}
// Check TOTP
if a.totpEnabled() {
totpSecret, _ := a.getTOTPSecret()
if !totp.Validate(totpPasscode, totpSecret) {
return false
}
}
return true
}
// Check if app passwords are correct
func (a *goBlog) checkAppPasswords(password string) bool {
// Check database app passwords (username is ignored)
if valid, err := a.checkAppPassword(password); err == nil && valid {
return true
}
return false
}
// totpEnabled checks if TOTP is enabled
func (a *goBlog) totpEnabled() bool {
if a.db != nil {
if hasTOTP, err := a.hasTOTP(); err == nil && hasTOTP {
return true
}
}
return false
}
// Check if cookie is known and logged in
func (a *goBlog) checkLoginCookie(r *http.Request) bool {
a.initSessionStores()
ses, err := a.loginSessions.Get(r, "l")
if err == nil && ses != nil {
if login, ok := ses.Values["login"]; ok && login.(bool) {
return true
}
}
return false
}
// Middleware to force login
func (a *goBlog) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if already logged in
if a.isLoggedIn(r) {
next.ServeHTTP(w, r)
return
}
// Encode original request
headerBuffer, bodyBuffer := bufferpool.Get(), bufferpool.Get()
defer bufferpool.Put(headerBuffer, bodyBuffer)
// Encode headers
headerEncoder := base64.NewEncoder(base64.StdEncoding, headerBuffer)
_ = json.NewEncoder(headerEncoder).Encode(r.Header)
_ = headerEncoder.Close()
// Encode body
bodyEncoder := base64.NewEncoder(base64.StdEncoding, bodyBuffer)
limit := 3 * bodylimit.MB
written, _ := io.Copy(bodyEncoder, io.LimitReader(r.Body, limit))
if written == 0 {
// Maybe it's a form
_ = r.ParseForm() //nolint:gosec
// Encode form
sw, _ := io.WriteString(bodyEncoder, r.Form.Encode())
written = int64(sw)
}
bodyEncoder.Close()
if written >= limit {
a.serveError(w, r, "Request body too large, first login", http.StatusRequestEntityTooLarge)
return
}
// Render login form
w.Header().Set(cacheControl, "no-store,max-age=0")
w.Header().Set("X-Robots-Tag", "noindex")
a.render(w, r, a.renderLogin, &renderData{
Data: &loginRenderData{
loginMethod: r.Method,
loginHeaders: headerBuffer.String(),
loginBody: bodyBuffer.String(),
totp: a.totpEnabled(),
},
})
})
}
// Middleware to check if the request is a login request
func (a *goBlog) checkIsLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if !a.checkLogin(rw, r) {
next.ServeHTTP(rw, r)
}
})
}
// Checks login and returns true if it already served an error
func (a *goBlog) checkLogin(w http.ResponseWriter, r *http.Request) bool {
if r.Method != http.MethodPost {
return false
}
if !strings.Contains(r.Header.Get(contentType), contenttype.WWWForm) {
return false
}
if r.FormValue("loginaction") != "login" { //nolint:gosec
return false
}
// Check credential
if !a.checkCredentials(r.FormValue("username"), r.FormValue("password"), r.FormValue("token")) { //nolint:gosec
a.serveError(w, r, "Incorrect credentials", http.StatusUnauthorized)
return true
}
// Prepare original request
bodyDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(r.FormValue("loginbody"))) //nolint:gosec
origReq, _ := http.NewRequestWithContext(r.Context(), r.FormValue("loginmethod"), r.URL.RequestURI(), bodyDecoder) //nolint:gosec
headerDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(r.FormValue("loginheaders"))) //nolint:gosec
_ = json.NewDecoder(headerDecoder).Decode(&origReq.Header)
// Cookie
a.initSessionStores()
ses, err := a.loginSessions.Get(r, "l")
if err != nil {
a.error("Failed to get login session", "err", err)
a.serveError(w, r, "", http.StatusInternalServerError)
return true
}
ses.Values["login"] = true
err = a.loginSessions.Save(r, w, ses)
if err != nil {
a.error("Failed to save login session", "err", err)
a.serveError(w, r, "", http.StatusInternalServerError)
return true
}
// Serve original request
setLoggedIn(origReq, true)
a.d.ServeHTTP(w, origReq)
return true
}
func (a *goBlog) isLoggedIn(r *http.Request) bool {
// Check if context key already set
if loggedIn, ok := r.Context().Value(loggedInKey).(bool); ok {
return loggedIn
}
// Check app passwords
if _, password, ok := r.BasicAuth(); ok && a.checkAppPasswords(password) {
setLoggedIn(r, true)
return true
}
// Check session cookie
if a.checkLoginCookie(r) {
setLoggedIn(r, true)
return true
}
// Not logged in
return false
}
// Set request context value
func setLoggedIn(r *http.Request, loggedIn bool) {
// Overwrite the value of r (r is a pointer)
(*r) = *(r.WithContext(context.WithValue(r.Context(), loggedInKey, loggedIn)))
}
// HandlerFunc to redirect to home after login
// Need to set auth middleware!
func serveLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
}
// HandlerFunc to delete login session and cookie
func (a *goBlog) serveLogout(w http.ResponseWriter, r *http.Request) {
a.initSessionStores()
if ses, err := a.loginSessions.Get(r, "l"); err == nil && ses != nil {
_ = a.loginSessions.Delete(r, w, ses)
}
http.Redirect(w, r, "/", http.StatusFound)
}
func (a *goBlog) getDefaultPostStates(r *http.Request) (status []postStatus, visibility []postVisibility) {
if a.isLoggedIn(r) {
status = []postStatus{statusPublished}
visibility = []postVisibility{visibilityPublic, visibilityUnlisted, visibilityPrivate}
} else {
status = []postStatus{statusPublished}
visibility = []postVisibility{visibilityPublic}
}
return
}