summaryrefslogtreecommitdiff
path: root/pkg/webui/login.go
blob: d004d82e0fda93fb9ac0094d4dc01f36ed224684 (plain)
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
package webui

import (
	"context"
	"fmt"
	"html/template"
	"net/http"
	"regexp"

	"git.adyxax.org/adyxax/tfstated/pkg/database"
	"git.adyxax.org/adyxax/tfstated/pkg/model"
)

var loginTemplate = template.Must(template.ParseFS(htmlFS, "html/base.html", "html/login.html"))

type loginPage struct {
	Forbidden bool
	Username  string
}

func handleLoginGET() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-store, no-cache")

		session := r.Context().Value(model.SessionContextKey{})
		if session != nil {
			http.Redirect(w, r, "/", http.StatusFound)
			return
		}

		render(w, loginTemplate, http.StatusOK, loginPage{})
	})
}

func handleLoginPOST(db *database.DB) http.Handler {
	var validUsername = regexp.MustCompile(`^[a-zA-Z]\w*$`)
	renderForbidden := func(w http.ResponseWriter, username string) {
		render(w, loginTemplate, http.StatusForbidden, loginPage{
			Forbidden: true,
			Username:  username,
		})
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			errorResponse(w, http.StatusBadRequest, err)
			return
		}
		username := r.FormValue("username")
		password := r.FormValue("password")

		if username == "" || password == "" { // the webui cannot issue this
			errorResponse(w, http.StatusBadRequest, fmt.Errorf("Forbidden"))
			return
		}
		if ok := validUsername.MatchString(username); !ok {
			renderForbidden(w, username)
			return
		}
		account, err := db.LoadAccountByUsername(username)
		if err != nil {
			errorResponse(w, http.StatusInternalServerError, err)
			return
		}
		if account == nil || !account.CheckPassword(password) {
			renderForbidden(w, username)
			return
		}
		if err := db.TouchAccount(account); err != nil {
			errorResponse(w, http.StatusInternalServerError, err)
			return
		}
		sessionId, err := db.CreateSession(account)
		if err != nil {
			errorResponse(w, http.StatusInternalServerError, err)
			return
		}
		http.SetCookie(w, &http.Cookie{
			Name:     cookieName,
			Value:    sessionId,
			Quoted:   false,
			Path:     "/",
			MaxAge:   8 * 3600, // 1 hour sessions
			HttpOnly: true,
			SameSite: http.SameSiteStrictMode,
			Secure:   true,
		})
		http.Redirect(w, r, "/", http.StatusFound)
	})
}

func loginMiddleware(db *database.DB) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Cache-Control", "no-store, no-cache")
			session := r.Context().Value(model.SessionContextKey{})
			if session == nil {
				http.Redirect(w, r, "/login", http.StatusFound)
				return
			}
			account, err := db.LoadAccountById(session.(*model.Session).AccountId)
			if err != nil {
				errorResponse(w, http.StatusInternalServerError, err)
				return
			}
			if account == nil {
				// this could happen if the account was deleted in the short
				// time between retrieving the session and here
				http.Redirect(w, r, "/login", http.StatusFound)
				return
			}
			ctx := context.WithValue(r.Context(), model.AccountContextKey{}, account)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}