/web/account, offered to everyone, lists every browser and client signed in as you, with when each was last used, and signs any of them out, or all but the current one. It sets up, replaces and removes the second factor, and holds the password form, moved from the vault page. Administrators can sign a user out everywhere from the People page. The API gains GET and DELETE /api/v1/auth/sessions and DELETE /api/v1/auth/totp. Sessions are named by a digest of their token, never the token, and record when they were last used. Replacing or removing an active second factor now needs the password and a current code. Server version 0.10.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
341 lines
12 KiB
Go
341 lines
12 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"html/template"
|
|
"net/http"
|
|
"net/url"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"cc.tiredsysadmin.keeporg/internal/store"
|
|
"cc.tiredsysadmin.keeporg/internal/totp"
|
|
)
|
|
|
|
// The settings page at /web/account: who you are, how you sign in, and every
|
|
// device and browser signed in as you, each of which can be signed out from
|
|
// here. The rules are the functions in account.go, shared with the API.
|
|
|
|
// webAccount is what the settings page shows.
|
|
type webAccount struct {
|
|
Username string
|
|
Email string
|
|
ServerAdmin bool
|
|
Since string
|
|
Groups []webMembership
|
|
HasPassword bool
|
|
SSO string // the identity provider's host, when linked
|
|
TOTPOn bool
|
|
// TOTPKey and TOTPLink are set while an enrolment awaits its first code.
|
|
TOTPKey string
|
|
TOTPLink template.URL
|
|
Sessions []webSessionRow
|
|
}
|
|
|
|
type webMembership struct {
|
|
Name string
|
|
Role string
|
|
}
|
|
|
|
type webSessionRow struct {
|
|
ID string
|
|
Label string
|
|
Browser bool
|
|
Current bool
|
|
Created string
|
|
LastSeen string
|
|
Expires string
|
|
}
|
|
|
|
func (s *Server) accountView(sess *webSession) webAccount {
|
|
var v webAccount
|
|
s.st.Read(func(st *store.State) {
|
|
u := st.Users[sess.user.ID]
|
|
if u == nil {
|
|
return
|
|
}
|
|
v = webAccount{
|
|
Username: u.Username, Email: u.Email, ServerAdmin: u.ServerAdmin,
|
|
Since: u.CreatedAt.UTC().Format("2006-01-02"),
|
|
HasPassword: u.PassHash != "", TOTPOn: u.TOTPConfirmed,
|
|
}
|
|
if u.OIDCIssuer != "" {
|
|
v.SSO = u.OIDCIssuer
|
|
if iss, err := url.Parse(u.OIDCIssuer); err == nil && iss.Host != "" {
|
|
v.SSO = iss.Host
|
|
}
|
|
}
|
|
if u.TOTPSecret != "" && !u.TOTPConfirmed {
|
|
v.TOTPKey = groupKey(u.TOTPSecret)
|
|
// The otpauth: scheme is what authenticator apps register for;
|
|
// html/template would neutralise it, and the URI is built here
|
|
// from our own values.
|
|
v.TOTPLink = template.URL(totp.URI("KeepOrg", u.Username, u.TOTPSecret))
|
|
}
|
|
for _, m := range st.Memberships {
|
|
if m.UserID != u.ID {
|
|
continue
|
|
}
|
|
if g := st.Groups[m.GroupID]; g != nil {
|
|
v.Groups = append(v.Groups, webMembership{Name: g.Name, Role: string(m.Role)})
|
|
}
|
|
}
|
|
sort.Slice(v.Groups, func(i, j int) bool { return v.Groups[i].Name < v.Groups[j].Name })
|
|
for _, sv := range sessionsOf(st, u.ID, sess.token) {
|
|
v.Sessions = append(v.Sessions, webSessionRow{
|
|
ID: sv.ID, Label: sv.Label, Browser: sv.Browser, Current: sv.Current,
|
|
Created: sv.CreatedAt.UTC().Format("2006-01-02 15:04 UTC"),
|
|
LastSeen: ago(sv.LastSeenAt),
|
|
Expires: sv.ExpiresAt.UTC().Format("2006-01-02"),
|
|
})
|
|
}
|
|
})
|
|
return v
|
|
}
|
|
|
|
// groupKey spaces a base32 secret in fours, for typing into an app by hand.
|
|
func groupKey(k string) string {
|
|
var b strings.Builder
|
|
for i, r := range k {
|
|
if i > 0 && i%4 == 0 {
|
|
b.WriteByte(' ')
|
|
}
|
|
b.WriteRune(r)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// ago says how long ago t was, coarsely.
|
|
func ago(t time.Time) string {
|
|
d := time.Since(t)
|
|
switch {
|
|
case d < 2*time.Minute:
|
|
return "just now"
|
|
case d < time.Hour:
|
|
return fmt.Sprintf("%d minutes ago", int(d.Minutes()))
|
|
case d < 2*time.Hour:
|
|
return "an hour ago"
|
|
case d < 24*time.Hour:
|
|
return fmt.Sprintf("%d hours ago", int(d.Hours()))
|
|
case d < 48*time.Hour:
|
|
return "yesterday"
|
|
case d < 30*24*time.Hour:
|
|
return fmt.Sprintf("%d days ago", int(d.Hours()/24))
|
|
}
|
|
return t.UTC().Format("2006-01-02")
|
|
}
|
|
|
|
func (s *Server) handleWebAccount(w http.ResponseWriter, r *http.Request, sess *webSession) {
|
|
s.renderAccount(w, sess, "", "")
|
|
}
|
|
|
|
// handleWebAccountAction applies one control of the settings page.
|
|
func (s *Server) handleWebAccountAction(w http.ResponseWriter, r *http.Request, sess *webSession) {
|
|
var notice string
|
|
err := s.st.Update(func(st *store.State) error {
|
|
switch r.FormValue("action") {
|
|
case "revoke":
|
|
if err := revokeSession(st, sess.user.ID, r.FormValue("session")); err != nil {
|
|
return err
|
|
}
|
|
notice = "That device is signed out. It has to sign in again to sync."
|
|
case "revoke-others":
|
|
n := revokeOtherSessions(st, sess.user.ID, sess.token)
|
|
notice = fmt.Sprintf("Signed out %d other %s.", n, plural(n, "session", "sessions"))
|
|
case "password":
|
|
next := r.FormValue("new_password")
|
|
if next != r.FormValue("new_password2") {
|
|
return errors.New("the two new passwords do not match")
|
|
}
|
|
if err := changePassword(st, sess.user.Username, r.FormValue("current_password"),
|
|
r.FormValue("totp"), next, sess.token); err != nil {
|
|
return err
|
|
}
|
|
notice = "Password changed. Your other sessions were signed out."
|
|
case "totp-begin":
|
|
if _, err := beginTOTP(st, sess.user.ID, r.FormValue("password"), r.FormValue("totp")); err != nil {
|
|
return err
|
|
}
|
|
notice = "Add the key below to your authenticator app, then enter the code it shows."
|
|
case "totp-confirm":
|
|
if err := confirmTOTP(st, sess.user.ID, r.FormValue("code")); err != nil {
|
|
return err
|
|
}
|
|
notice = "Two-factor authentication is on. Signing in now asks for a one-time code."
|
|
case "totp-cancel":
|
|
cancelTOTP(st, sess.user.ID)
|
|
notice = "Setup cancelled. Nothing changed."
|
|
case "totp-disable":
|
|
if err := disableTOTP(st, sess.user.ID, r.FormValue("password"), r.FormValue("totp")); err != nil {
|
|
return err
|
|
}
|
|
notice = "Two-factor authentication is off."
|
|
default:
|
|
return errBadAction
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
s.renderAccount(w, sess, accountError(err), "")
|
|
return
|
|
}
|
|
// Signing out one's own browser from the list ends this session too.
|
|
if s.webUser(r) == nil {
|
|
s.setWebCookie(w, "", -time.Second)
|
|
http.Redirect(w, r, "/web", http.StatusFound)
|
|
return
|
|
}
|
|
s.renderAccount(w, sess, "", notice)
|
|
}
|
|
|
|
func accountError(err error) string {
|
|
switch {
|
|
case errors.Is(err, errReauth), errors.Is(err, errTOTPRequired):
|
|
return "Confirm with your password and your current one-time code."
|
|
case errors.Is(err, errTOTPInvalid):
|
|
return "That one-time code was rejected. Check the clock on the device that shows it."
|
|
case errors.Is(err, errBadCredentials):
|
|
return "The password is wrong."
|
|
case errors.Is(err, errNoSuchSession):
|
|
return "That session is already signed out."
|
|
}
|
|
return humanError(err)
|
|
}
|
|
|
|
func plural(n int, one, many string) string {
|
|
if n == 1 {
|
|
return one
|
|
}
|
|
return many
|
|
}
|
|
|
|
func (s *Server) renderAccount(w http.ResponseWriter, sess *webSession, errMsg, notice string) {
|
|
d := s.shell(sess, "Account", "Account")
|
|
d["A"], d["Error"], d["Notice"] = s.accountView(sess), errMsg, notice
|
|
render(w, accountTmpl, d)
|
|
}
|
|
|
|
var accountTmpl = template.Must(template.Must(pages.Clone()).Parse(`
|
|
{{define "body"}}
|
|
<h1>Account</h1>
|
|
<p class="sub">How you sign in, and everywhere you are signed in.</p>
|
|
{{if .Error}}<p class="err">{{.Error}}</p>{{end}}
|
|
{{if .Notice}}<p class="ok">{{.Notice}}</p>{{end}}
|
|
{{with .A}}
|
|
<fieldset><legend>You</legend>
|
|
<table><tbody>
|
|
<tr><th>Username</th><td class="name">{{.Username}}</td></tr>
|
|
{{if .Email}}<tr><th>Email</th><td>{{.Email}}</td></tr>{{end}}
|
|
<tr><th>Signs in with</th><td>
|
|
{{if .HasPassword}}<span class="tag">password</span>{{end}}
|
|
{{if .TOTPOn}}<span class="tag">one-time code</span>{{end}}
|
|
{{if .SSO}}<span class="tag">single sign-on</span> <small>via {{.SSO}}</small>{{end}}
|
|
</td></tr>
|
|
<tr><th>Role</th><td>{{if .ServerAdmin}}server administrator{{else}}member{{end}}</td></tr>
|
|
<tr><th>Groups</th><td>{{range $i, $g := .Groups}}{{if $i}}, {{end}}{{$g.Name}} <small>({{$g.Role}})</small>{{else}}none{{end}}</td></tr>
|
|
<tr><th>Member since</th><td>{{.Since}}</td></tr>
|
|
</tbody></table>
|
|
</fieldset>
|
|
|
|
<fieldset><legend>Signed-in devices</legend>
|
|
<p class="sub">Every browser and KeepOrg client signed in as you. Signing one out
|
|
stops it syncing at once; it has to sign in again.</p>
|
|
<div class="scroll"><table>
|
|
<thead><tr><th>Device</th><th>Last active</th><th>Signed in</th><th>Expires</th><th></th></tr></thead>
|
|
<tbody>
|
|
{{range .Sessions}}<tr>
|
|
<td class="name">{{if .Label}}{{.Label}}{{else}}unnamed{{end}}<br>
|
|
<span class="tag">{{if .Browser}}browser{{else}}app{{end}}</span>
|
|
{{if .Current}}<span class="tag">this browser</span>{{end}}</td>
|
|
<td>{{.LastSeen}}</td>
|
|
<td>{{.Created}}</td>
|
|
<td>{{.Expires}}</td>
|
|
<td>{{if not .Current}}<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="revoke">
|
|
<input type="hidden" name="session" value="{{.ID}}">
|
|
<button class="danger" type="submit">Sign out</button>
|
|
</form>{{end}}</td>
|
|
</tr>{{end}}
|
|
</tbody></table></div>
|
|
{{if gt (len .Sessions) 1}}
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="revoke-others">
|
|
<button class="destroy" type="submit">Sign out every other device</button>
|
|
</form>
|
|
{{end}}
|
|
</fieldset>
|
|
|
|
{{if .HasPassword}}
|
|
<fieldset><legend>Two-factor authentication</legend>
|
|
{{if .TOTPOn}}
|
|
<p class="sub">On. Signing in with your password also asks for a one-time code
|
|
from your authenticator app.</p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<div class="inline">
|
|
<div><label for="tf_password">Password</label>
|
|
<input id="tf_password" name="password" type="password" autocomplete="current-password" required></div>
|
|
<div><label for="tf_totp">Current one-time code</label>
|
|
<input id="tf_totp" name="totp" inputmode="numeric" autocomplete="one-time-code" required></div>
|
|
</div>
|
|
<div class="inline">
|
|
<button type="submit" name="action" value="totp-begin">Move to a new authenticator</button>
|
|
<button class="destroy" type="submit" name="action" value="totp-disable">Turn off</button>
|
|
</div>
|
|
</form>
|
|
{{else if .TOTPKey}}
|
|
<p class="sub">Add this key to an authenticator app such as Aegis, 2FAS or
|
|
Google Authenticator, then enter the six-digit code it shows.</p>
|
|
<p><code>{{.TOTPKey}}</code></p>
|
|
<p><a href="{{.TOTPLink}}">Open in an authenticator app on this device</a></p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="totp-confirm">
|
|
<label for="code">Code from the app</label>
|
|
<input id="code" name="code" inputmode="numeric" autocomplete="one-time-code" required>
|
|
<button type="submit">Turn on</button>
|
|
</form>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="totp-cancel">
|
|
<button class="secondary" type="submit">Cancel</button>
|
|
</form>
|
|
{{else}}
|
|
<p class="sub">Off. With it on, a stolen password is not enough to sign in:
|
|
each sign-in also needs a code from an app on your phone.</p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="totp-begin">
|
|
<button type="submit">Set up two-factor authentication</button>
|
|
</form>
|
|
{{end}}
|
|
</fieldset>
|
|
|
|
<fieldset><legend>Password</legend>
|
|
<p class="sub">The password you sign in with, not any vault's password.
|
|
Changing it signs out your other devices.</p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="password">
|
|
<label for="current_password">Current password</label>
|
|
<input id="current_password" name="current_password" type="password" autocomplete="current-password" required>
|
|
{{if .TOTPOn}}<label for="cp_totp">One-time code</label>
|
|
<input id="cp_totp" name="totp" inputmode="numeric" autocomplete="one-time-code" required>{{end}}
|
|
<label for="new_password">New password</label>
|
|
<input id="new_password" name="new_password" type="password" autocomplete="new-password" minlength="10" required>
|
|
<label for="new_password2">Repeat new password</label>
|
|
<input id="new_password2" name="new_password2" type="password" autocomplete="new-password" minlength="10" required>
|
|
<button type="submit">Change password</button>
|
|
</form>
|
|
</fieldset>
|
|
{{else}}
|
|
<p class="note">You sign in through single sign-on{{if .SSO}} at {{.SSO}}{{end}},
|
|
so your password and second factor are managed there, not here.</p>
|
|
{{end}}
|
|
{{end}}
|
|
{{end}}`))
|