From d556f3eaca1b59be243c4c88ca2251b31b5d7690 Mon Sep 17 00:00:00 2001 From: Haelnorr Date: Sun, 11 Jan 2026 23:43:35 +1100 Subject: [PATCH] added doc about the contextloader from hwsauth --- HWSAuth.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/HWSAuth.md b/HWSAuth.md index e1281da..737dcc3 100644 --- a/HWSAuth.md +++ b/HWSAuth.md @@ -144,6 +144,53 @@ if err != nil { } ``` +### 5. (Optional) Global Context Loader + +For accessing the current user across your application (especially useful in templates), you can create a global `ContextLoader`: + +```go +package contexts + +import ( + "yourapp/internal/models" + "git.haelnorr.com/h/golib/hwsauth" +) + +// Global variable for accessing current user from context +var CurrentUser hwsauth.ContextLoader[*models.User] +``` + +Then in your auth setup, assign the authenticator's `CurrentModel` method: + +```go +func setupAuth(...) (*hwsauth.Authenticator[*User, bun.Tx], error) { + // ... create authenticator ... + + // Set up global context loader + contexts.CurrentUser = auth.CurrentModel + + return auth, nil +} +``` + +Now you can access the current user anywhere in your application: + +```go +// In handlers +func profileHandler(w http.ResponseWriter, r *http.Request) { + user := contexts.CurrentUser(r.Context()) + // use user... +} + +// In templates (templ example) +templ Profile() { + {{ user := contexts.CurrentUser(ctx) }} +

Hello, { user.Username }

+} +``` + +**Note**: The user will be `nil` if not authenticated, so check for nil in non-protected routes. + ## Core Features ### Middleware @@ -724,3 +771,4 @@ func changePasswordHandler( +