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
Emails []emailKind // the emails they may choose
Photos bool // there's file storage for a photo
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, d.Emails, d.Photos = u, v.Member.Role, commonZones, emailsFor(v.Member), s.Files != nil
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"))
u.Emails = pickEmails(v.Member, r.PostForm["emails"])
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}})
}