Add a logout button
This commit is contained in:
@@ -12,12 +12,6 @@ import (
|
||||
const sessionName = "session"
|
||||
const EmailKey = "email"
|
||||
const UserIdKey = "userId"
|
||||
const AuthContextKey = "authContext"
|
||||
|
||||
type AuthContext struct {
|
||||
Email string
|
||||
UserId int
|
||||
}
|
||||
|
||||
func SaveEmailAndUserIdToSessionStore(request *http.Request, writer http.ResponseWriter, store *sessions.CookieStore, email string, userId int) error {
|
||||
session, err := store.New(request, sessionName)
|
||||
|
||||
@@ -13,6 +13,13 @@ import (
|
||||
htmx "maragu.dev/gomponents-htmx"
|
||||
)
|
||||
|
||||
const AuthContextKey = "authContext"
|
||||
|
||||
type AuthContext struct {
|
||||
Email string
|
||||
UserId int
|
||||
}
|
||||
|
||||
type HtmxContext interface {
|
||||
Render(node gomponents.Node)
|
||||
SetError(err error)
|
||||
@@ -29,6 +36,7 @@ type HtmxContext interface {
|
||||
SetAllRoutes(routes []HtmxRoute)
|
||||
GetAllRoutes() []HtmxRoute
|
||||
GetQueryParams() []HtmxPathParam
|
||||
GetAuthContext() (bool, AuthContext)
|
||||
}
|
||||
|
||||
type HtmxContextImpl struct {
|
||||
@@ -40,6 +48,14 @@ type HtmxContextImpl struct {
|
||||
routes []HtmxRoute
|
||||
}
|
||||
|
||||
func (c *HtmxContextImpl) GetAuthContext() (bool, AuthContext) {
|
||||
authCtx := c.req.Context().Value(AuthContextKey)
|
||||
if authCtx == nil {
|
||||
return false, AuthContext{}
|
||||
}
|
||||
return true, authCtx.(AuthContext)
|
||||
}
|
||||
|
||||
func (c *HtmxContextImpl) GetQueryParams() []HtmxPathParam {
|
||||
// Extract query parameters from the current request URL and return them as
|
||||
// a deterministic list of HtmxPathParam. If a key has multiple values,
|
||||
|
||||
@@ -67,10 +67,24 @@ func AddLanguageSelectScript(metadata PageWebsiteMetaData) Node {
|
||||
}
|
||||
|
||||
func GetNav(c HtmxContext, metadata PageWebsiteMetaData) Node {
|
||||
// Create navigation items from metadata
|
||||
navItems := Map(metadata.NavItems, func(path ActivePath) Node {
|
||||
return CreateNavItem(c, path)
|
||||
})
|
||||
|
||||
// Check if user is authenticated and add logout button if so
|
||||
isAuthenticated, authCtx := c.GetAuthContext()
|
||||
if isAuthenticated {
|
||||
logoutButton := A(
|
||||
Href("/logout"),
|
||||
Text("Logout ("+authCtx.Email+")"),
|
||||
Class("logout-button"),
|
||||
)
|
||||
navItems = append(navItems, logoutButton)
|
||||
}
|
||||
|
||||
return Nav(Class("nav"), Aria("label", "Main Menu"),
|
||||
Map(metadata.NavItems, func(path ActivePath) Node {
|
||||
return CreateNavItem(c, path)
|
||||
}),
|
||||
Group(navItems),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user