diff --git a/authentication/auth.go b/authentication/auth.go index 017b97f..8fb75b0 100644 --- a/authentication/auth.go +++ b/authentication/auth.go @@ -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) diff --git a/htmx_route.go b/htmx_route.go index 752d196..8542a5c 100644 --- a/htmx_route.go +++ b/htmx_route.go @@ -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, diff --git a/page.go b/page.go index 0855287..82bc989 100644 --- a/page.go +++ b/page.go @@ -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), ) }