From c005016cb23a03231275b661b76816a0c40af8c6 Mon Sep 17 00:00:00 2001 From: grumbulon Date: Thu, 5 Jan 2023 19:15:15 -0500 Subject: [PATCH] adding error returns or else bad things happen and adding max cookie age of 1 hr --- internal/api/auth.go | 13 ++++++++++++- internal/api/users.go | 4 ++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/internal/api/auth.go b/internal/api/auth.go index 7b55619..193f3ca 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -25,8 +25,16 @@ func Login(w http.ResponseWriter, r *http.Request) { password := r.Form.Get("password") + if username == "" { + http.Error(w, "No username provided", http.StatusInternalServerError) // this should prob be handled by the frontend + + return + } + if password == "" { http.Error(w, "No password provided", http.StatusInternalServerError) // this should prob be handled by the frontend + + return } db, ok := r.Context().Value(keyPrincipalContextID).(*gorm.DB) @@ -37,11 +45,13 @@ func Login(w http.ResponseWriter, r *http.Request) { } db.Where("username = ?", username).First(&result) + if result.Username == "" { http.Error(w, "login failed", http.StatusUnauthorized) return } + err = bcrypt.CompareHashAndPassword([]byte(result.HashedPassword), []byte(password)) if err != nil { @@ -54,7 +64,8 @@ func Login(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ HttpOnly: true, - Expires: time.Now().Add(7 * 24 * time.Hour), + Expires: time.Now().Add(1 * time.Hour), + MaxAge: 3600, SameSite: http.SameSiteLaxMode, // Uncomment below for HTTPS: // Secure: true, diff --git a/internal/api/users.go b/internal/api/users.go index 51b6b6d..6ecebc8 100644 --- a/internal/api/users.go +++ b/internal/api/users.go @@ -38,6 +38,8 @@ func NewUser(w http.ResponseWriter, r *http.Request) { if password == "" { http.Error(w, "No password entered", http.StatusInternalServerError) + + return } db.Where("username = ?", username).First(&result) @@ -51,6 +53,8 @@ func NewUser(w http.ResponseWriter, r *http.Request) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) + + return } db.Create(&internal.User{Username: username, HashedPassword: string(hashedPassword)})