camper/pkg/app/app.go

147 lines
3.7 KiB
Go

/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package app
import (
"errors"
"net/http"
"net/mail"
"path"
"strings"
"time"
"golang.org/x/text/language"
"dev.tandem.ws/tandem/camper/pkg/database"
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"
)
func shiftPath(p string) (head, tail string) {
p = path.Clean("/" + p)
if i := strings.IndexByte(p[1:], '/') + 1; i <= 0 {
return p[1:], "/"
} else {
return p[1:i], p[i:]
}
}
func methodNotAllowed(w http.ResponseWriter, _ *http.Request, allowed ...string) {
w.Header().Set("Allow", strings.Join(allowed, ", "))
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
type App struct {
db *database.DB
fileHandler http.Handler
locales locale.Locales
defaultLocale *locale.Locale
languageMatcher language.Matcher
}
func New(db *database.DB) http.Handler {
locales := locale.MustGetAll(db)
app := &App{
db: db,
fileHandler: http.FileServer(http.Dir("web/static")),
locales: locales,
defaultLocale: locales[language.Catalan],
languageMatcher: language.NewMatcher(locales.Tags()),
}
var handler http.Handler = app
handler = httplib.RecoverPanic(handler)
handler = httplib.LogRequest(handler)
return handler
}
func (h *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var head string
head, r.URL.Path = shiftPath(r.URL.Path)
switch head {
case "static":
h.fileHandler.ServeHTTP(w, r)
case "login":
switch r.Method {
case http.MethodPost:
h.handleLogin(w, r)
default:
methodNotAllowed(w, r, http.MethodPost)
}
case "":
switch r.Method {
case http.MethodGet:
h.handleGet(w, r)
default:
methodNotAllowed(w, r, http.MethodGet)
}
default:
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,
}
}