lishwist/auth/register.go

115 lines
3.0 KiB
Go

package auth
import (
"log"
"net/http"
"lishwist/db"
"lishwist/templates"
"golang.org/x/crypto/bcrypt"
)
type RegisterProps struct {
GeneralError string
Username templates.InputProps
Password templates.InputProps
ConfirmPassword templates.InputProps
}
func NewRegisterProps() RegisterProps {
return RegisterProps{
GeneralError: "",
Username: templates.InputProps{
Name: "username",
Required: true,
},
Password: templates.InputProps{
Type: "password",
Name: "newPassword",
Required: true,
MinLength: 5,
},
ConfirmPassword: templates.InputProps{
Type: "password",
Name: "confirmPassword",
Required: true,
},
}
}
func (auth *AuthMiddleware) Register(w http.ResponseWriter, r *http.Request) {
props := NewRegisterProps()
session, _ := auth.Store.Get(r, "lishwist_user")
if flashes := session.Flashes("register_props"); len(flashes) > 0 {
flashProps, _ := flashes[0].(*RegisterProps)
props.Username.Value = flashProps.Username.Value
props.GeneralError = flashProps.GeneralError
props.Username.Error = flashProps.Username.Error
props.ConfirmPassword.Error = flashProps.ConfirmPassword.Error
}
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
}
templates.Execute(w, "register.gotmpl", props)
}
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")
props := NewRegisterProps()
props.Username.Value = username
props.Password.Value = newPassword
props.ConfirmPassword.Value = confirmPassword
existingUser, _ := db.GetUserByName(username)
if existingUser != nil {
props.Username.Error = "Username is taken"
auth.RedirectWithFlash(w, r, "/register", "register_props", &props)
return
}
if newPassword != confirmPassword {
props.ConfirmPassword.Error = "Password didn't match"
auth.RedirectWithFlash(w, r, "/register", "register_props", &props)
return
}
hashedPasswordBytes, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.MinCost)
if err != nil {
props.GeneralError = "Something went wrong. Error code: Aang"
auth.RedirectWithFlash(w, r, "/register", "register_props", &props)
return
}
_, err = db.CreateUser(username, hashedPasswordBytes)
if err != nil {
props.GeneralError = "Something went wrong. Error code: Ozai"
auth.RedirectWithFlash(w, r, "/register", "register_props", &props)
return
}
session, _ := auth.Store.Get(r, "lishwist_user")
session.AddFlash(true, "successful_registration")
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)
}