tfstated/pkg/webui/login.go
Julien Dessaux 3bb5e735c6
All checks were successful
main / main (push) Successful in 3m13s
main / deploy (push) Has been skipped
main / publish (push) Has been skipped
chore(webui): rewrite all the web session code
#60
2025-04-29 01:25:11 +02:00

119 lines
3.5 KiB
Go

package webui
import (
"context"
"fmt"
"html/template"
"log/slog"
"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"))
var validUsername = regexp.MustCompile(`^[a-zA-Z]\w*$`)
type loginPage struct {
Page *Page
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")
account := r.Context().Value(model.AccountContextKey{})
if account != nil {
http.Redirect(w, r, "/states", http.StatusFound)
return
}
render(w, loginTemplate, http.StatusOK, loginPage{
Page: makePage(r, &Page{Title: "Login", Section: "login"}),
})
})
}
func handleLoginPOST(db *database.DB) http.Handler {
renderForbidden := func(w http.ResponseWriter, r *http.Request, username string) {
render(w, loginTemplate, http.StatusForbidden, loginPage{
Page: makePage(r, &Page{Title: "Login", Section: "login"}),
Forbidden: true,
Username: username,
})
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
errorResponse(w, r, http.StatusBadRequest,
fmt.Errorf("failed to parse form: %w", err))
return
}
username := r.FormValue("username")
password := r.FormValue("password")
if username == "" || password == "" {
errorResponse(w, r, http.StatusBadRequest, nil)
return
}
if ok := validUsername.MatchString(username); !ok {
renderForbidden(w, r, username)
return
}
account, err := db.LoadAccountByUsername(username)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to load account by username %s: %w", username, err))
return
}
if account == nil || !account.CheckPassword(password) {
renderForbidden(w, r, username)
return
}
if err := db.TouchAccount(account); err != nil {
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to touch account %s: %w", username, err))
return
}
session := r.Context().Value(model.SessionContextKey{}).(*model.Session)
sessionId, err := db.MigrateSession(session, account)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to migrate session: %w", err))
return
}
setSessionCookie(w, sessionId)
if err := db.DeleteExpiredSessions(); err != nil {
slog.Error("failed to delete expired sessions after user login", "err", err, "accountId", account.Id)
}
http.Redirect(w, r, "/", http.StatusFound)
})
}
func loginMiddleware(db *database.DB, requireSession func(http.Handler) http.Handler) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return requireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store, no-cache")
session := r.Context().Value(model.SessionContextKey{}).(*model.Session)
if session.AccountId == nil {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
account, err := db.LoadAccountById(session.AccountId)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to load account by Id: %w", err))
return
}
if account == nil {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
ctx := context.WithValue(r.Context(), model.AccountContextKey{}, account)
next.ServeHTTP(w, r.WithContext(ctx))
}))
}
}