From 6d6aff50b3e0092cd7bf6780360ee87e82a075d2 Mon Sep 17 00:00:00 2001 From: max Date: Wed, 14 Feb 2024 13:20:35 -0600 Subject: [PATCH] Only show logout (now CSRF protected) if user is authenticated, include relevant authentication logic in GET controllers (this should be moved to middleware) --- controllers/get.go | 58 ++++++++++++++++++++++++++++++++------------- templates/base.html | 15 ++++++++++++ 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/controllers/get.go b/controllers/get.go index fe708b0..cfb576d 100644 --- a/controllers/get.go +++ b/controllers/get.go @@ -2,6 +2,7 @@ package controllers import ( "GoWeb/app" + "GoWeb/models" "GoWeb/security" "GoWeb/templating" "net/http" @@ -12,22 +13,11 @@ type Get struct { App *app.App } -func (g *Get) ShowHome(w http.ResponseWriter, _ *http.Request) { +func (g *Get) ShowHome(w http.ResponseWriter, r *http.Request) { type dataStruct struct { - CsrfToken string - Test string - } - - data := dataStruct{ - Test: "Hello World!", - } - - templating.RenderTemplate(w, "templates/pages/home.html", data) -} - -func (g *Get) ShowRegister(w http.ResponseWriter, r *http.Request) { - type dataStruct struct { - CsrfToken string + CsrfToken string + IsAuthenticated bool + Test string } CsrfToken, err := security.GenerateCsrfToken(w, r) @@ -35,8 +25,41 @@ func (g *Get) ShowRegister(w http.ResponseWriter, r *http.Request) { return } + isAuthenticated := true + user, err := models.CurrentUser(g.App, r) + if err != nil || user.Id == 0 { + isAuthenticated = false + } + data := dataStruct{ - CsrfToken: CsrfToken, + CsrfToken: CsrfToken, + Test: "Hello World!", + IsAuthenticated: isAuthenticated, + } + + templating.RenderTemplate(w, "templates/pages/home.html", data) +} + +func (g *Get) ShowRegister(w http.ResponseWriter, r *http.Request) { + type dataStruct struct { + CsrfToken string + IsAuthenticated bool + } + + CsrfToken, err := security.GenerateCsrfToken(w, r) + if err != nil { + return + } + + isAuthenticated := true + user, err := models.CurrentUser(g.App, r) + if err != nil || user.Id == 0 { + isAuthenticated = false + } + + data := dataStruct{ + CsrfToken: CsrfToken, + IsAuthenticated: isAuthenticated, } templating.RenderTemplate(w, "templates/pages/register.html", data) @@ -44,7 +67,8 @@ func (g *Get) ShowRegister(w http.ResponseWriter, r *http.Request) { func (g *Get) ShowLogin(w http.ResponseWriter, r *http.Request) { type dataStruct struct { - CsrfToken string + CsrfToken string + IsAuthenticated bool } CsrfToken, err := security.GenerateCsrfToken(w, r) diff --git a/templates/base.html b/templates/base.html index 7ad57b9..6191c93 100644 --- a/templates/base.html +++ b/templates/base.html @@ -6,6 +6,21 @@ + {{ template "content" . }}