added doc about the contextloader from hwsauth

2026-01-11 23:43:35 +11:00
parent be3f7f4d32
commit d556f3eaca

@@ -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) }}
<h1>Hello, { user.Username }</h1>
}
```
**Note**: The user will be `nil` if not authenticated, so check for nil in non-protected routes.
## Core Features ## Core Features
### Middleware ### Middleware
@@ -724,3 +771,4 @@ func changePasswordHandler(