Convert the login variables to a struct with parsing and validation

It is a lot of code having to check the login variables inside the POST
handler, and i could not mark each input field individually as invalid
because the generic errors array i was using did no identify which field
had the error.

Thus, i use more or less the same technique as with Numerus: a struct
with the value and the error message.  This time the input field does
not have the label and extra attributes because i believe this belongs
to the template: if i want do reuse the same form template, i should
create a common template rather than defining everything in Go.

The name is a bit different, however, because it has meaning both to the
front and back ends, as it needs to be exactly the same.  Writing it
twice is error-prone, as with a rename i could easily forget to change
one or the other, and here i see value in having that in Go, because
it is also used in code.
This commit is contained in:
jordi fita mas 2023-07-24 17:17:15 +02:00
parent 7b1e17569e
commit 01526bff1a
8 changed files with 242 additions and 89 deletions

View File

@ -6,23 +6,14 @@
package app package app
import ( import (
"errors" "golang.org/x/text/language"
"net/http" "net/http"
"net/mail"
"path" "path"
"strings" "strings"
"time"
"golang.org/x/text/language"
"dev.tandem.ws/tandem/camper/pkg/database" "dev.tandem.ws/tandem/camper/pkg/database"
httplib "dev.tandem.ws/tandem/camper/pkg/http" httplib "dev.tandem.ws/tandem/camper/pkg/http"
"dev.tandem.ws/tandem/camper/pkg/locale" "dev.tandem.ws/tandem/camper/pkg/locale"
"dev.tandem.ws/tandem/camper/pkg/template"
)
const (
sessionCookie = "camper-session"
) )
func shiftPath(p string) (head, tail string) { func shiftPath(p string) (head, tail string) {
@ -87,60 +78,3 @@ func (h *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r) http.NotFound(w, r)
} }
} }
func (h *App) handleGet(w http.ResponseWriter, r *http.Request) {
l := h.matchLocale(r)
template.MustRender(w, l, "login.gohtml", nil)
}
func (h *App) matchLocale(r *http.Request) *locale.Locale {
return locale.Match(r, h.locales, h.defaultLocale, h.languageMatcher)
}
func (h *App) handleLogin(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var errs []error
l := h.matchLocale(r)
email := strings.TrimSpace(r.FormValue("email"))
if email == "" {
errs = append(errs, errors.New(l.Get("Email can not be empty.")))
} else if _, err := mail.ParseAddress(email); err != nil {
errs = append(errs, errors.New(l.Get("This email is not valid. It should be like name@domain.com.")))
}
password := strings.TrimSpace(r.FormValue("password"))
if password == "" {
errs = append(errs, errors.New(l.Get("Password can not be empty.")))
}
if errs == nil {
conn := h.db.MustAcquire(r.Context())
cookie := conn.MustGetText(r.Context(), "select login($1, $2, $3)", email, password, httplib.RemoteAddr(r))
if cookie != "" {
setSessionCookie(w, cookie)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
errs = append(errs, errors.New(l.Get("Invalid user or password.")))
w.WriteHeader(http.StatusUnauthorized)
} else {
w.WriteHeader(http.StatusUnprocessableEntity)
}
template.MustRender(w, l, "login.gohtml", errs)
}
func setSessionCookie(w http.ResponseWriter, cookie string) {
http.SetCookie(w, createSessionCookie(cookie, 8766*24*time.Hour))
}
func createSessionCookie(value string, duration time.Duration) *http.Cookie {
return &http.Cookie{
Name: sessionCookie,
Value: value,
Path: "/",
Expires: time.Now().Add(duration),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}

104
pkg/app/login.go Normal file
View File

@ -0,0 +1,104 @@
/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package app
import (
"errors"
"net/http"
"time"
"dev.tandem.ws/tandem/camper/pkg/form"
httplib "dev.tandem.ws/tandem/camper/pkg/http"
"dev.tandem.ws/tandem/camper/pkg/locale"
"dev.tandem.ws/tandem/camper/pkg/template"
)
const (
sessionCookie = "camper-session"
)
type loginForm struct {
Email *form.Input
Password *form.Input
Error error
}
func newLoginForm() *loginForm {
return &loginForm{
Email: &form.Input{
Name: "email",
},
Password: &form.Input{
Name: "password",
},
}
}
func (f *loginForm) Parse(r *http.Request) error {
if err := r.ParseForm(); err != nil {
return err
}
f.Email.FillValue(r)
f.Password.FillValue(r)
return nil
}
func (f *loginForm) Valid(l *locale.Locale) bool {
v := form.NewValidator(l)
if v.CheckRequired(f.Email, l.GettextNoop("Email can not be empty.")) {
v.CheckValidEmail(f.Email, l.GettextNoop("This email is not valid. It should be like name@domain.com."))
}
v.CheckRequired(f.Password, l.GettextNoop("Password can not be empty."))
return v.AllOK
}
func (h *App) handleGet(w http.ResponseWriter, r *http.Request) {
l := h.matchLocale(r)
login := newLoginForm()
template.MustRender(w, l, "login.gohtml", login)
}
func (h *App) matchLocale(r *http.Request) *locale.Locale {
return locale.Match(r, h.locales, h.defaultLocale, h.languageMatcher)
}
func (h *App) handleLogin(w http.ResponseWriter, r *http.Request) {
login := newLoginForm()
if err := login.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
l := h.matchLocale(r)
if login.Valid(l) {
conn := h.db.MustAcquire(r.Context())
cookie := conn.MustGetText(r.Context(), "select login($1, $2, $3)", login.Email, login.Password, httplib.RemoteAddr(r))
if cookie != "" {
setSessionCookie(w, cookie)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
login.Error = errors.New(l.Gettext("Invalid user or password."))
w.WriteHeader(http.StatusUnauthorized)
} else {
w.WriteHeader(http.StatusUnprocessableEntity)
}
template.MustRender(w, l, "login.gohtml", login)
}
func setSessionCookie(w http.ResponseWriter, cookie string) {
http.SetCookie(w, createSessionCookie(cookie, 8766*24*time.Hour))
}
func createSessionCookie(value string, duration time.Duration) *http.Cookie {
return &http.Cookie{
Name: sessionCookie,
Value: value,
Path: "/",
Expires: time.Now().Add(duration),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}

25
pkg/form/input.go Normal file
View File

@ -0,0 +1,25 @@
/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package form
import (
"database/sql/driver"
"net/http"
"strings"
)
type Input struct {
Name string
Val string
Error error
}
func (input *Input) FillValue(r *http.Request) {
input.Val = strings.TrimSpace(r.FormValue(input.Name))
}
func (input *Input) Value() (driver.Value, error) {
return input.Val, nil
}

41
pkg/form/validator.go Normal file
View File

@ -0,0 +1,41 @@
/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package form
import (
"dev.tandem.ws/tandem/camper/pkg/locale"
"errors"
"net/mail"
)
type Validator struct {
l *locale.Locale
AllOK bool
}
func NewValidator(l *locale.Locale) *Validator {
return &Validator{
l: l,
AllOK: true,
}
}
func (v *Validator) CheckRequired(input *Input, message string) bool {
return v.check(input, input.Val != "", message)
}
func (v *Validator) CheckValidEmail(input *Input, message string) bool {
_, err := mail.ParseAddress(input.Val)
return v.check(input, err == nil, message)
}
func (v *Validator) check(field *Input, ok bool, message string) bool {
if !ok {
field.Error = errors.New(v.l.Get(message))
v.AllOK = false
}
return ok
}

View File

@ -8,7 +8,7 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: camper\n" "Project-Id-Version: camper\n"
"Report-Msgid-Bugs-To: jordi@tandem.blog\n" "Report-Msgid-Bugs-To: jordi@tandem.blog\n"
"POT-Creation-Date: 2023-07-22 23:45+0200\n" "POT-Creation-Date: 2023-07-24 17:04+0200\n"
"PO-Revision-Date: 2023-07-22 23:45+0200\n" "PO-Revision-Date: 2023-07-22 23:45+0200\n"
"Last-Translator: jordi fita mas <jordi@tandem.blog>\n" "Last-Translator: jordi fita mas <jordi@tandem.blog>\n"
"Language-Team: Catalan <ca@dodds.net>\n" "Language-Team: Catalan <ca@dodds.net>\n"
@ -18,22 +18,22 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n" "Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: web/templates/login.gohtml:2 web/templates/login.gohtml:7 #: web/templates/login.gohtml:2 web/templates/login.gohtml:8
msgctxt "title" msgctxt "title"
msgid "Login" msgid "Login"
msgstr "Entrada" msgstr "Entrada"
#: web/templates/login.gohtml:9 #: web/templates/login.gohtml:17
msgctxt "input" msgctxt "input"
msgid "Email" msgid "Email"
msgstr "Correu-e" msgstr "Correu-e"
#: web/templates/login.gohtml:12 #: web/templates/login.gohtml:26
msgctxt "input" msgctxt "input"
msgid "Password" msgid "Password"
msgstr "Contrasenya" msgstr "Contrasenya"
#: web/templates/login.gohtml:15 #: web/templates/login.gohtml:35
msgctxt "action" msgctxt "action"
msgid "Login" msgid "Login"
msgstr "Entra" msgstr "Entra"
@ -41,3 +41,19 @@ msgstr "Entra"
#: web/templates/layout.gohtml:15 #: web/templates/layout.gohtml:15
msgid "Skip to main content" msgid "Skip to main content"
msgstr "Salta al contingut principal" msgstr "Salta al contingut principal"
#: pkg/app/login.go:50
msgid "Email can not be empty."
msgstr "No podeu deixar el correu en blanc."
#: pkg/app/login.go:51
msgid "This email is not valid. It should be like name@domain.com."
msgstr "Aquest correu-e no és vàlid. Hauria de ser similar a nom@domini.com."
#: pkg/app/login.go:53
msgid "Password can not be empty."
msgstr "No podeu deixar la contrasenya en blanc."
#: pkg/app/login.go:82
msgid "Invalid user or password."
msgstr "Nom dusuari o contrasenya incorrectes."

View File

@ -8,7 +8,7 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: camper\n" "Project-Id-Version: camper\n"
"Report-Msgid-Bugs-To: jordi@tandem.blog\n" "Report-Msgid-Bugs-To: jordi@tandem.blog\n"
"POT-Creation-Date: 2023-07-22 23:45+0200\n" "POT-Creation-Date: 2023-07-24 17:04+0200\n"
"PO-Revision-Date: 2023-07-22 23:46+0200\n" "PO-Revision-Date: 2023-07-22 23:46+0200\n"
"Last-Translator: jordi fita mas <jordi@tandem.blog>\n" "Last-Translator: jordi fita mas <jordi@tandem.blog>\n"
"Language-Team: Spanish <es@tp.org.es>\n" "Language-Team: Spanish <es@tp.org.es>\n"
@ -18,22 +18,22 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n" "Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: web/templates/login.gohtml:2 web/templates/login.gohtml:7 #: web/templates/login.gohtml:2 web/templates/login.gohtml:8
msgctxt "title" msgctxt "title"
msgid "Login" msgid "Login"
msgstr "Entrada" msgstr "Entrada"
#: web/templates/login.gohtml:9 #: web/templates/login.gohtml:17
msgctxt "input" msgctxt "input"
msgid "Email" msgid "Email"
msgstr "Correo-e" msgstr "Correo-e"
#: web/templates/login.gohtml:12 #: web/templates/login.gohtml:26
msgctxt "input" msgctxt "input"
msgid "Password" msgid "Password"
msgstr "Contraseña" msgstr "Contraseña"
#: web/templates/login.gohtml:15 #: web/templates/login.gohtml:35
msgctxt "action" msgctxt "action"
msgid "Login" msgid "Login"
msgstr "Entrar" msgstr "Entrar"
@ -41,3 +41,19 @@ msgstr "Entrar"
#: web/templates/layout.gohtml:15 #: web/templates/layout.gohtml:15
msgid "Skip to main content" msgid "Skip to main content"
msgstr "Saltar al contenido principal" msgstr "Saltar al contenido principal"
#: pkg/app/login.go:50
msgid "Email can not be empty."
msgstr "No podéis dejar el correo-e en blanco."
#: pkg/app/login.go:51
msgid "This email is not valid. It should be like name@domain.com."
msgstr "Este correo-e no es válido. Tiene que ser parecido a nombre@dominio.com."
#: pkg/app/login.go:53
msgid "Password can not be empty."
msgstr "No podéis dejar la contraseña en blanco."
#: pkg/app/login.go:82
msgid "Invalid user or password."
msgstr "Usuario o contraseña incorrectos."

View File

@ -20,3 +20,10 @@
</main> </main>
</body> </body>
</html> </html>
{{ define "error-attrs" }}{{ if .Error }}aria-invalid="true" aria-errormessage="{{ .Name }}-error"{{ end }}{{ end }}
{{ define "error-message" -}}
{{ if .Error -}}
<span id="{{ .Name }}-error" class="error">{{ .Error }}</span><br>
{{- end }}
{{- end }}

View File

@ -3,23 +3,33 @@
{{- end }} {{- end }}
{{ define "content" -}} {{ define "content" -}}
{{- /*gotype: dev.tandem.ws/tandem/camper/pkg/app.loginForm */ -}}
<form method="post" action="/login"> <form method="post" action="/login">
<h2>{{( pgettext "Login" "title" )}}</h2> <h2>{{( pgettext "Login" "title" )}}</h2>
{{ if . -}} {{ if .Error -}}
<div class="message" role="alert"> <div class="error" role="alert">
{{ range . -}} <p>{{ .Error }}</p>
<p>{{ . }}</p>
{{- end }}
</div> </div>
{{- end }} {{- end }}
<fieldset> <fieldset>
<label> {{ with .Email -}}
{{( pgettext "Email" "input" )}}<br> <label>
<input type="email" name="email" autocomplete="username" required autofocus><br> {{( pgettext "Email" "input" )}}<br>
</label><label> <input type="email" name="{{ .Name }}" value="{{ .Val }}"
{{( pgettext "Password" "input" )}}<br> autocomplete="username" required autofocus
<input type="password" name="password" autocomplete="current-password" required><br> {{ template "error-attrs" . }}><br>
</label> </label>
{{ template "error-message" . }}
{{- end }}
{{ with .Password -}}
<label>
{{( pgettext "Password" "input" )}}<br>
<input type="password" name="{{ .Name }}" value="{{ .Val }}"
autocomplete="current-password" required
{{ template "error-attrs" . }}><br>
</label>
{{ template "error-message" . }}
{{- end }}
</fieldset> </fieldset>
<footer> <footer>
<button type="submit">{{( pgettext "Login" "action" )}}</button> <button type="submit">{{( pgettext "Login" "action" )}}</button>