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"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/dgrijalva/jwt-go"
|
2021-02-28 07:57:15 +00:00
|
|
|
"github.com/pquerna/otp/totp"
|
2020-12-15 16:40:14 +00:00
|
|
|
)
|
|
|
|
|
2021-02-28 07:57:15 +00:00
|
|
|
func checkCredentials(username, password, totpPasscode string) bool {
|
|
|
|
return username == appConfig.User.Nick &&
|
|
|
|
password == appConfig.User.Password &&
|
|
|
|
(appConfig.User.TOTP == "" || totp.Validate(totpPasscode, appConfig.User.TOTP))
|
2020-12-15 16:40:14 +00:00
|
|
|
}
|
|
|
|
|
2021-02-28 07:57:15 +00:00
|
|
|
func checkUsernameTOTP(username string, totp bool) bool {
|
|
|
|
return username == appConfig.User.Nick && totp == (appConfig.User.TOTP != "")
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkAppPasswords(username, password string) bool {
|
|
|
|
for _, apw := range appConfig.User.AppPasswords {
|
|
|
|
if apw.Username == username && apw.Password == password {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2021-02-06 21:53:56 +00:00
|
|
|
}
|
|
|
|
|
2020-12-15 16:40:14 +00:00
|
|
|
func jwtKey() []byte {
|
|
|
|
return []byte(appConfig.Server.JWTSecret)
|
|
|
|
}
|
|
|
|
|
|
|
|
func authMiddleware(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2021-02-20 22:35:16 +00:00
|
|
|
// Check if already logged in
|
|
|
|
if loggedIn, ok := r.Context().Value(loggedInKey).(bool); ok && loggedIn {
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
2021-02-28 07:57:15 +00:00
|
|
|
// 1. Check BasicAuth (just for app passwords)
|
|
|
|
if username, password, ok := r.BasicAuth(); ok && checkAppPasswords(username, password) {
|
2021-02-06 21:53:56 +00:00
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// 2. Check JWT
|
2021-02-20 22:35:16 +00:00
|
|
|
if checkAuthToken(r) {
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
2020-12-15 16:40:14 +00:00
|
|
|
}
|
2021-02-06 21:53:56 +00:00
|
|
|
// 3. Show login form
|
2021-03-06 18:29:15 +00:00
|
|
|
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())
|
|
|
|
}
|
2021-02-20 22:35:16 +00:00
|
|
|
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),
|
2021-02-28 07:57:15 +00:00
|
|
|
"totp": appConfig.User.TOTP != "",
|
2020-12-15 16:40:14 +00:00
|
|
|
},
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-02-20 22:35:16 +00:00
|
|
|
func checkAuthToken(r *http.Request) bool {
|
|
|
|
if tokenCookie, err := r.Cookie("token"); err == nil {
|
|
|
|
claims := &authClaims{}
|
|
|
|
if tkn, err := jwt.ParseWithClaims(tokenCookie.Value, claims, func(t *jwt.Token) (interface{}, error) {
|
|
|
|
return jwtKey(), nil
|
|
|
|
}); err == nil && tkn.Valid &&
|
|
|
|
claims.TokenType == "login" &&
|
2021-02-28 07:57:15 +00:00
|
|
|
checkUsernameTOTP(claims.Username, claims.TOTP) {
|
2021-02-20 22:35:16 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
const loggedInKey requestContextKey = "loggedIn"
|
|
|
|
|
|
|
|
func checkLoggedIn(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
if checkAuthToken(r) {
|
|
|
|
next.ServeHTTP(rw, r.WithContext(context.WithValue(r.Context(), loggedInKey, true)))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
next.ServeHTTP(rw, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-12-15 16:40:14 +00:00
|
|
|
func checkIsLogin(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
if !checkLogin(rw, r) {
|
|
|
|
next.ServeHTTP(rw, r)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func 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) != contentTypeWWWForm {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if r.FormValue("loginaction") != "login" {
|
|
|
|
return false
|
|
|
|
}
|
2021-02-28 07:57:15 +00:00
|
|
|
// Check credential
|
|
|
|
if !checkCredentials(r.FormValue("username"), r.FormValue("password"), r.FormValue("token")) {
|
|
|
|
serveError(w, r, "Incorrect credentials", http.StatusUnauthorized)
|
|
|
|
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
|
|
|
|
tokenCookie, err := createTokenCookie()
|
|
|
|
if err != nil {
|
|
|
|
serveError(w, r, err.Error(), http.StatusInternalServerError)
|
|
|
|
return true
|
2020-12-15 16:40:14 +00:00
|
|
|
}
|
2021-02-28 07:57:15 +00:00
|
|
|
req.AddCookie(tokenCookie)
|
|
|
|
http.SetCookie(w, tokenCookie)
|
2021-02-24 12:16:33 +00:00
|
|
|
// Serve original request
|
|
|
|
d.ServeHTTP(w, req)
|
|
|
|
return true
|
2020-12-15 16:40:14 +00:00
|
|
|
}
|
|
|
|
|
2021-02-06 21:53:56 +00:00
|
|
|
type authClaims struct {
|
|
|
|
*jwt.StandardClaims
|
|
|
|
TokenType string
|
|
|
|
Username string
|
2021-02-28 07:57:15 +00:00
|
|
|
TOTP bool
|
2021-02-06 21:53:56 +00:00
|
|
|
}
|
|
|
|
|
2021-02-28 07:57:15 +00:00
|
|
|
func createTokenCookie() (*http.Cookie, error) {
|
2020-12-15 16:40:14 +00:00
|
|
|
expiration := time.Now().Add(7 * 24 * time.Hour)
|
2021-02-06 21:53:56 +00:00
|
|
|
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, &authClaims{
|
|
|
|
&jwt.StandardClaims{ExpiresAt: expiration.Unix()},
|
|
|
|
"login",
|
2021-02-28 07:57:15 +00:00
|
|
|
appConfig.User.Nick,
|
|
|
|
appConfig.User.TOTP != "",
|
2021-02-06 21:53:56 +00:00
|
|
|
}).SignedString(jwtKey())
|
2020-12-15 16:40:14 +00:00
|
|
|
if err != nil {
|
2021-01-23 16:24:47 +00:00
|
|
|
return nil, err
|
2020-12-15 16:40:14 +00:00
|
|
|
}
|
2021-01-23 16:24:47 +00:00
|
|
|
return &http.Cookie{
|
2020-12-15 16:40:14 +00:00
|
|
|
Name: "token",
|
|
|
|
Value: tokenString,
|
|
|
|
Expires: expiration,
|
2021-02-20 21:45:38 +00:00
|
|
|
Secure: httpsConfigured(),
|
2020-12-15 16:40:14 +00:00
|
|
|
HttpOnly: true,
|
2021-02-20 21:45:38 +00:00
|
|
|
SameSite: http.SameSiteLaxMode,
|
2021-01-23 16:24:47 +00:00
|
|
|
}, nil
|
2020-12-15 16:40:14 +00:00
|
|
|
}
|
2021-02-24 15:01:10 +00:00
|
|
|
|
|
|
|
// Need to set auth middleware!
|
|
|
|
func serveLogin(w http.ResponseWriter, r *http.Request) {
|
|
|
|
http.Redirect(w, r, "/", http.StatusFound)
|
|
|
|
}
|
|
|
|
|
|
|
|
func serveLogout(w http.ResponseWriter, r *http.Request) {
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
|
|
Name: "token",
|
|
|
|
MaxAge: -1,
|
|
|
|
Secure: httpsConfigured(),
|
|
|
|
HttpOnly: true,
|
|
|
|
SameSite: http.SameSiteLaxMode,
|
|
|
|
})
|
|
|
|
http.Redirect(w, r, "/", http.StatusFound)
|
|
|
|
}
|