From 789d21034e526a03d3e91d5d284a4888be938340 Mon Sep 17 00:00:00 2001 From: René 'Necoro' Neumann Date: Thu, 17 Oct 2024 00:43:31 +0200 Subject: Handle login routing at login page --- pages/login.go | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) (limited to 'pages/login.go') diff --git a/pages/login.go b/pages/login.go index fb7859a..9d8f686 100644 --- a/pages/login.go +++ b/pages/login.go @@ -11,11 +11,16 @@ import ( "net/http" "net/url" + "github.com/go-chi/chi/v5" "golang.org/x/crypto/bcrypt" ) type userContextKey struct{} +func userId(r *http.Request) int32 { + return r.Context().Value(userContextKey{}).(int32) +} + const ( sessionDuration = 86400 * 7 // 7 days loginQueryMarker = "next" @@ -46,7 +51,7 @@ func RequireAuth(next http.Handler) http.Handler { }) } -type User struct { +type user struct { Name string `form:"options=required,autofocus"` Password string `form:"type=password;options=required"` RememberMe bool `form:"type=checkbox;value=y;options=checked"` @@ -54,26 +59,24 @@ type User struct { csrf.Csrf } -func showLoginPage(w http.ResponseWriter, u User) { - showTemplate(w, "login", u) -} +func Login() Page { + r := chi.NewRouter() -func Login() http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + r.Get("/", func(w http.ResponseWriter, r *http.Request) { if session.From(r).Authenticated { http.Redirect(w, r, "/", http.StatusFound) } - u := User{} + u := user{} u.SetCsrfField(r) showLoginPage(w, u) - } -} + }) -func userId(r *http.Request) int32 { - return r.Context().Value(userContextKey{}).(int32) + r.Post("/", handleLogin) + + return r } -func checkLogin(ctx context.Context, user User) (bool, int32) { +func checkLogin(ctx context.Context, user user) (bool, int32) { dbUser, err := Q.GetUserByName(ctx, user.Name) if err == nil { hash := []byte(dbUser.Pwd) @@ -91,8 +94,8 @@ func checkLogin(ctx context.Context, user User) (bool, int32) { return true, dbUser.ID } -func HandleLogin(w http.ResponseWriter, r *http.Request) { - u := User{} +func handleLogin(w http.ResponseWriter, r *http.Request) { + u := user{} form.Parse(r, &u) ok, userId := checkLogin(r.Context(), u) @@ -121,3 +124,7 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) { } http.Redirect(w, r, next, http.StatusFound) } + +func showLoginPage(w http.ResponseWriter, u user) { + showTemplate(w, "login", u) +} -- cgit v1.2.3-70-g09d2