From 9b52a88e971e70facc74778c133244f8a93b1f31 Mon Sep 17 00:00:00 2001 From: GrailFinder Date: Sun, 19 May 2024 07:15:20 +0300 Subject: Enha: avoid panic; check password at login --- internal/handlers/auth.go | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) (limited to 'internal/handlers/auth.go') diff --git a/internal/handlers/auth.go b/internal/handlers/auth.go index 0287960..e147efc 100644 --- a/internal/handlers/auth.go +++ b/internal/handlers/auth.go @@ -36,7 +36,7 @@ func (h *Handlers) HandleSignup(w http.ResponseWriter, r *http.Request) { abortWithError(w, msg) return } - // TODO: make sure username does not exists + // make sure username does not exists cleanName := utils.RemoveSpacesFromStr(username) hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // create user in db @@ -53,7 +53,7 @@ func (h *Handlers) HandleSignup(w http.ResponseWriter, r *http.Request) { abortWithError(w, msg) return } - // TODO: login user + // login user cookie, err := h.makeCookie(cleanName, r.RemoteAddr) if err != nil { h.log.Error("failed to login", "error", err) @@ -64,7 +64,8 @@ func (h *Handlers) HandleSignup(w http.ResponseWriter, r *http.Request) { // http.Redirect(w, r, "/", 302) tmpl, err := template.ParseGlob("components/*.html") if err != nil { - panic(err) + abortWithError(w, err.Error()) + return } tmpl.ExecuteTemplate(w, "main", newUser) } @@ -88,17 +89,33 @@ func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request) { cleanName := utils.RemoveSpacesFromStr(username) tmpl, err := template.ParseGlob("components/*.html") if err != nil { - panic(err) + abortWithError(w, err.Error()) + return } userScore, err := h.repo.DBUserScoreGet(cleanName) if err != nil { - h.log.Warn("got db err", "err", err) - tmpl.ExecuteTemplate(w, "main", nil) + h.log.Warn("failed to find user in db", "err", err) + abortWithError(w, err.Error()) + return + } + // check password + // hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) + // if err != nil { + // h.log.Warn("failed to gen pass hash", "err", err) + // abortWithError(w, err.Error()) + // return + // } + if err := bcrypt.CompareHashAndPassword( + []byte(userScore.Password), []byte(password), + ); err != nil { + h.log.Warn("wrong password", "err", err) + abortWithError(w, err.Error()) return } userScore.Actions, err = h.repo.DBActionList(cleanName) if err != nil { - panic(err) + abortWithError(w, err.Error()) + return } cookie, err := h.makeCookie(cleanName, r.RemoteAddr) if err != nil { @@ -107,7 +124,6 @@ func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request) { return } http.SetCookie(w, cookie) - // http.Redirect(w, r, "/", 302) tmpl.ExecuteTemplate(w, "main", userScore) } -- cgit v1.2.3