check more errors
Marco Andronaco andronacomarco@gmail.com
Thu, 24 Oct 2024 21:01:45 +0200
3 files changed,
27 insertions(+),
11 deletions(-)
M
src/app/functions.go
→
src/app/functions.go
@@ -34,6 +34,11 @@ err = db.Model(&User{}).Where("upper(username) == upper(?) AND id != ?", username, excluding).First(&user).Error
return } +func getUserByEmail(email string, excluding uint) (user User, err error) { + err = db.Model(&User{}).Where("upper(email) == upper(?) AND id != ?", email, excluding).First(&user).Error + return +} + func sanitizeUsername(username string) (string, error) { if !validUsername.MatchString(username) || len(username) < minUsernameLength || len(username) > maxUsernameLength { return "", errors.New("invalid username")
M
src/app/handlers.go
→
src/app/handlers.go
@@ -60,6 +60,12 @@ showError(w, "This username is already registered.", http.StatusConflict)
return } + _, err = getUserByEmail(email, 0) + if err == nil { + showError(w, "This email is already registered.", http.StatusConflict) + return + } + hashedPassword, salt, err := g.HashPassword(r.FormValue("password")) if err != nil { showError(w, "Invalid password.", http.StatusBadRequest)@@ -73,9 +79,9 @@ PasswordHash: hashedPassword,
Salt: salt, } - db.Create(&user) - if user.ID == 0 { - showError(w, "This email is already registered.", http.StatusConflict) + err = db.Create(&user).Error + if err != nil { + showError(w, "Could not create user.", http.StatusInternalServerError) return }@@ -91,7 +97,7 @@
user, err := getUserByName(username, 0) if err != nil || !g.CheckPassword(password, user.Salt, user.PasswordHash) { - showError(w, "Invalid credentials", http.StatusUnauthorized) + showError(w, "Invalid credentials.", http.StatusUnauthorized) return }@@ -108,9 +114,8 @@ func postResetPasswordHandler(w http.ResponseWriter, r *http.Request) {
emailInput := r.FormValue("email") var user User - db.Where("email = ?", emailInput).First(&user) - - if user.ID == 0 { + err := db.Where("email = ?", emailInput).First(&user).Error + if err != nil { http.Redirect(w, r, "/login", http.StatusFound) return }@@ -148,7 +153,10 @@ return
} var user User - db.First(&user, *userID) + err = db.First(&user, *userID).Error + if err != nil { + showError(w, "Could not get user.", http.StatusInternalServerError) + } password := r.FormValue("password")@@ -160,7 +168,10 @@ }
user.PasswordHash = hashedPassword user.Salt = salt - db.Save(&user) + err = db.Save(&user).Error + if err != nil { + showError(w, "Could not save user.", http.StatusInternalServerError) + } ks.Delete(token) http.Redirect(w, r, "/login", http.StatusFound)
M
templates/error.tmpl
→
templates/error.tmpl
@@ -1,8 +1,8 @@
{{ extends "base.tmpl" }} -{{define "title" -}}Error - {{end}} +{{define "title" -}}Error {{.Status}} - {{end}} {{define "content" -}} - <h1>{{.Status}}</h1> + <h1>Error {{.Status}}</h1> <p>{{.Text}}</p> {{end}}