Phase 10, part 3: signing in and out, resets, locks and two-factor

The server edition now starts. Sign-in by email and password, limited per
address and per IP; ten failures in a row lock the account and email its
owner, and a reset by email (or an admin) unlocks it. Settings → Your
account has the profile, the password, where you're signed in, and
two-factor sign-in with an authenticator app (TOTP, from a QR code) and
ten recovery codes. The app's own mail goes through SUPERMARKET_MAIL_URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 09:01:29 -07:00
co-authored by Claude Opus 5.5
parent 72455438c9
commit 8040512a18
26 changed files with 1991 additions and 12 deletions
+358
View File
@@ -0,0 +1,358 @@
package web
import (
"encoding/base64"
"html/template"
"net/http"
"net/url"
"strings"
"time"
"rsc.io/qr"
"supermarket/internal/users"
)
// Settings → Your account, on the server edition: each person's profile,
// password, two-factor sign-in, and where they're signed in.
type accountData struct {
U *users.User
Role users.Role
Sessions []sessionRow
Zones []string
Problem string // under the form it's about
Section string // which form: profile, password, two-factor
// Setting up two-factor sign-in.
Secret string
QR template.URL
// Recovery codes, shown once.
Codes []string
}
type sessionRow struct {
*users.Session
This bool
}
// commonZones are offered for the time zone; any IANA name is accepted.
var commonZones = []string{
"UTC", "Europe/London", "Europe/Dublin", "Europe/Lisbon", "Europe/Paris", "Europe/Berlin", "Europe/Madrid", "Europe/Rome",
"Europe/Amsterdam", "Europe/Stockholm", "Europe/Warsaw", "Europe/Athens", "Europe/Helsinki", "Europe/Istanbul",
"America/New_York", "America/Toronto", "America/Chicago", "America/Denver", "America/Phoenix", "America/Los_Angeles",
"America/Anchorage", "Pacific/Honolulu", "America/Mexico_City", "America/Sao_Paulo", "America/Buenos_Aires",
"Africa/Lagos", "Africa/Johannesburg", "Africa/Nairobi", "Asia/Dubai", "Asia/Kolkata", "Asia/Singapore",
"Asia/Shanghai", "Asia/Tokyo", "Asia/Seoul", "Australia/Perth", "Australia/Sydney", "Pacific/Auckland",
}
// me is the signed-in user, or a 404 on the local edition, which has no
// accounts.
func (s *Server) me(w http.ResponseWriter, r *http.Request) *viewer {
v := viewerOf(r)
if v.User == nil {
http.NotFound(w, r)
return nil
}
return v
}
func (s *Server) accountPage(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
s.renderAccount(w, r, v, &accountData{}, http.StatusOK)
}
func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, v *viewer, d *accountData, code int) {
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
list, err := users.Sessions(s.DB, u.ID, time.Now())
if err != nil {
s.serverError(w, err)
return
}
d.U, d.Role, d.Zones = u, v.Member.Role, commonZones
for _, ss := range list {
d.Sessions = append(d.Sessions, sessionRow{Session: ss, This: ss.ID == v.Session.ID})
}
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "account", page{Title: "Your account", Nav: "settings/account", Data: d})
}
func (s *Server) accountProfile(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u := *v.User
u.Name = strings.TrimSpace(r.PostFormValue("name"))
u.Title = strings.TrimSpace(r.PostFormValue("title"))
u.TimeZone = strings.TrimSpace(r.PostFormValue("time_zone"))
switch {
case u.Name == "":
s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: "Give your name."}, http.StatusUnprocessableEntity)
return
case u.TimeZone != "" && !validZone(u.TimeZone):
s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: "That isn't a time zone: choose one from the list, such as Europe/Paris."}, http.StatusUnprocessableEntity)
return
}
if err := users.SaveProfile(s.DB, &u); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/account", "saved")
}
func validZone(z string) bool {
if z == "Local" || len(z) > 64 {
return false
}
_, err := time.LoadLocation(z)
return err == nil
}
func (s *Server) accountPassword(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
fail := func(msg string) {
s.renderAccount(w, r, v, &accountData{Section: "password", Problem: msg}, http.StatusUnprocessableEntity)
}
if !users.CheckPassword(u, r.PostFormValue("current")) {
s.accountWrongPassword(r, u)
fail("Your current password isn't right.")
return
}
pw := r.PostFormValue("password")
if err := users.CheckNewPassword(pw, u.Email); err != nil {
fail(sentence(err.Error()) + ".")
return
}
if pw != r.PostFormValue("password2") {
fail("The two new passwords aren't the same.")
return
}
if err := users.SetPassword(s.DB, u, pw); err != nil {
s.serverError(w, err)
return
}
n, err := users.EndOtherSessions(s.DB, u.ID, v.Session.ID)
if err != nil {
s.serverError(w, err)
return
}
s.Log.Info("account: password changed", "user", u.Email, "sessions ended", n)
redirect(w, r, "/settings/account", "password-changed")
}
// accountWrongPassword counts a wrong current password like a failed
// sign-in: someone at an open laptop can't guess at it for ever.
func (s *Server) accountWrongPassword(r *http.Request, u *users.User) {
now := time.Now()
s.countFailure("signin:ip:"+clientIP(r), "signin:email:"+u.Email, u, now)
}
func (s *Server) accountEndSession(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
id := r.PathValue("id")
if id == v.Session.ID {
s.signout(w, r)
return
}
if err := users.EndSessionByID(s.DB, v.User.ID, id); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/account#sessions", "session-ended")
}
func (s *Server) accountEndOthers(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
if _, err := users.EndOtherSessions(s.DB, v.User.ID, v.Session.ID); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/account#sessions", "sessions-ended")
}
// Two-factor sign-in.
// twoFactorPage starts setting up an authenticator app: a new secret,
// kept aside until a code from the app confirms it.
func (s *Server) twoFactorPage(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
if v.User.TwoFactor {
http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther)
return
}
secret := s.Secrets.Get(users.TOTPPendingName(v.User.ID))
if secret == "" || r.URL.Query().Get("new") != "" {
var err error
if secret, err = users.NewTOTPSecret(); err != nil {
s.serverError(w, err)
return
}
if err := s.Secrets.Set(map[string]string{users.TOTPPendingName(v.User.ID): secret}); err != nil {
s.serverError(w, err)
return
}
}
s.renderTwoFactor(w, r, v, secret, "", http.StatusOK)
}
func (s *Server) renderTwoFactor(w http.ResponseWriter, r *http.Request, v *viewer, secret, problem string, code int) {
d := &accountData{U: v.User, Secret: spaced(secret), Problem: problem}
if c, err := qr.Encode(users.TOTPURL(s.issuer(), v.User.Email, secret), qr.M); err == nil {
c.Scale = 6
d.QR = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(c.PNG()))
}
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Data: d})
}
// issuer is the name the authenticator app shows: Supermarket and where.
func (s *Server) issuer() string {
if u, err := url.Parse(s.PublicURL); err == nil && u.Hostname() != "" {
return "Supermarket (" + u.Hostname() + ")"
}
return "Supermarket"
}
// spaced writes a secret in groups of four, to type it in.
func spaced(secret string) string {
var b strings.Builder
for i, c := range secret {
if i > 0 && i%4 == 0 {
b.WriteByte(' ')
}
b.WriteRune(c)
}
return b.String()
}
func (s *Server) twoFactorOn(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
secret := s.Secrets.Get(users.TOTPPendingName(u.ID))
if u.TwoFactor || secret == "" {
http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther)
return
}
step, ok := users.CheckTOTP(secret, r.PostFormValue("code"), 0, time.Now())
if !ok {
s.renderTwoFactor(w, r, v, secret, "That code isn't right. Check the app shows Supermarket's code, and that your phone's clock is right, then try the code showing now.", http.StatusUnprocessableEntity)
return
}
codes, hashes, err := users.NewRecoveryCodes()
if err != nil {
s.serverError(w, err)
return
}
if err := s.Secrets.Set(map[string]string{users.TOTPSecretName(u.ID): secret, users.TOTPPendingName(u.ID): ""}); err != nil {
s.serverError(w, err)
return
}
if err := users.SetTwoFactor(s.DB, u, true, hashes); err != nil {
s.serverError(w, err)
return
}
_ = users.UseTOTPStep(s.DB, u, step)
s.Log.Info("account: two-factor sign-in on", "user", u.Email)
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "Two-factor sign-in is on.", Data: &accountData{U: u, Codes: codes}})
}
func (s *Server) twoFactorOff(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
if !users.CheckPassword(u, r.PostFormValue("current")) {
s.accountWrongPassword(r, u)
s.renderAccount(w, r, v, &accountData{Section: "two-factor", Problem: "Your password isn't right."}, http.StatusUnprocessableEntity)
return
}
if err := turnOffTwoFactor(s, u); err != nil {
s.serverError(w, err)
return
}
s.Log.Info("account: two-factor sign-in off", "user", u.Email)
redirect(w, r, "/settings/account#two-factor", "two-factor-off")
}
// turnOffTwoFactor removes a user's authenticator and recovery codes.
func turnOffTwoFactor(s *Server, u *users.User) error {
if err := users.SetTwoFactor(s.DB, u, false, nil); err != nil {
return err
}
return s.Secrets.Set(map[string]string{users.TOTPSecretName(u.ID): "", users.TOTPPendingName(u.ID): ""})
}
func (s *Server) recoveryCodes(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
if !u.TwoFactor {
http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther)
return
}
if !users.CheckPassword(u, r.PostFormValue("current")) {
s.accountWrongPassword(r, u)
s.renderAccount(w, r, v, &accountData{Section: "two-factor", Problem: "Your password isn't right."}, http.StatusUnprocessableEntity)
return
}
codes, hashes, err := users.NewRecoveryCodes()
if err != nil {
s.serverError(w, err)
return
}
step := u.TOTPStep()
if err := users.SetTwoFactor(s.DB, u, true, hashes); err != nil {
s.serverError(w, err)
return
}
_ = users.UseTOTPStep(s.DB, u, step)
s.Log.Info("account: new recovery codes", "user", u.Email)
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "New recovery codes: the old ones no longer work.", Data: &accountData{U: u, Codes: codes}})
}
+3 -3
View File
@@ -84,8 +84,8 @@ func publicPath(p string) bool {
switch {
case p == "/healthz", p == "/favicon.ico", p == "/mcp",
strings.HasPrefix(p, "/static/"),
p == "/signin", p == "/signout",
strings.HasPrefix(p, "/setup"):
p == "/signin", p == "/signin/code", p == "/signout", p == "/forgot",
strings.HasPrefix(p, "/reset/"), strings.HasPrefix(p, "/setup/"):
return true
}
return false
@@ -99,7 +99,7 @@ func (s *Server) sessions(next http.Handler) http.Handler {
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, localOwner)))
return
}
if !publicPath(r.URL.Path) || r.URL.Path == "/signin" {
if !publicPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/signin") {
if done, err := s.hasOwner(); err != nil {
s.serverError(w, err)
return
+2
View File
@@ -8,6 +8,7 @@ import (
"testing"
"time"
"supermarket/internal/appmail"
"supermarket/internal/config"
"supermarket/internal/users"
)
@@ -17,6 +18,7 @@ func newServerEdition(t *testing.T) (*Server, http.Handler) {
t.Helper()
s, h := newTestServer(t, nil)
s.Config = &config.Config{Edition: config.Server}
s.Mail = &appmail.Outbox{}
return s, h
}
+27 -1
View File
@@ -27,6 +27,7 @@ import (
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/appmail"
"supermarket/internal/core"
"supermarket/internal/db"
"supermarket/internal/legacy"
@@ -59,7 +60,8 @@ type Server struct {
MCPToken string
MCPSocket string // the MCP socket's path on the host, for Hermes' config
MCP http.Handler
Restart func() // stops the app so Docker starts it again; nil in tests
Mail appmail.Sender // the app's own mail (invitations, resets); nil on local
Restart func() // stops the app so Docker starts it again; nil in tests
Log *slog.Logger
// What the legacy import did at startup, or why it failed.
@@ -140,6 +142,23 @@ func (s *Server) Handler() (http.Handler, error) {
// Signing in (the server edition).
mux.HandleFunc("GET /setup/{token}", s.setupPage)
mux.HandleFunc("POST /setup/{token}", s.setupSave)
mux.HandleFunc("GET /signin", s.signinPage)
mux.HandleFunc("POST /signin", s.signin)
mux.HandleFunc("POST /signin/code", s.signinCode)
mux.HandleFunc("POST /signout", s.signout)
mux.HandleFunc("GET /forgot", s.forgotPage)
mux.HandleFunc("POST /forgot", s.forgot)
mux.HandleFunc("GET /reset/{token}", s.resetPage)
mux.HandleFunc("POST /reset/{token}", s.reset)
mux.HandleFunc("GET /settings/account", s.accountPage)
mux.HandleFunc("POST /settings/account/profile", s.accountProfile)
mux.HandleFunc("POST /settings/account/password", s.accountPassword)
mux.HandleFunc("POST /settings/account/sessions/end-others", s.accountEndOthers)
mux.HandleFunc("POST /settings/account/sessions/{id}/end", s.accountEndSession)
mux.HandleFunc("GET /settings/account/two-factor", s.twoFactorPage)
mux.HandleFunc("POST /settings/account/two-factor", s.twoFactorOn)
mux.HandleFunc("POST /settings/account/two-factor/off", s.twoFactorOff)
mux.HandleFunc("POST /settings/account/recovery-codes", s.recoveryCodes)
mux.HandleFunc("GET /search", s.searchPage)
@@ -609,6 +628,13 @@ func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name str
var flashes = map[string]string{
"saved": "Saved.",
"welcome": "Welcome: you're the owner. Start with the company's profile.",
"signed-out": "Signed out.",
"password-reset": "Your new password is saved: sign in with it.",
"password-changed": "Password changed. You're signed out everywhere else.",
"session-ended": "Signed out there.",
"sessions-ended": "Signed out everywhere else.",
"two-factor-off": "Two-factor sign-in is off.",
"codes-low": "You're running out of recovery codes: make new ones below.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
+417
View File
@@ -0,0 +1,417 @@
package web
import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"supermarket/internal/appmail"
"supermarket/internal/users"
)
// Signing in and out, and resetting a password by email (the server
// edition).
// signinForm is what the sign-in pages show.
type signinForm struct {
Email, Next string
Code bool // the second step: the authenticator's code
Token string // the sign-in waiting for its code
Problem string
Sent bool // a reset link went out (or would have)
Reset string
}
// safeNext is where to go after signing in: a path in this app, else the
// Overview.
func safeNext(next string) string {
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, `/\`) || strings.ContainsAny(next, "\r\n") {
return "/"
}
return next
}
func (s *Server) signinPage(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
next := safeNext(r.URL.Query().Get("next"))
if v, _ := s.lookupSession(r); v != nil {
http.Redirect(w, r, next, http.StatusSeeOther)
return
}
s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: signinForm{Next: next, Email: r.URL.Query().Get("email")}})
}
func (s *Server) signinFail(w http.ResponseWriter, r *http.Request, f signinForm, code int) {
w.WriteHeader(code)
s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f})
}
const badSignIn = "That email address and password don't match an account."
func (s *Server) signin(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
now := time.Now()
email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email")))
f := signinForm{Email: email, Next: safeNext(r.PostFormValue("next"))}
ipKey, emailKey := "signin:ip:"+clientIP(r), "signin:email:"+email
if s.throttled(ipKey, users.MaxFailsPerIP, now) || s.throttled(emailKey, users.MaxFailsPerEmail, now) {
f.Problem = "Too many failed sign-ins: wait a quarter of an hour, then try again. If you've forgotten your password, reset it."
s.signinFail(w, r, f, http.StatusTooManyRequests)
return
}
u, err := users.ByEmail(s.DB, email)
if err != nil && !errors.Is(err, users.ErrNotFound) {
s.serverError(w, err)
return
}
if err != nil {
u = nil
}
ok := users.CheckPassword(u, r.PostFormValue("password"))
if !ok {
s.countFailure(ipKey, emailKey, u, now)
f.Problem = badSignIn
s.signinFail(w, r, f, http.StatusUnauthorized)
return
}
// The password is right: now it's safe to say what else stops them.
if msg := s.cannotSignIn(u); msg != "" {
f.Problem = msg
s.signinFail(w, r, f, http.StatusForbidden)
return
}
if u.TwoFactor {
token, err := users.NewLink(s.DB, users.CodeLink, u.ID, now)
if err != nil {
s.serverError(w, err)
return
}
f.Code, f.Token = true, token
s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f})
return
}
s.finishSignIn(w, r, u, ipKey, emailKey, f.Next)
}
// cannotSignIn says why a user with the right password still can't sign
// in, or "".
func (s *Server) cannotSignIn(u *users.User) string {
switch {
case u.Locked():
return "This account is locked after too many failed sign-ins. To unlock it, reset your password (below), or ask an admin."
case u.Status == users.Disabled:
return "This account is turned off. Ask an admin if you need it again."
case u.Status != users.Active || u.Kind != users.Person:
return badSignIn
}
if _, err := users.MembershipOf(s.DB, users.Team, u.ID); err != nil {
return "This account isn't part of the team any more. Ask an admin if you need it again."
}
return ""
}
// signinCode is the second step, with the authenticator's code or a
// recovery code.
func (s *Server) signinCode(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
now := time.Now()
token := r.PostFormValue("token")
f := signinForm{Next: safeNext(r.PostFormValue("next")), Code: true, Token: token}
id, err := users.PeekLink(s.DB, token, users.CodeLink, now)
if err != nil {
if !errors.Is(err, users.ErrBadLink) {
s.serverError(w, err)
return
}
f = signinForm{Next: f.Next, Problem: "That took too long: sign in again."}
s.signinFail(w, r, f, http.StatusUnauthorized)
return
}
u, err := users.ByID(s.DB, id)
if err != nil {
s.serverError(w, err)
return
}
ipKey, emailKey := "signin:ip:"+clientIP(r), "signin:email:"+u.Email
if s.throttled(ipKey, users.MaxFailsPerIP, now) || s.throttled(emailKey, users.MaxFailsPerEmail, now) {
_ = users.DropLinks(s.DB, users.CodeLink, u.ID)
f = signinForm{Next: f.Next, Problem: "Too many failed sign-ins: wait a quarter of an hour, then try again."}
s.signinFail(w, r, f, http.StatusTooManyRequests)
return
}
if msg := s.cannotSignIn(u); msg != "" {
_ = users.DropLinks(s.DB, users.CodeLink, u.ID)
s.signinFail(w, r, signinForm{Next: f.Next, Problem: msg}, http.StatusForbidden)
return
}
code := strings.TrimSpace(r.PostFormValue("code"))
ok := false
if step, good := users.CheckTOTP(s.Secrets.Get(users.TOTPSecretName(u.ID)), code, u.TOTPStep(), now); good {
if err := users.UseTOTPStep(s.DB, u, step); err != nil {
s.serverError(w, err)
return
}
ok = true
} else if len(code) > 6 {
if ok, err = users.UseRecoveryCode(s.DB, u, code); err != nil {
s.serverError(w, err)
return
}
if ok {
s.Log.Info("signin: a recovery code was used", "user", u.Email, "left", u.RecoveryLeft)
}
}
if !ok {
s.countFailure(ipKey, emailKey, u, now)
f.Problem = "That code isn't right. Codes change every 30 seconds; enter the one showing now, or a recovery code."
s.signinFail(w, r, f, http.StatusUnauthorized)
return
}
if _, err := users.UseLink(s.DB, token, users.CodeLink, now); err != nil {
s.signinFail(w, r, signinForm{Next: f.Next, Problem: "That took too long: sign in again."}, http.StatusUnauthorized)
return
}
s.finishSignIn(w, r, u, ipKey, emailKey, f.Next)
}
// finishSignIn starts the session, clears the failures, and goes on.
func (s *Server) finishSignIn(w http.ResponseWriter, r *http.Request, u *users.User, ipKey, emailKey, next string) {
if err := users.Unlock(s.DB, u.ID); err != nil {
s.serverError(w, err)
return
}
_ = users.ClearFails(s.DB, emailKey)
if err := s.startSession(w, r, u); err != nil {
s.serverError(w, err)
return
}
s.Log.Info("signin", "user", u.Email, "ip", clientIP(r))
if u.TwoFactor && u.RecoveryLeft < 3 {
redirect(w, r, "/settings/account#two-factor", "codes-low")
return
}
http.Redirect(w, r, next, http.StatusSeeOther)
}
// throttled says whether key has failed too often lately.
func (s *Server) throttled(key string, max int, now time.Time) bool {
n, _ := users.Fails(s.DB, key, users.ThrottleWindow, now)
return n >= max
}
// countFailure counts a failed sign-in against the IP, the address and
// the account, which locks after too many; its owner is told.
func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Time) {
for _, k := range []string{ipKey, emailKey} {
if err := users.Fail(s.DB, k, users.ThrottleWindow, now); err != nil {
s.Log.Warn("signin: counting a failure", "err", err)
}
}
if u == nil {
s.Log.Info("signin: failed, no such account", "key", emailKey, "ip", strings.TrimPrefix(ipKey, "signin:ip:"))
return
}
s.Log.Info("signin: failed", "user", u.Email, "ip", strings.TrimPrefix(ipKey, "signin:ip:"))
locked, err := users.FailedSignIn(s.DB, u, now)
if err != nil {
s.Log.Warn("signin: counting a failure", "err", err)
return
}
if locked {
s.Log.Warn("signin: account locked", "user", u.Email)
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Your Supermarket account is locked",
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
"Your account at " + s.PublicURL + " was locked after " + strconv.Itoa(users.LockAfter) + " failed sign-ins in a row.\n\n" +
"To unlock it, reset your password:\n" + s.PublicURL + "/forgot\n\nor ask an admin to unlock it.\n\n" +
"If those sign-ins weren't you, someone may be guessing your password. A long password used nowhere else, " +
"and two-factor sign-in (Settings → Your account), keep them out.\n"})
}
}
func (s *Server) signout(w http.ResponseWriter, r *http.Request) {
if err := s.endSession(w, r); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/signin", "signed-out")
}
// Resetting a password.
func (s *Server) forgotPage(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: signinForm{Email: r.URL.Query().Get("email")}})
}
func (s *Server) forgot(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
now := time.Now()
email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email")))
f := signinForm{Email: email, Sent: true}
// The same answer whether or not there's an account, and the email is
// sent in the background, so the page can't tell anyone which
// addresses have one. Limited per IP and per address.
ipKey, emailKey := "reset:ip:"+clientIP(r), "reset:email:"+email
if s.throttled(ipKey, 10, now) || s.throttled(emailKey, 3, now) {
f.Sent, f.Problem = false, "Several links were sent already: check your email (and its spam folder), or wait a quarter of an hour."
w.WriteHeader(http.StatusTooManyRequests)
s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: f})
return
}
_ = users.Fail(s.DB, ipKey, users.ThrottleWindow, now)
_ = users.Fail(s.DB, emailKey, users.ThrottleWindow, now)
if u, err := users.ByEmail(s.DB, email); err == nil && u.Kind == users.Person && (u.Status == users.Active) {
token, err := users.NewLink(s.DB, users.ResetLink, u.ID, now)
if err != nil {
s.serverError(w, err)
return
}
s.Log.Info("signin: password reset asked for", "user", u.Email, "ip", clientIP(r))
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Reset your Supermarket password",
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
"Someone, probably you, asked to reset your password at " + s.PublicURL + ".\n\n" +
"Choose a new one here, within an hour:\n" + s.PublicURL + "/reset/" + token + "\n\n" +
"If it wasn't you, ignore this email: your password stays as it is.\n"})
} else if err != nil && !errors.Is(err, users.ErrNotFound) {
s.serverError(w, err)
return
}
s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: f})
}
func (s *Server) resetPage(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
token := r.PathValue("token")
f := signinForm{Reset: token}
if _, err := users.PeekLink(s.DB, token, users.ResetLink, time.Now()); err != nil {
f.Reset, f.Problem = "", "This reset link has expired or was already used. Ask for a new one below."
w.WriteHeader(http.StatusNotFound)
}
s.render(w, r, "forgot", page{Title: "Choose a new password", Bare: true, Data: f})
}
func (s *Server) reset(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
now := time.Now()
token := r.PathValue("token")
f := signinForm{Reset: token}
id, err := users.PeekLink(s.DB, token, users.ResetLink, now)
if err != nil {
s.resetPage(w, r)
return
}
u, err := users.ByID(s.DB, id)
if err != nil {
s.serverError(w, err)
return
}
pw := r.PostFormValue("password")
if err := users.CheckNewPassword(pw, u.Email); err != nil {
f.Problem = sentence(err.Error()) + "."
} else if pw != r.PostFormValue("password2") {
f.Problem = "The two passwords aren't the same."
}
if f.Problem != "" {
w.WriteHeader(http.StatusUnprocessableEntity)
s.render(w, r, "forgot", page{Title: "Choose a new password", Bare: true, Data: f})
return
}
if _, err := users.UseLink(s.DB, token, users.ResetLink, now); err != nil {
s.resetPage(w, r)
return
}
if err := users.SetPassword(s.DB, u, pw); err != nil {
s.serverError(w, err)
return
}
// The email proved who they are: the lock goes, and so does every
// session, in case someone else had one.
if err := users.Unlock(s.DB, u.ID); err != nil {
s.serverError(w, err)
return
}
if _, err := users.EndOtherSessions(s.DB, u.ID, ""); err != nil {
s.serverError(w, err)
return
}
_ = users.ClearFails(s.DB, "signin:email:"+u.Email)
s.Log.Info("signin: password reset", "user", u.Email, "ip", clientIP(r))
redirect(w, r, "/signin?email="+url.QueryEscape(u.Email), "password-reset")
}
// sendMail sends the app's own mail in the background, so how long it
// takes says nothing to the person waiting.
func (s *Server) sendMail(m appmail.Message) {
if s.Mail == nil {
s.Log.Error("mail: no mail server (SUPERMARKET_MAIL_URL): not sent", "to", m.To, "subject", m.Subject)
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
if err := s.Mail.Send(ctx, m); err != nil {
s.Log.Error("mail: not sent", "to", m.To, "subject", m.Subject, "err", err)
}
}()
}
func nameSuffix(name string) string {
if name = strings.TrimSpace(name); name != "" {
return " " + strings.Fields(name)[0]
}
return ""
}
// RunAccounts forgets ended sessions, used-up links and old counts of
// failed sign-ins, every hour (the server edition).
func (s *Server) RunAccounts(ctx context.Context) {
if !s.signsIn() {
return
}
tick := time.NewTicker(time.Hour)
defer tick.Stop()
for {
s.jobDo(ctx, "accounts", func(context.Context) {
now := time.Now()
if _, err := users.PruneSessions(s.DB, now); err != nil {
s.Log.Warn("accounts: pruning sessions", "err", err)
}
if err := users.PruneLinks(s.DB, now); err != nil {
s.Log.Warn("accounts: pruning links", "err", err)
}
if err := users.PruneThrottle(s.DB, now); err != nil {
s.Log.Warn("accounts: pruning counts", "err", err)
}
})
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
+375
View File
@@ -0,0 +1,375 @@
package web
import (
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
"time"
"supermarket/internal/appmail"
"supermarket/internal/users"
)
// signin posts the sign-in form, from an IP.
func signin(h http.Handler, ip string, form url.Values) *httptest.ResponseRecorder {
return signinPost(h, ip, "/signin", form)
}
func signinPost(h http.Handler, ip, path string, form url.Values) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
req.Host = "localhost:8470"
req.RemoteAddr = ip + ":40000"
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Origin", "http://localhost:8470")
req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF})
req.Header.Set(csrfHeader, testCSRF)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func cookieOf(rec *httptest.ResponseRecorder, name string) *http.Cookie {
for _, c := range rec.Result().Cookies() {
if c.Name == name && c.MaxAge >= 0 {
return c
}
}
return nil
}
// waitMail waits for the app's mail (sent in the background).
func waitMail(t *testing.T, s *Server, to string, n int) *appmail.Message {
t.Helper()
ob := s.Mail.(*appmail.Outbox)
for i := 0; i < 200; i++ {
if ob.Count() >= n {
if m := ob.Last(to); m != nil {
return m
}
}
time.Sleep(5 * time.Millisecond)
}
t.Fatalf("no mail to %s (%d sent)", to, ob.Count())
return nil
}
func TestSignInAndOut(t *testing.T) {
s, h := newServerEdition(t)
addUser(t, s, "owner@example.com", users.Owner, nil)
rec := do(h, http.MethodGet, "/signin?next=/seo/check", nil, nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `name="next" value="/seo/check"`) {
t.Fatalf("page: %d", rec.Code)
}
// Wrong password, unknown address: the same answer.
for _, f := range []url.Values{
{"email": {"owner@example.com"}, "password": {"wrong password"}},
{"email": {"nobody@example.com"}, "password": {"a long enough one"}},
} {
rec := signin(h, "203.0.113.1", f)
if rec.Code != http.StatusUnauthorized || !strings.Contains(rec.Body.String(), "match an account") || cookieOf(rec, sessionCookie) != nil {
t.Errorf("%v: %d", f, rec.Code)
}
}
rec = signin(h, "203.0.113.1", url.Values{"email": {"Owner@Example.com"}, "password": {"a long enough one"}, "next": {"/seo/check"}})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/seo/check" {
t.Fatalf("sign in: %d %s", rec.Code, rec.Header().Get("Location"))
}
c := cookieOf(rec, sessionCookie)
if c == nil {
t.Fatal("no session")
}
if u, _ := users.ByEmail(s.DB, "owner@example.com"); u.FailedSignIns != 0 {
t.Errorf("failures not cleared: %d", u.FailedSignIns)
}
// Signed in, the sign-in page moves on.
if rec := as(h, c, http.MethodGet, "/signin", nil); rec.Code != http.StatusSeeOther {
t.Errorf("signed in, /signin: %d", rec.Code)
}
// Somewhere else: a path only.
rec = signin(h, "203.0.113.1", url.Values{"email": {"owner@example.com"}, "password": {"a long enough one"}, "next": {"//evil.example/"}})
if rec.Header().Get("Location") != "/" {
t.Errorf("open redirect: %s", rec.Header().Get("Location"))
}
// The sidebar shows who's signed in.
if rec := as(h, c, http.MethodGet, "/", nil); !strings.Contains(rec.Body.String(), `action="/signout"`) {
t.Error("no sign-out button")
}
rec = as(h, c, http.MethodPost, "/signout", url.Values{})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?msg=signed-out" {
t.Errorf("sign out: %d %s", rec.Code, rec.Header().Get("Location"))
}
if rec := as(h, c, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther {
t.Errorf("after signing out: %d", rec.Code)
}
}
func TestSignInLimitsAndLocks(t *testing.T) {
s, h := newServerEdition(t)
u := addUser(t, s, "owner@example.com", users.Owner, nil)
addUser(t, s, "jo@example.com", users.Member, map[string]users.Access{"seo": users.View})
bad := url.Values{"email": {"owner@example.com"}, "password": {"wrong password"}}
good := url.Values{"email": {"owner@example.com"}, "password": {"a long enough one"}}
// Five failures for an address, and it waits, even with the password.
for i := 0; i < users.MaxFailsPerEmail; i++ {
signin(h, "203.0.113.1", bad)
}
if rec := signin(h, "203.0.113.2", good); rec.Code != http.StatusTooManyRequests {
t.Errorf("address limit: %d", rec.Code)
}
// Another address from the same IP still works.
if rec := signin(h, "203.0.113.1", url.Values{"email": {"jo@example.com"}, "password": {"a long enough one"}}); rec.Code != http.StatusSeeOther {
t.Errorf("other address: %d", rec.Code)
}
// An IP that fails often waits too.
for i := 0; i < users.MaxFailsPerIP; i++ {
signin(h, "198.51.100.7", url.Values{"email": {"x" + string(rune('a'+i)) + "@example.com"}, "password": {"nope nope nope"}})
}
if rec := signin(h, "198.51.100.7", url.Values{"email": {"jo@example.com"}, "password": {"a long enough one"}}); rec.Code != http.StatusTooManyRequests {
t.Errorf("IP limit: %d", rec.Code)
}
// Ten failures in a row lock the account, and its owner is told.
s.DB.Exec(`DELETE FROM throttle`)
for i := 0; i < users.LockAfter; i++ {
if i%users.MaxFailsPerEmail == 0 {
s.DB.Exec(`DELETE FROM throttle`)
}
signin(h, "203.0.113.3", bad)
}
m := waitMail(t, s, "owner@example.com", 1)
if !strings.Contains(m.Subject, "locked") || !strings.Contains(m.Body, "/forgot") {
t.Errorf("mail %+v", m)
}
s.DB.Exec(`DELETE FROM throttle`)
rec := signin(h, "203.0.113.3", good)
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "locked") {
t.Errorf("locked, right password: %d", rec.Code)
}
// With the wrong password, it doesn't say.
if rec := signin(h, "203.0.113.3", bad); strings.Contains(rec.Body.String(), "locked") {
t.Error("told a guesser it's locked")
}
users.Unlock(s.DB, u.ID)
s.DB.Exec(`DELETE FROM throttle`)
if rec := signin(h, "203.0.113.3", good); rec.Code != http.StatusSeeOther {
t.Errorf("unlocked: %d", rec.Code)
}
// A disabled account, with the right password, is told so.
users.SetStatus(s.DB, u.ID, users.Disabled)
if rec := signin(h, "203.0.113.3", good); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "turned off") {
t.Errorf("disabled: %d", rec.Code)
}
}
var linkRe = regexp.MustCompile(`http://localhost:8470(/reset/[A-Za-z0-9_-]+)`)
func TestPasswordReset(t *testing.T) {
s, h := newServerEdition(t)
u := addUser(t, s, "owner@example.com", users.Owner, nil)
old := sessionFor(t, s, u)
users.FailedSignIn(s.DB, u, time.Now())
// The same page whether or not there's an account.
for _, email := range []string{"nobody@example.com", "Owner@example.com"} {
rec := postForm(h, "/forgot", url.Values{"email": {email}})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Check your email") {
t.Errorf("%s: %d", email, rec.Code)
}
}
m := waitMail(t, s, "owner@example.com", 1)
if s.Mail.(*appmail.Outbox).Count() != 1 {
t.Errorf("mail to an unknown address")
}
path := linkRe.FindStringSubmatch(m.Body)
if path == nil {
t.Fatalf("no link: %s", m.Body)
}
if rec := do(h, http.MethodGet, path[1], nil, nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Choose a new password") {
t.Errorf("reset page: %d", rec.Code)
}
if rec := postForm(h, path[1], url.Values{"password": {"short"}, "password2": {"short"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("short: %d", rec.Code)
}
rec := postForm(h, path[1], url.Values{"password": {"a brand new password"}, "password2": {"a brand new password"}})
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/signin?email=owner%40example.com") {
t.Fatalf("reset: %d %s", rec.Code, rec.Header().Get("Location"))
}
got, _ := users.ByID(s.DB, u.ID)
if !users.CheckPassword(got, "a brand new password") || got.FailedSignIns != 0 {
t.Error("not reset")
}
if rec := as(h, old, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther {
t.Error("an old session survived the reset")
}
if rec := postForm(h, path[1], url.Values{"password": {"a brand new password"}, "password2": {"a brand new password"}}); rec.Code != http.StatusNotFound {
t.Errorf("used twice: %d", rec.Code)
}
// Limited per address.
for i := 0; i < 3; i++ {
postForm(h, "/forgot", url.Values{"email": {"jo@example.com"}})
}
if rec := postForm(h, "/forgot", url.Values{"email": {"jo@example.com"}}); rec.Code != http.StatusTooManyRequests {
t.Errorf("limit: %d", rec.Code)
}
}
// codeFor signs a user in up to the two-factor step and returns its token.
func codeStep(t *testing.T, h http.Handler, email string) string {
t.Helper()
rec := signin(h, "203.0.113.9", url.Values{"email": {email}, "password": {"a long enough one"}})
m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(rec.Body.String())
if rec.Code != http.StatusOK || m == nil || cookieOf(rec, sessionCookie) != nil {
t.Fatalf("first step: %d %s", rec.Code, rec.Body.String())
}
return m[1]
}
func TestTwoFactor(t *testing.T) {
s, h := newServerEdition(t)
u := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, u)
rec := as(h, c, http.MethodGet, "/settings/account", nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Turn it on") {
t.Fatalf("account: %d", rec.Code)
}
rec = as(h, c, http.MethodGet, "/settings/account/two-factor", nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `src="data:image/png;base64,`) {
t.Fatalf("setup: %d %s", rec.Code, rec.Body.String())
}
secret := s.Secrets.Get(users.TOTPPendingName(u.ID))
if secret == "" || !strings.Contains(rec.Body.String(), spaced(secret)) {
t.Fatal("no pending secret")
}
// Reloading keeps the same secret (the app may have it already).
as(h, c, http.MethodGet, "/settings/account/two-factor", nil)
if s.Secrets.Get(users.TOTPPendingName(u.ID)) != secret {
t.Error("secret changed on reload")
}
if rec := as(h, c, http.MethodPost, "/settings/account/two-factor", url.Values{"code": {"000000"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("wrong code: %d", rec.Code)
}
now := time.Now()
rec = as(h, c, http.MethodPost, "/settings/account/two-factor", url.Values{"code": {users.TOTPCode(secret, now)}})
codes := recoveryCodesIn(rec.Body.String())
if rec.Code != http.StatusOK || len(codes) != 10 {
t.Fatalf("on: %d %d codes", rec.Code, len(codes))
}
if s.Secrets.Get(users.TOTPSecretName(u.ID)) != secret || s.Secrets.Get(users.TOTPPendingName(u.ID)) != "" {
t.Error("secret not moved")
}
// Signing in now asks for the code.
token := codeStep(t, h, "owner@example.com")
// The code just used to turn it on doesn't work again.
if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {users.TOTPCode(secret, now)}}); rec.Code != http.StatusUnauthorized {
t.Errorf("reused code: %d", rec.Code)
}
rec = signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {users.TOTPCode(secret, now.Add(30 * time.Second))}, "next": {"/seo"}})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/seo" || cookieOf(rec, sessionCookie) == nil {
t.Fatalf("code: %d %s", rec.Code, rec.Body.String())
}
// The step is used up.
if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {"123456"}}); rec.Code != http.StatusUnauthorized || !strings.Contains(rec.Body.String(), "took too long") {
t.Errorf("token reused: %d", rec.Code)
}
// A recovery code works once.
token = codeStep(t, h, "owner@example.com")
if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {strings.ToUpper(codes[0])}}); rec.Code != http.StatusSeeOther {
t.Errorf("recovery code: %d", rec.Code)
}
token = codeStep(t, h, "owner@example.com")
if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {codes[0]}}); rec.Code != http.StatusUnauthorized {
t.Errorf("recovery code twice: %d", rec.Code)
}
// New codes and turning it off need the password.
if rec := as(h, c, http.MethodPost, "/settings/account/recovery-codes", url.Values{"current": {"wrong one"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("codes, wrong password: %d", rec.Code)
}
rec = as(h, c, http.MethodPost, "/settings/account/recovery-codes", url.Values{"current": {"a long enough one"}})
if n := len(recoveryCodesIn(rec.Body.String())); n != 10 {
t.Errorf("new codes: %d", n)
}
if rec := as(h, c, http.MethodPost, "/settings/account/two-factor/off", url.Values{"current": {"a long enough one"}}); rec.Code != http.StatusSeeOther {
t.Errorf("off: %d", rec.Code)
}
if got, _ := users.ByID(s.DB, u.ID); got.TwoFactor || s.Secrets.Get(users.TOTPSecretName(u.ID)) != "" {
t.Error("still on")
}
if rec := signin(h, "203.0.113.9", url.Values{"email": {"owner@example.com"}, "password": {"a long enough one"}}); rec.Code != http.StatusSeeOther {
t.Errorf("sign in without a code: %d", rec.Code)
}
}
func TestAccountPage(t *testing.T) {
s, h := newServerEdition(t)
u := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, u)
other := sessionFor(t, s, u)
third := sessionFor(t, s, u)
rec := as(h, c, http.MethodPost, "/settings/account/profile", url.Values{"name": {"Olu A."}, "title": {"CEO"}, "time_zone": {"Mars/Base"}})
if rec.Code != http.StatusUnprocessableEntity {
t.Errorf("bad zone: %d", rec.Code)
}
as(h, c, http.MethodPost, "/settings/account/profile", url.Values{"name": {"Olu A."}, "title": {"CEO"}, "time_zone": {"Europe/Paris"}})
if got, _ := users.ByID(s.DB, u.ID); got.Name != "Olu A." || got.TimeZone != "Europe/Paris" {
t.Errorf("profile %+v", got)
}
rec = as(h, c, http.MethodGet, "/settings/account", nil)
if strings.Count(rec.Body.String(), "/end\"") != 3 || !strings.Contains(rec.Body.String(), "this one") {
t.Errorf("sessions: %s", rec.Body.String())
}
// Signing out one other session.
sess, _, err := users.Lookup(s.DB, other.Value, time.Now())
if err != nil {
t.Fatal(err)
}
otherID := sess.ID
if rec := as(h, c, http.MethodPost, "/settings/account/sessions/"+otherID+"/end", url.Values{}); rec.Code != http.StatusSeeOther {
t.Errorf("end one: %d", rec.Code)
}
if rec := as(h, other, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther {
t.Error("ended session still works")
}
// Changing the password ends the others, not this one.
if rec := as(h, c, http.MethodPost, "/settings/account/password", url.Values{"current": {"wrong"}, "password": {"a brand new password"}, "password2": {"a brand new password"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("wrong current: %d", rec.Code)
}
rec = as(h, c, http.MethodPost, "/settings/account/password", url.Values{"current": {"a long enough one"}, "password": {"a brand new password"}, "password2": {"a brand new password"}})
if rec.Code != http.StatusSeeOther {
t.Errorf("change: %d %s", rec.Code, rec.Body.String())
}
if rec := as(h, third, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther {
t.Error("other session survived the change")
}
if rec := as(h, c, http.MethodGet, "/", nil); rec.Code != http.StatusOK {
t.Error("this session ended")
}
// The local edition has no account page.
_, lh := newTestServer(t, nil)
if rec := do(lh, http.MethodGet, "/settings/account", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("local: %d", rec.Code)
}
}
// recoveryCodesIn finds the codes shown on the page.
func recoveryCodesIn(body string) []string {
m := regexp.MustCompile(`(?s)<pre id="codes">(.*?)</pre>`).FindStringSubmatch(body)
if m == nil {
return nil
}
return strings.Fields(m[1])
}
+5
View File
@@ -496,3 +496,8 @@ dl.facts dd { margin: 0; overflow-wrap: anywhere; }
.bare-main .card { padding: 1.5rem; }
.bare-main button[type="submit"] { width: 100%; }
.bare-shell .version { margin-top: auto; padding-top: 2rem; font-size: 0.8rem; color: hsl(var(--muted-foreground)); }
.pill.ok { background: hsl(var(--ok-bg)); border-color: hsl(var(--ok) / 0.35); color: hsl(var(--ok)); }
img.qr { image-rendering: pixelated; background: #fff; padding: 0.5rem; border-radius: var(--radius-sm); border: 1px solid hsl(var(--border)); }
.sidebar-foot .who { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; padding: 0.35rem 0.9rem; font-size: 0.85rem; color: hsl(var(--muted-foreground)); }
.sidebar-foot .who form { margin: 0; }
.sidebar-foot .who button { padding: 0.15rem 0.5rem; font-size: 0.8rem; }
+70
View File
@@ -0,0 +1,70 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
<h2>Your account</h2>
<p class="lede">{{.U.Email}} · {{.Role}}{{if not .U.SignedIn.IsZero}} · signed in {{ago .U.SignedIn}}{{end}}</p>
<form class="card" method="post" action="/settings/account/profile" id="profile">
<h2>About you</h2>
{{if eq .Section "profile"}}<p class="error" role="alert">{{.Problem}}</p>{{end}}
<div class="cols">
<label>Name <input name="name" value="{{.U.Name}}" autocomplete="name" required></label>
<label>Title <input name="title" value="{{.U.Title}}" placeholder="e.g. Head of marketing" autocomplete="organization-title"></label>
</div>
<label>Time zone <input name="time_zone" value="{{.U.TimeZone}}" list="zones" placeholder="e.g. Europe/Paris">
<span class="help">Times are shown in it. Empty: the server's.</span></label>
<datalist id="zones">{{range .Zones}}<option value="{{.}}">{{end}}</datalist>
<button type="submit">Save</button>
</form>
<form class="card" method="post" action="/settings/account/password" id="password">
<h2>Password</h2>
{{if eq .Section "password"}}<p class="error" role="alert">{{.Problem}}</p>{{end}}
<input type="text" name="username" value="{{.U.Email}}" autocomplete="username" hidden>
<label>Current password <input type="password" name="current" autocomplete="current-password" required></label>
<div class="cols">
<label>New password <input type="password" name="password" autocomplete="new-password" minlength="10" required>
<span class="help">At least 10 characters.</span></label>
<label>The new one again <input type="password" name="password2" autocomplete="new-password" minlength="10" required></label>
</div>
<p class="help">Changing it signs you out everywhere else.</p>
<button type="submit">Change the password</button>
</form>
<section class="card" id="two-factor">
<h2>Two-factor sign-in</h2>
{{if eq .Section "two-factor"}}<p class="error" role="alert">{{.Problem}}</p>{{end}}
{{if .U.TwoFactor}}
<p><span class="pill ok">On</span> Signing in asks for a code from your authenticator app.
{{if lt .U.RecoveryLeft 3}}<strong>{{.U.RecoveryLeft}} recovery codes left:</strong> make new ones below.{{else}}{{.U.RecoveryLeft}} recovery codes left.{{end}}</p>
<div class="cols">
<form method="post" action="/settings/account/recovery-codes">
<input type="text" name="username" value="{{.U.Email}}" autocomplete="username" hidden>
<label>Your password <input type="password" name="current" autocomplete="current-password" required></label>
<button type="submit" class="secondary">New recovery codes</button>
</form>
<form method="post" action="/settings/account/two-factor/off">
<input type="text" name="username" value="{{.U.Email}}" autocomplete="username" hidden>
<label>Your password <input type="password" name="current" autocomplete="current-password" required></label>
<button type="submit" class="secondary danger">Turn it off</button>
</form>
</div>
{{else}}
<p>Off. With it on, signing in asks for your password and a code from an authenticator app on your phone (such as Aegis, 2FAS, Google Authenticator or 1Password), so a stolen password isn't enough.</p>
<a class="button" href="/settings/account/two-factor">Turn it on</a>
{{end}}
</section>
<section class="card" id="sessions">
<h2>Where you're signed in</h2>
<table class="list">
<thead><tr><th>Browser</th><th>From</th><th>Signed in</th><th>Last used</th><th></th></tr></thead>
<tbody>
{{range .Sessions}}<tr>
<td>{{if .UserAgent}}{{truncate 60 .UserAgent}}{{else}}<span class="muted">unknown</span>{{end}}{{if .This}} <span class="pill">this one</span>{{end}}</td>
<td>{{.IP}}</td><td>{{ago .Created}}</td><td>{{ago .Seen}}</td>
<td><form class="inline" method="post" action="/settings/account/sessions/{{.ID}}/end"><button type="submit" class="secondary small">Sign out</button></form></td>
</tr>{{end}}
</tbody>
</table>
{{if gt (len .Sessions) 1}}<form method="post" action="/settings/account/sessions/end-others"><button type="submit" class="secondary">Sign out everywhere else</button></form>{{end}}
</section>
{{end}}{{template "settings-end"}}{{end}}
+29
View File
@@ -0,0 +1,29 @@
{{define "content"}}{{with .Data}}
{{if .Reset}}
<h1>Choose a new password</h1>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<form class="card" method="post" action="/reset/{{.Reset}}">
<label>New password <input type="password" name="password" autocomplete="new-password" minlength="10" required autofocus>
<span class="help">At least 10 characters. A few unrelated words make a good one.</span></label>
<label>The same password again <input type="password" name="password2" autocomplete="new-password" minlength="10" required></label>
<button type="submit">Save the new password</button>
</form>
<p class="help">Every place you're signed in is signed out; then you sign in with the new password.</p>
{{else if .Sent}}
<h1>Check your email</h1>
<section class="card">
<p>If there's an account for <strong>{{.Email}}</strong>, a link to choose a new password is on its way. It works once, for an hour.</p>
<p class="help">Nothing after a few minutes? Check the spam folder, and that the address is the one you sign in with.</p>
</section>
<p class="help"><a href="/signin">Back to signing in</a></p>
{{else}}
<h1>Reset your password</h1>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<form class="card" method="post" action="/forgot">
<label>Your email address <input type="email" name="email" value="{{.Email}}" autocomplete="username" required autofocus>
<span class="help">We'll email you a link to choose a new one. Resetting also unlocks a locked account.</span></label>
<button type="submit">Send the link</button>
</form>
<p class="help"><a href="/signin">Back to signing in</a></p>
{{end}}
{{end}}{{end}}
+4
View File
@@ -102,6 +102,8 @@
</nav>
<div class="sidebar-foot">
<a href="/settings/profile" {{if hasPrefix .Nav "settings"}}aria-current="page"{{end}}>{{template "icon" "settings"}}<span>Settings</span></a>
{{with .Viewer}}{{with .User}}<div class="who"><a href="/settings/account" title="Your account">{{if .Name}}{{.Name}}{{else}}{{.Email}}{{end}}</a>
<form method="post" action="/signout"><button type="submit" class="secondary small">Sign out</button></form></div>{{end}}{{end}}
<p class="version">Supermarket {{.Version}}</p>
</div>
</aside>
@@ -136,6 +138,8 @@
</div>
<div class="settings">
<nav class="settings-nav" aria-label="Settings sections">
{{with .Viewer}}{{if .User}}<div class="nav-label">You</div>
<a href="/settings/account" {{if eq $.Nav "settings/account"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Your account</a>{{end}}{{end}}
<div class="nav-label">Company</div>
<a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a>
<div class="nav-label">Connections</div>
+25
View File
@@ -0,0 +1,25 @@
{{define "content"}}{{with .Data}}
{{if .Code}}
<h1>Two-factor sign-in</h1>
<p class="lede">Enter the six-digit code your authenticator app shows for Supermarket.</p>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<form class="card" method="post" action="/signin/code">
<input type="hidden" name="token" value="{{.Token}}">
<input type="hidden" name="next" value="{{.Next}}">
<label>Code <input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9 ]{6,7}|[A-Za-z0-9 -]{12,16}" required autofocus>
<span class="help">Lost your phone? Enter one of your recovery codes instead.</span></label>
<button type="submit">Sign in</button>
</form>
<p class="help"><a href="/signin">Start again</a></p>
{{else}}
<h1>Sign in</h1>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<form class="card" method="post" action="/signin">
<input type="hidden" name="next" value="{{.Next}}">
<label>Email address <input type="email" name="email" value="{{.Email}}" autocomplete="username" required {{if not .Email}}autofocus{{end}}></label>
<label>Password <input type="password" name="password" autocomplete="current-password" required {{if .Email}}autofocus{{end}}></label>
<button type="submit">Sign in</button>
</form>
<p class="help"><a href="/forgot{{with .Email}}?email={{.}}{{end}}">Forgotten your password?</a></p>
{{end}}
{{end}}{{end}}
+29
View File
@@ -0,0 +1,29 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
<h2>Two-factor sign-in</h2>
{{if .Codes}}
<section class="card">
<h2>Your recovery codes</h2>
<p>If you lose your phone, each of these signs you in once instead of a code. <strong>Save them now</strong> (in a password manager, or printed): they aren't shown again.</p>
<pre id="codes">{{range .Codes}}{{.}}
{{end}}</pre>
<button type="button" class="secondary" data-copy="codes">Copy</button>
<p><a class="button" href="/settings/account#two-factor">Done</a></p>
</section>
{{else}}
<section class="card">
<ol>
<li>Open your authenticator app and add an account, by scanning this code:
{{with .QR}}<p><img src="{{.}}" alt="QR code to add Supermarket to an authenticator app" width="246" height="246" class="qr"></p>{{end}}
<p class="help">Or type this key: <code>{{.Secret}}</code> (time-based).</p></li>
<li>Enter the six-digit code the app shows:
<form method="post" action="/settings/account/two-factor">
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<label>Code <input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9 ]{6,7}" required autofocus></label>
<button type="submit">Turn on two-factor sign-in</button>
</form>
</li>
</ol>
<p class="help">Then you get ten recovery codes, for when you don't have your phone. <a href="/settings/account">Cancel</a></p>
</section>
{{end}}
{{end}}{{template "settings-end"}}{{end}}