lishwist/server/routing/register.go

54 lines
1.5 KiB
Go

package routing
import (
"encoding/json"
"lishwist/api"
"lishwist/templates"
"log"
"net/http"
)
func (ctx *Context) Register(w http.ResponseWriter, r *http.Request) {
props := api.NewRegisterProps("", "", "")
session, _ := ctx.store.Get(r, "lishwist_user")
if flashes := session.Flashes("register_props"); len(flashes) > 0 {
log.Printf("Register found flashes: %#v\n", flashes)
flashProps, _ := flashes[0].(*api.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 (ctx *Context) 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 := api.Register(username, newPassword, confirmPassword)
if props != nil {
ctx.RedirectWithFlash(w, r, "/register", "register_props", &props)
_ = json.NewEncoder(w).Encode(props)
return
}
ctx.RedirectWithFlash(w, r, "/", "successful_registration", true)
}