67 lines
1.7 KiB
Go
67 lines
1.7 KiB
Go
package routing
|
|
|
|
import (
|
|
"errors"
|
|
lishwist "lishwist/core"
|
|
"lishwist/http/api"
|
|
"lishwist/http/response"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/Teajey/rsvp"
|
|
)
|
|
|
|
func Register(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
|
|
props := api.NewRegisterProps("", "", "")
|
|
|
|
flash := session.FlashGet()
|
|
|
|
flashProps, _ := flash.(*api.RegisterProps)
|
|
if flashProps != nil {
|
|
props.Username.Value = flashProps.Username.Value
|
|
|
|
props.GeneralError = flashProps.GeneralError
|
|
props.Username.Error = flashProps.Username.Error
|
|
props.ConfirmPassword.Error = flashProps.ConfirmPassword.Error
|
|
}
|
|
|
|
return response.Data("register.gotmpl", props)
|
|
}
|
|
|
|
func RegisterPost(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
|
|
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")
|
|
|
|
props := api.NewRegisterProps(username, newPassword, confirmPassword)
|
|
|
|
valid := props.Validate()
|
|
props.Password.Value = ""
|
|
props.ConfirmPassword.Value = ""
|
|
if !valid {
|
|
s.FlashSet(&props)
|
|
log.Printf("Invalid register props: %#v\n", props)
|
|
return rsvp.SeeOther(r.URL.Path, props)
|
|
}
|
|
|
|
_, err = lishwist.Register(username, newPassword)
|
|
if err != nil {
|
|
if errors.Is(err, lishwist.ErrorUsernameTaken) {
|
|
props.Username.Error = "Username is taken"
|
|
} else {
|
|
props.GeneralError = "Something went wrong."
|
|
}
|
|
s.FlashSet(&props)
|
|
log.Printf("Registration failed: %s\n", err)
|
|
return rsvp.SeeOther(r.URL.Path, props)
|
|
}
|
|
|
|
s.FlashSet(true)
|
|
return rsvp.SeeOther("/", "Registration successful!")
|
|
}
|