From 88fa53fb9e2f45f47b33d5edef43e7338d5c4f03 Mon Sep 17 00:00:00 2001 From: René 'Necoro' Neumann Date: Thu, 17 Oct 2024 21:58:02 +0200 Subject: Introduce change password functionality --- pages/login.go | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) (limited to 'pages/login.go') diff --git a/pages/login.go b/pages/login.go index 84119e9..d433937 100644 --- a/pages/login.go +++ b/pages/login.go @@ -27,15 +27,24 @@ const ( loginQueryMarker = "next" ) +func setUserInContext(ctx context.Context, uid int32) (context.Context, error) { + u, err := Q.GetUserById(ctx, uid) + if err != nil { + return ctx, err + } + + u.Pwd = "" // don't carry pwd around + return context.WithValue(ctx, userContextKey{}, u), nil +} + func RequireAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s := session.From(r) if !s.IsNew() && s.Authenticated { - u, err := Q.GetUserById(r.Context(), s.UserID) + ctx, err := setUserInContext(r.Context(), s.UserID) if err == nil { // authenticated --> done - ctx := context.WithValue(r.Context(), userContextKey{}, u) next.ServeHTTP(w, r.WithContext(ctx)) return } @@ -53,10 +62,10 @@ func RequireAuth(next http.Handler) http.Handler { } 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"` - Errors []error `form:"-"` + Name string `form:"options=required,autofocus"` + Password string `form:"type=password;options=required"` + RememberMe bool `form:"type=checkbox;value=y;options=checked"` + form.FormErrors csrf.CsrfField } @@ -77,13 +86,17 @@ func Login() Page { return r } +func validatePwd(hash, pwd string) bool { + hashB := []byte(hash) + pwdB := []byte(pwd) + + return bcrypt.CompareHashAndPassword(hashB, pwdB) == nil +} + func checkLogin(ctx context.Context, user user) (bool, int32) { dbUser, err := Q.GetUserByName(ctx, user.Name) if err == nil { - hash := []byte(dbUser.Pwd) - pwd := []byte(user.Password) - - if bcrypt.CompareHashAndPassword(hash, pwd) != nil { + if !validatePwd(dbUser.Pwd, user.Password) { return false, 0 } } else if errors.Is(err, sql.ErrNoRows) { -- cgit v1.2.3-70-g09d2