GoBlog/authentication.go

156 lines
4.3 KiB
Go
Raw Normal View History

2020-12-15 16:40:14 +00:00
package main
import (
"bytes"
2021-02-20 22:35:16 +00:00
"context"
2020-12-15 16:40:14 +00:00
"encoding/base64"
2021-01-21 16:59:47 +00:00
"encoding/json"
2020-12-15 16:40:14 +00:00
"io"
"net/http"
2021-02-28 07:57:15 +00:00
"github.com/pquerna/otp/totp"
"go.goblog.app/app/pkgs/contenttype"
2020-12-15 16:40:14 +00:00
)
func (a *goBlog) checkCredentials(username, password, totpPasscode string) bool {
return username == a.cfg.User.Nick &&
password == a.cfg.User.Password &&
(a.cfg.User.TOTP == "" || totp.Validate(totpPasscode, a.cfg.User.TOTP))
2020-12-15 16:40:14 +00:00
}
func (a *goBlog) checkAppPasswords(username, password string) bool {
for _, apw := range a.cfg.User.AppPasswords {
2021-02-28 07:57:15 +00:00
if apw.Username == username && apw.Password == password {
return true
}
}
return false
}
func (a *goBlog) jwtKey() []byte {
return []byte(a.cfg.Server.JWTSecret)
2020-12-15 16:40:14 +00:00
}
func (a *goBlog) authMiddleware(next http.Handler) http.Handler {
2020-12-15 16:40:14 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2021-05-14 16:24:02 +00:00
// 1. Check if already logged in
2021-02-20 22:35:16 +00:00
if loggedIn, ok := r.Context().Value(loggedInKey).(bool); ok && loggedIn {
next.ServeHTTP(w, r)
return
}
2021-05-14 16:24:02 +00:00
// 2. Check BasicAuth (just for app passwords)
if username, password, ok := r.BasicAuth(); ok && a.checkAppPasswords(username, password) {
next.ServeHTTP(w, r)
return
}
2021-05-14 16:24:02 +00:00
// 3. Check login cookie
if a.checkLoginCookie(r) {
2021-05-14 16:24:02 +00:00
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), loggedInKey, true)))
2021-02-20 22:35:16 +00:00
return
2020-12-15 16:40:14 +00:00
}
2021-05-14 16:24:02 +00:00
// 4. Show login form
w.Header().Set("Cache-Control", "no-store,max-age=0")
2020-12-15 16:40:14 +00:00
h, _ := json.Marshal(r.Header.Clone())
2021-02-17 07:23:03 +00:00
b, _ := io.ReadAll(io.LimitReader(r.Body, 2000000)) // Only allow 20 Megabyte
2020-12-15 16:40:14 +00:00
_ = r.Body.Close()
if len(b) == 0 {
// Maybe it's a form
_ = r.ParseForm()
b = []byte(r.PostForm.Encode())
}
a.render(w, r, templateLogin, &renderData{
2021-02-28 07:57:15 +00:00
Data: map[string]interface{}{
2020-12-15 16:40:14 +00:00
"loginmethod": r.Method,
"loginheaders": base64.StdEncoding.EncodeToString(h),
"loginbody": base64.StdEncoding.EncodeToString(b),
"totp": a.cfg.User.TOTP != "",
2020-12-15 16:40:14 +00:00
},
})
})
}
const loggedInKey contextKey = "loggedIn"
2021-02-20 22:35:16 +00:00
func (a *goBlog) checkLoggedIn(next http.Handler) http.Handler {
2021-02-20 22:35:16 +00:00
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if a.checkLoginCookie(r) {
2021-02-20 22:35:16 +00:00
next.ServeHTTP(rw, r.WithContext(context.WithValue(r.Context(), loggedInKey, true)))
return
}
next.ServeHTTP(rw, r)
})
}
func (a *goBlog) checkLoginCookie(r *http.Request) bool {
ses, err := a.loginSessions.Get(r, "l")
2021-05-14 16:24:02 +00:00
if err == nil && ses != nil {
if login, ok := ses.Values["login"]; ok && login.(bool) {
return true
}
}
return false
}
func (a *goBlog) checkIsLogin(next http.Handler) http.Handler {
2020-12-15 16:40:14 +00:00
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if !a.checkLogin(rw, r) {
2020-12-15 16:40:14 +00:00
next.ServeHTTP(rw, r)
}
})
}
func (a *goBlog) checkLogin(w http.ResponseWriter, r *http.Request) bool {
2021-02-24 12:16:33 +00:00
if r.Method != http.MethodPost {
return false
}
if r.Header.Get(contentType) != contenttype.WWWForm {
2021-02-24 12:16:33 +00:00
return false
}
if r.FormValue("loginaction") != "login" {
return false
}
2021-02-28 07:57:15 +00:00
// Check credential
if !a.checkCredentials(r.FormValue("username"), r.FormValue("password"), r.FormValue("token")) {
a.serveError(w, r, "Incorrect credentials", http.StatusUnauthorized)
2021-02-28 07:57:15 +00:00
return true
}
// Prepare original request
2021-02-24 12:16:33 +00:00
loginbody, _ := base64.StdEncoding.DecodeString(r.FormValue("loginbody"))
req, _ := http.NewRequest(r.FormValue("loginmethod"), r.RequestURI, bytes.NewReader(loginbody))
// Copy original headers
loginheaders, _ := base64.StdEncoding.DecodeString(r.FormValue("loginheaders"))
var headers http.Header
_ = json.Unmarshal(loginheaders, &headers)
for k, v := range headers {
req.Header[k] = v
}
2021-02-28 07:57:15 +00:00
// Cookie
ses, err := a.loginSessions.Get(r, "l")
2021-02-28 07:57:15 +00:00
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
2021-02-28 07:57:15 +00:00
return true
2020-12-15 16:40:14 +00:00
}
2021-05-14 16:24:02 +00:00
ses.Values["login"] = true
cookie, err := a.loginSessions.SaveGetCookie(r, w, ses)
2021-05-14 16:24:02 +00:00
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
2021-05-14 16:24:02 +00:00
return true
}
req.AddCookie(cookie)
2021-02-24 12:16:33 +00:00
// Serve original request
a.d.ServeHTTP(w, req)
2021-02-24 12:16:33 +00:00
return true
2020-12-15 16:40:14 +00:00
}
// Need to set auth middleware!
func serveLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
}
func (a *goBlog) serveLogout(w http.ResponseWriter, r *http.Request) {
if ses, err := a.loginSessions.Get(r, "l"); err == nil && ses != nil {
_ = a.loginSessions.Delete(r, w, ses)
2021-05-14 16:24:02 +00:00
}
http.Redirect(w, r, "/", http.StatusFound)
}