lishwist/http/routing/register.go

74 lines
2.0 KiB
Go

package routing
import (
"errors"
lishwist "lishwist/core"
"lishwist/http/props"
"lishwist/http/response"
"lishwist/http/session"
"log"
"net/http"
"github.com/Teajey/rsvp"
)
func Register(session *session.Session, h http.Header, r *http.Request) rsvp.Response {
register := props.NewRegister("", "", "")
flash := session.FlashGet()
flashProps, _ := flash.(*props.Register)
if flashProps != nil {
register.Form.Elements.Username.Value = flashProps.Form.Elements.Username.Value
register.Error = flashProps.Error
register.Form.Elements.Username.Error = flashProps.Form.Elements.Username.Error
register.Form.Elements.ConfirmPassword.Error = flashProps.Form.Elements.ConfirmPassword.Error
}
return response.Data("register.gotmpl", register)
}
func RegisterPost(s *session.Session, h http.Header, r *http.Request) rsvp.Response {
var confirmPassword string
username, newPassword, ok := r.BasicAuth()
if ok {
confirmPassword = newPassword
} else {
err := r.ParseForm()
if err != nil {
return response.Error(http.StatusBadRequest, "Failed to parse form")
}
username = r.Form.Get("username")
newPassword = r.Form.Get("newPassword")
confirmPassword = r.Form.Get("confirmPassword")
}
register := props.NewRegister(username, newPassword, confirmPassword)
valid := register.Form.Elements.Validate()
register.Form.Elements.Password.Value = ""
register.Form.Elements.ConfirmPassword.Value = ""
if !valid {
s.FlashSet(&register)
log.Printf("Invalid register submission: %#v\n", register)
return rsvp.SeeOther(r.URL.Path, register)
}
_, err := lishwist.Register(username, newPassword)
if err != nil {
if errors.Is(err, lishwist.ErrorUsernameTaken) {
register.Form.Elements.Username.Error = "Username is taken"
} else {
register.Error = "Something went wrong."
}
s.FlashSet(&register)
log.Printf("Registration failed: %s\n", err)
return rsvp.SeeOther(r.URL.Path, register)
}
s.FlashSet(&props.Login{SuccessfulRegistration: true})
return rsvp.SeeOther("/", "Registration successful!")
}