refactor to improve database operability in hwsauth

This commit is contained in:
2026-01-11 23:00:50 +11:00
parent ae4094d426
commit 4c5af63ea2
17 changed files with 582 additions and 96 deletions

View File

@@ -7,8 +7,14 @@ import (
"git.haelnorr.com/h/golib/hws"
)
// Checks if the model is set in the context and shows 401 page if not logged in
func (auth *Authenticator[T]) LoginReq(next http.Handler) http.Handler {
// LoginReq returns a middleware that requires the user to be authenticated.
// If the user is not authenticated, it returns a 401 Unauthorized error page.
//
// Example:
//
// protectedHandler := auth.LoginReq(http.HandlerFunc(dashboardHandler))
// server.AddRoute("GET", "/dashboard", protectedHandler)
func (auth *Authenticator[T, TX]) LoginReq(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, ok := getAuthorizedModel[T](r.Context())
if !ok {
@@ -36,9 +42,14 @@ func (auth *Authenticator[T]) LoginReq(next http.Handler) http.Handler {
})
}
// Checks if the model is set in the context and redirects them to the landing page if
// they are logged in
func (auth *Authenticator[T]) LogoutReq(next http.Handler) http.Handler {
// LogoutReq returns a middleware that redirects authenticated users to the landing page.
// Use this for login and registration pages to prevent logged-in users from accessing them.
//
// Example:
//
// loginPageHandler := auth.LogoutReq(http.HandlerFunc(showLoginPage))
// server.AddRoute("GET", "/login", loginPageHandler)
func (auth *Authenticator[T, TX]) LogoutReq(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, ok := getAuthorizedModel[T](r.Context())
if ok {
@@ -49,10 +60,17 @@ func (auth *Authenticator[T]) LogoutReq(next http.Handler) http.Handler {
})
}
// FreshReq protects a route from access if the auth token is not fresh.
// A status code of 444 will be written to the header and the request will be terminated.
// As an example, this can be used on the client to show a confirm password dialog to refresh their login
func (auth *Authenticator[T]) FreshReq(next http.Handler) http.Handler {
// FreshReq returns a middleware that requires a fresh authentication token.
// If the token is not fresh (recently issued), it returns a 444 status code.
// Use this for sensitive operations like password changes or account deletions.
//
// Example:
//
// changePasswordHandler := auth.FreshReq(http.HandlerFunc(handlePasswordChange))
// server.AddRoute("POST", "/change-password", changePasswordHandler)
//
// The 444 status code can be used by the client to prompt for re-authentication.
func (auth *Authenticator[T, TX]) FreshReq(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
model, ok := getAuthorizedModel[T](r.Context())
if !ok {