71 lines
1.8 KiB
Go
71 lines
1.8 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 {
|
|
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)
|
|
return
|
|
}
|
|
|
|
ctx.RedirectWithFlash(w, r, "/", "successful_registration", true)
|
|
}
|
|
|
|
type jsonParams struct {
|
|
Username string
|
|
NewPassword string
|
|
ConfirmPassword string
|
|
}
|
|
|
|
func (ctx *Context) RegisterPostJson(w http.ResponseWriter, r *http.Request) {
|
|
var params jsonParams
|
|
err := decodeJsonParams(r, ¶ms)
|
|
if err != nil {
|
|
writeGeneralError(w, "Failed to decode json params: "+err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
props := api.Register(params.Username, params.NewPassword, params.ConfirmPassword)
|
|
|
|
_ = json.NewEncoder(w).Encode(props)
|
|
}
|