/* * SPDX-FileCopyrightText: 2023 jordi fita mas * SPDX-License-Identifier: AGPL-3.0-only */ package app import ( "errors" "net/http" "time" "dev.tandem.ws/tandem/camper/pkg/database" "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 Redirect *form.Input Error error } func newLoginForm() *loginForm { return &loginForm{ Email: &form.Input{ Name: "email", }, Password: &form.Input{ Name: "password", }, Redirect: &form.Input{ Name: "redirect", }, } } func (f *loginForm) Parse(r *http.Request) error { if err := r.ParseForm(); err != nil { return err } f.Email.FillValue(r) f.Password.FillValue(r) f.Redirect.FillValue(r) if f.Redirect.Val == "" { f.Redirect.Val = "/" } 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) serveLoginForm(w http.ResponseWriter, _ *http.Request, l *locale.Locale, requestURL string) { login := newLoginForm() login.Redirect.Val = requestURL w.WriteHeader(http.StatusUnauthorized) template.MustRender(w, l, "login.gohtml", login) } func (h *App) handleLogin(w http.ResponseWriter, r *http.Request, l *locale.Locale, conn *database.Conn) { login := newLoginForm() if err := login.Parse(r); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if login.Valid(l) { 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, login.Redirect.Val, 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 getSessionCookie(r *http.Request) string { if cookie, err := r.Cookie(sessionCookie); err == nil { return cookie.Value } return "" } 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, } }