lishwist/auth/register.go

45 lines
1018 B
Go

package auth
import (
"net/http"
"lishwist/db"
"lishwist/types"
"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")
if db.Exists("user:" + username) {
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
}
db.Set("user:"+username, types.UserData{
Username: username,
PassHash: hashedPasswordBytes,
})
http.Redirect(w, r, "/", http.StatusSeeOther)
}