diff --git a/internal/application.go b/internal/application.go index 30db8d4..f3ceca5 100644 --- a/internal/application.go +++ b/internal/application.go @@ -1,6 +1,7 @@ package internal import ( + "context" "fmt" "html/template" "net/http" @@ -93,28 +94,39 @@ type renderInfo struct { RedirectIfLoggedIn bool } +type ContextKey string + +const ( + ContextKeyLoggedInUser ContextKey = "com.mineshspc.logged_in_user" +) + type Info struct { - config config.Configuration + config config.Configuration + pageName string } -func (*Info) Title() string { - return "Home" +func (i *Info) Title() string { + return i.pageName } func (i *Info) HostedByHTML() template.HTML { return i.config.HostedByHTML } -func (*Info) PageName() partials.PageName { - return partials.PageNameHome +func (i *Info) PageName() partials.PageName { + return partials.PageName(strings.ToLower(i.pageName)) } func (i *Info) RegistrationEnabled() bool { return i.config.RegistrationEnabled } -func (*Info) Username() string { - return "username" +func (*Info) Username(ctx context.Context) string { + if loggedInUser, ok := ctx.Value(ContextKeyLoggedInUser).(*database.Teacher); ok { + return loggedInUser.Name + } else { + return "" + } } func (a *Application) Start() { @@ -127,10 +139,14 @@ func (a *Application) Start() { noArgs := func(r *http.Request) map[string]any { return nil } - base := Info{config: a.Config} - router.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { - templates.Base(&base, templates.Home(&base)).Render(r.Context(), w) + info := Info{config: a.Config, pageName: "Home"} + ctx := r.Context() + user, err := a.GetLoggedInTeacher(r) + if err == nil { + ctx = context.WithValue(ctx, ContextKeyLoggedInUser, user) + } + templates.Base(&info, templates.Home(&info)).Render(ctx, w) }) // Static pages diff --git a/internal/templates/partials/navbar.templ b/internal/templates/partials/navbar.templ index 80bf734..e881fb5 100644 --- a/internal/templates/partials/navbar.templ +++ b/internal/templates/partials/navbar.templ @@ -14,7 +14,7 @@ const ( type NavbarInfo interface { PageName() PageName RegistrationEnabled() bool - Username() string + Username(ctx context.Context) string // TODO make more things configurable? } @@ -106,8 +106,8 @@ templ Navbar(info NavbarInfo) {