added doc about the contextloader from hwsauth
48
HWSAuth.md
48
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) }}
|
||||
<h1>Hello, { user.Username }</h1>
|
||||
}
|
||||
```
|
||||
|
||||
**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(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user