85 lines
1.7 KiB
Go
85 lines
1.7 KiB
Go
package routes
|
|
|
|
import (
|
|
"html/template"
|
|
"net/http"
|
|
"net/url"
|
|
"shelves/backend/errorsx"
|
|
"shelves/backend/forms"
|
|
"shelves/backend/httpx"
|
|
"shelves/backend/templates"
|
|
)
|
|
|
|
func renderView(f setupForm, e setupFormErrors) template.HTML {
|
|
|
|
body := templates.Form{
|
|
Action: "/setup",
|
|
Fields: []templates.Field{
|
|
templates.Field{
|
|
Label: "Password",
|
|
Type: "password",
|
|
Name: "password",
|
|
Error: errorsx.String(e.password),
|
|
},
|
|
templates.Field{
|
|
Label: "Confirm password",
|
|
Type: "password",
|
|
Name: "passwordConfirmation",
|
|
},
|
|
},
|
|
}
|
|
|
|
return templates.PageBase{Title: "Set up", Body: body.HTML()}.HTML()
|
|
}
|
|
|
|
func SetupGet(w http.ResponseWriter, r *http.Request) {
|
|
ctx := httpx.GetCtx(r)
|
|
if !ctx.NeedsOwnerSetup {
|
|
httpx.SeeOther(w, "/")
|
|
return
|
|
}
|
|
|
|
html(w, renderView(setupForm{}, setupFormErrors{}))
|
|
}
|
|
|
|
type setupForm struct {
|
|
password string
|
|
}
|
|
|
|
type setupFormErrors struct {
|
|
password error
|
|
}
|
|
|
|
func parseForm(f *setupForm, e *setupFormErrors, vs url.Values, v *forms.Validator) {
|
|
f.password = vs.Get("password")
|
|
passwordConfirmation := vs.Get("passwordConfirmation")
|
|
|
|
if f.password != passwordConfirmation {
|
|
e.password = v.Fail("Passwords did not match")
|
|
return
|
|
}
|
|
|
|
e.password = v.MinLength(f.password, 1)
|
|
}
|
|
|
|
func SetupPost(w http.ResponseWriter, r *http.Request) {
|
|
ctx := httpx.GetCtx(r)
|
|
if !ctx.NeedsOwnerSetup {
|
|
httpx.SeeOther(w, "/")
|
|
return
|
|
}
|
|
|
|
form := setupForm{}
|
|
errs := setupFormErrors{}
|
|
failed := forms.ParseFormData(r, func(vs url.Values, v *forms.Validator) {
|
|
parseForm(&form, &errs, vs, v)
|
|
})
|
|
|
|
if failed {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
html(w, renderView(form, errs))
|
|
} else {
|
|
httpx.SeeOther(w, "/setup")
|
|
}
|
|
}
|