lishwist/auth/register.go

55 lines
1.4 KiB
Go

package auth
import (
"log"
"net/http"
"lishwist/db"
"golang.org/x/crypto/bcrypt"
)
func (auth *AuthMiddleware) RegisterPost(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Couldn't parse form", http.StatusBadRequest)
return
}
username := r.Form.Get("username")
newPassword := r.Form.Get("newPassword")
confirmPassword := r.Form.Get("confirmPassword")
existingUser, _ := db.GetUserByName(username)
if existingUser != nil {
http.Error(w, "Username is taken", http.StatusBadRequest)
return
}
if newPassword != confirmPassword {
http.Error(w, "passwords didn't match", http.StatusBadRequest)
return
}
hashedPasswordBytes, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.MinCost)
if err != nil {
http.Error(w, "Something went wrong. Error code: Aang", http.StatusInternalServerError)
return
}
_, err = db.CreateUser(username, hashedPasswordBytes)
if err != nil {
http.Error(w, "Something went wrong. Error code: Ozai", http.StatusInternalServerError)
return
}
session, _ := auth.Store.Get(r, "lishwist_user")
session.Values["successful_registration"] = true
if err := session.Save(r, w); err != nil {
log.Println("Couldn't save session:", err)
http.Error(w, "Something went wrong. Error code: Zuko", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}