chore(webui): rewrite all the web session code
All checks were successful
main / main (push) Successful in 3m13s
main / deploy (push) Has been skipped
main / publish (push) Has been skipped

#60
This commit is contained in:
Julien Dessaux 2025-04-29 01:25:11 +02:00
parent 929657fd34
commit 3bb5e735c6
Signed by: adyxax
GPG key ID: F92E51B86E07177E
19 changed files with 173 additions and 123 deletions

View file

@ -29,7 +29,7 @@ func handleAccountsIdGET(db *database.DB) http.Handler {
errorResponse(w, r, http.StatusBadRequest, err)
return
}
account, err := db.LoadAccountById(accountId)
account, err := db.LoadAccountById(&accountId)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
return

View file

@ -30,7 +30,7 @@ func processAccountsIdResetPasswordPathValues(db *database.DB, w http.ResponseWr
errorResponse(w, r, http.StatusBadRequest, err)
return nil, false
}
account, err := db.LoadAccountById(accountId)
account, err := db.LoadAccountById(&accountId)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
return nil, false
@ -55,7 +55,7 @@ func handleAccountsIdResetPasswordGET(db *database.DB) http.Handler {
render(w, accountsIdResetPasswordTemplates, http.StatusOK,
AccountsIdResetPasswordPage{
Account: account,
Page: &Page{Title: "Password Reset", Section: "reset"},
Page: makePage(r, &Page{Title: "Password Reset", Section: "reset"}),
Token: r.PathValue("token"),
})
})
@ -80,7 +80,7 @@ func handleAccountsIdResetPasswordPOST(db *database.DB) http.Handler {
render(w, accountsIdResetPasswordTemplates, http.StatusOK,
AccountsIdResetPasswordPage{
Account: account,
Page: &Page{Title: "Password Reset", Section: "reset"},
Page: makePage(r, &Page{Title: "Password Reset", Section: "reset"}),
PasswordChanged: true,
})
})

View file

@ -15,7 +15,7 @@ func errorResponse(w http.ResponseWriter, r *http.Request, status int, err error
StatusText string
}
render(w, errorTemplates, status, &ErrorData{
Page: &Page{Title: "Error", Section: "error"},
Page: makePage(r, &Page{Title: "Error", Section: "error"}),
Err: err,
Status: status,
StatusText: http.StatusText(status),

View file

@ -55,6 +55,5 @@
</div>
<footer>
</footer>
<script type="module" src="/static/main.js"></script>
</body>
</html>

View file

@ -9,7 +9,7 @@ import (
)
type Page struct {
AccountId uuid.UUID
AccountId *uuid.UUID
IsAdmin bool
LightMode bool
Section string
@ -17,9 +17,12 @@ type Page struct {
}
func makePage(r *http.Request, page *Page) *Page {
account := r.Context().Value(model.AccountContextKey{}).(*model.Account)
page.AccountId = account.Id
page.IsAdmin = account.IsAdmin
accountCtx := r.Context().Value(model.AccountContextKey{})
if accountCtx != nil {
account := accountCtx.(*model.Account)
page.AccountId = &account.Id
page.IsAdmin = account.IsAdmin
}
settings := r.Context().Value(model.SettingsContextKey{}).(*model.Settings)
page.LightMode = settings.LightMode
return page

View file

@ -2,7 +2,7 @@ package webui
import (
"context"
"encoding/json"
"fmt"
"html/template"
"log/slog"
"net/http"
@ -26,29 +26,30 @@ 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 {
account := r.Context().Value(model.AccountContextKey{})
if account != nil {
http.Redirect(w, r, "/states", http.StatusFound)
return
}
render(w, loginTemplate, http.StatusOK, loginPage{
Page: &Page{Title: "Login", Section: "login"},
Page: makePage(r, &Page{Title: "Login", Section: "login"}),
})
})
}
func handleLoginPOST(db *database.DB) http.Handler {
renderForbidden := func(w http.ResponseWriter, username string) {
renderForbidden := func(w http.ResponseWriter, r *http.Request, username string) {
render(w, loginTemplate, http.StatusForbidden, loginPage{
Page: &Page{Title: "Login", Section: "login"},
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, err)
errorResponse(w, r, http.StatusBadRequest,
fmt.Errorf("failed to parse form: %w", err))
return
}
username := r.FormValue("username")
@ -59,37 +60,32 @@ func handleLoginPOST(db *database.DB) http.Handler {
return
}
if ok := validUsername.MatchString(username); !ok {
renderForbidden(w, username)
renderForbidden(w, r, username)
return
}
account, err := db.LoadAccountByUsername(username)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
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, username)
renderForbidden(w, r, username)
return
}
if err := db.TouchAccount(account); err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to touch account %s: %w", username, err))
return
}
sessionId, err := db.CreateSession(account)
session := r.Context().Value(model.SessionContextKey{}).(*model.Session)
sessionId, err := db.MigrateSession(session, account)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to migrate session: %w", err))
return
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: sessionId,
Quoted: false,
Path: "/",
MaxAge: 12 * 3600, // 12 hours sessions
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Secure: true,
})
setSessionCookie(w, sessionId)
if err := db.DeleteExpiredSessions(); err != nil {
slog.Error("failed to delete expired sessions after user login", "err", err, "accountId", account.Id)
}
@ -97,32 +93,26 @@ func handleLoginPOST(db *database.DB) http.Handler {
})
}
func loginMiddleware(db *database.DB, processSession func(http.Handler) http.Handler) func(http.Handler) http.Handler {
func loginMiddleware(db *database.DB, requireSession func(http.Handler) http.Handler) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return processSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
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{})
if session == nil {
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.(*model.Session).AccountId)
account, err := db.LoadAccountById(session.AccountId)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to load account by Id: %w", 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)
var settings model.Settings
if err := json.Unmarshal(account.Settings, &settings); err != nil {
slog.Error("failed to unmarshal account settings", "err", err, "accountId", account.Id)
}
ctx = context.WithValue(ctx, model.SettingsContextKey{}, &settings)
next.ServeHTTP(w, r.WithContext(ctx))
}))
}

View file

@ -1,6 +1,7 @@
package webui
import (
"fmt"
"html/template"
"net/http"
@ -12,18 +13,19 @@ var logoutTemplate = template.Must(template.ParseFS(htmlFS, "html/base.html", "h
func handleLogoutGET(db *database.DB) http.Handler {
type logoutPage struct {
Page
Page *Page
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value(model.SessionContextKey{})
err := db.DeleteSession(session.(*model.Session))
session := r.Context().Value(model.SessionContextKey{}).(*model.Session)
sessionId, err := db.MigrateSession(session, nil)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to migrate session: %w", err))
return
}
unsetSesssionCookie(w)
setSessionCookie(w, sessionId)
render(w, logoutTemplate, http.StatusOK, logoutPage{
Page: Page{Title: "Logout", Section: "login"},
Page: makePage(r, &Page{Title: "Logout", Section: "login"}),
})
})
}

View file

@ -10,17 +10,17 @@ func addRoutes(
mux *http.ServeMux,
db *database.DB,
) {
processSession := sessionsMiddleware(db)
requireLogin := loginMiddleware(db, processSession)
requireSession := sessionsMiddleware(db)
requireLogin := loginMiddleware(db, requireSession)
requireAdmin := adminMiddleware(db, requireLogin)
mux.Handle("GET /accounts", requireLogin(handleAccountsGET(db)))
mux.Handle("GET /accounts/{id}", requireLogin(handleAccountsIdGET(db)))
mux.Handle("GET /accounts/{id}/reset/{token}", handleAccountsIdResetPasswordGET(db))
mux.Handle("POST /accounts/{id}/reset/{token}", handleAccountsIdResetPasswordPOST(db))
mux.Handle("GET /accounts/{id}/reset/{token}", requireSession(handleAccountsIdResetPasswordGET(db)))
mux.Handle("POST /accounts/{id}/reset/{token}", requireSession(handleAccountsIdResetPasswordPOST(db)))
mux.Handle("POST /accounts", requireAdmin(handleAccountsPOST(db)))
mux.Handle("GET /healthz", handleHealthz())
mux.Handle("GET /login", processSession(handleLoginGET()))
mux.Handle("POST /login", processSession(handleLoginPOST(db)))
mux.Handle("GET /login", requireSession(handleLoginGET()))
mux.Handle("POST /login", requireSession(handleLoginPOST(db)))
mux.Handle("GET /logout", requireLogin(handleLogoutGET(db)))
mux.Handle("GET /settings", requireLogin(handleSettingsGET(db)))
mux.Handle("POST /settings", requireLogin(handleSettingsPOST(db)))
@ -30,5 +30,5 @@ func addRoutes(
mux.Handle("POST /states/{id}", requireLogin(handleStatesIdPOST(db)))
mux.Handle("GET /static/", cache(http.FileServer(http.FS(staticFS))))
mux.Handle("GET /versions/{id}", requireLogin(handleVersionsGET(db)))
mux.Handle("GET /", requireLogin(handleIndexGET()))
mux.Handle("GET /", requireSession(handleIndexGET()))
}

View file

@ -2,8 +2,10 @@ package webui
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"git.adyxax.org/adyxax/tfstated/pkg/database"
@ -17,49 +19,59 @@ func sessionsMiddleware(db *database.DB) func(http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(cookieName)
if err != nil && !errors.Is(err, http.ErrNoCookie) {
errorResponse(w, r, http.StatusInternalServerError, fmt.Errorf("failed to get request cookie \"%s\": %w", cookieName, err))
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to get session cookie from request: %w", err))
return
}
if err == nil {
if len(cookie.Value) != 43 {
unsetSesssionCookie(w)
} else {
if len(cookie.Value) == 43 {
session, err := db.LoadSessionById(cookie.Value)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to load session by ID: %w", err))
return
}
if session == nil {
unsetSesssionCookie(w)
} else if session.IsExpired() {
unsetSesssionCookie(w)
if err := db.DeleteSession(session); err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
if session != nil {
if session.IsExpired() {
if err := db.DeleteSession(session); err != nil {
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to delete session: %w", err))
return
}
} else {
ctx := context.WithValue(r.Context(), model.SessionContextKey{}, session)
var settings model.Settings
if err := json.Unmarshal(session.Settings, &settings); err != nil {
slog.Error("failed to unmarshal session settings", "err", err)
}
ctx = context.WithValue(ctx, model.SettingsContextKey{}, &settings)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
} else {
if err := db.TouchSession(cookie.Value); err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
return
}
ctx := context.WithValue(r.Context(), model.SessionContextKey{}, session)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
}
}
next.ServeHTTP(w, r)
sessionId, err := db.CreateSession(nil, nil)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError,
fmt.Errorf("failed to create session: %w", err))
return
}
setSessionCookie(w, sessionId)
var settings model.Settings
ctx := context.WithValue(r.Context(), model.SettingsContextKey{}, &settings)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func unsetSesssionCookie(w http.ResponseWriter) {
func setSessionCookie(w http.ResponseWriter, sessionId string) {
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: "",
Value: sessionId,
Quoted: false,
Path: "/",
MaxAge: 0, // remove invalid cookie
MaxAge: 12 * 3600, // 12 hours sessions
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Secure: true,

View file

@ -1,6 +1,7 @@
package webui
import (
"context"
"html/template"
"net/http"
@ -41,8 +42,8 @@ func handleSettingsPOST(db *database.DB) http.Handler {
errorResponse(w, r, http.StatusInternalServerError, err)
return
}
page := makePage(r, &Page{Title: "Settings", Section: "settings"})
page.LightMode = settings.LightMode
ctx := context.WithValue(r.Context(), model.SettingsContextKey{}, &settings)
page := makePage(r.WithContext(ctx), &Page{Title: "Settings", Section: "settings"})
render(w, settingsTemplates, http.StatusOK, SettingsPage{
Page: page,
Settings: &settings,

View file

@ -39,7 +39,7 @@ func handleVersionsGET(db *database.DB) http.Handler {
errorResponse(w, r, http.StatusInternalServerError, err)
return
}
account, err := db.LoadAccountById(version.AccountId)
account, err := db.LoadAccountById(&version.AccountId)
if err != nil {
errorResponse(w, r, http.StatusInternalServerError, err)
return