patx/gitman

Add site timezone settings, verified password controls and final delete dialog

Commit 41e8c05 · patx · Nov 4 at 9:08PM

Changeset
41e8c05f0383dbaf2916260c13f924ae1dfb278a
Parents
1645f5ed08df4ce7e0f545c7de2bdebbc5d5cc95

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/app.py b/app.py
index 29a6949..82ff24f 100644
--- a/app.py
+++ b/app.py
@@ -20,6 +20,7 @@ import time
 import tempfile
 from socketserver import ThreadingMixIn
 from pathlib import Path, PurePosixPath
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
 from urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse
 from wsgiref.simple_server import WSGIServer
 
@@ -29,6 +30,98 @@ from html_links import rewrite_html_links
 
 import bleach
 import markdown
+TIMEZONE_CHOICES = {
+    'Etc/GMT+12': 'International Date Line West',
+    'Pacific/Pago_Pago': 'American Samoa',
+    'Pacific/Honolulu': 'HST — Hawaii',
+    'America/Anchorage': 'AKST / AKDT — Alaska',
+    'America/Los_Angeles': 'PST / PDT — Pacific Time (US & Canada)',
+    'America/Vancouver': 'Pacific Time — Vancouver',
+    'America/Phoenix': 'MST — Arizona',
+    'America/Denver': 'MST / MDT — Mountain Time (US & Canada)',
+    'America/Chicago': 'CST / CDT — Central Time (US & Canada)',
+    'America/Mexico_City': 'Mexico City',
+    'America/Guatemala': 'Central America',
+    'America/New_York': 'EST / EDT — Eastern Time (US & Canada)',
+    'America/Bogota': 'Colombia — Bogota',
+    'America/Lima': 'Peru — Lima',
+    'America/Caracas': 'Venezuela — Caracas',
+    'America/Halifax': 'AST / ADT — Atlantic Time (Canada)',
+    'America/La_Paz': 'Bolivia — La Paz',
+    'America/Santiago': 'Chile — Santiago',
+    'America/St_Johns': 'Newfoundland',
+    'America/Sao_Paulo': 'Brazil — Sao Paulo',
+    'America/Argentina/Buenos_Aires': 'Argentina — Buenos Aires',
+    'America/Nuuk': 'Greenland',
+    'Atlantic/Azores': 'Azores',
+    'Atlantic/Cape_Verde': 'Cape Verde',
+    'UTC': 'UTC — Coordinated Universal Time',
+    'Europe/London': 'GMT / BST — London',
+    'Europe/Dublin': 'Ireland — Dublin',
+    'Europe/Lisbon': 'Portugal — Lisbon',
+    'Africa/Casablanca': 'Morocco — Casablanca',
+    'Africa/Lagos': 'WAT — West Africa',
+    'Europe/Paris': 'CET / CEST — Paris',
+    'Europe/Berlin': 'CET / CEST — Berlin',
+    'Europe/Rome': 'Italy — Rome',
+    'Europe/Madrid': 'Spain — Madrid',
+    'Europe/Zurich': 'Switzerland — Zurich',
+    'Europe/Athens': 'Greece — Athens',
+    'Europe/Helsinki': 'Finland — Helsinki',
+    'Europe/Kyiv': 'Ukraine — Kyiv',
+    'Europe/Bucharest': 'Romania — Bucharest',
+    'Africa/Cairo': 'Egypt — Cairo',
+    'Africa/Johannesburg': 'SAST — South Africa',
+    'Africa/Nairobi': 'EAT — East Africa',
+    'Europe/Istanbul': 'Turkey — Istanbul',
+    'Europe/Moscow': 'MSK — Moscow',
+    'Asia/Jerusalem': 'Israel — Jerusalem',
+    'Asia/Beirut': 'Lebanon — Beirut',
+    'Asia/Riyadh': 'Arabia — Riyadh',
+    'Asia/Baghdad': 'Iraq — Baghdad',
+    'Asia/Tehran': 'Iran — Tehran',
+    'Asia/Dubai': 'GST — Dubai',
+    'Asia/Baku': 'Azerbaijan — Baku',
+    'Asia/Yerevan': 'Armenia — Yerevan',
+    'Asia/Kabul': 'Afghanistan — Kabul',
+    'Asia/Karachi': 'PKT — Pakistan',
+    'Asia/Tashkent': 'Uzbekistan — Tashkent',
+    'Asia/Kolkata': 'IST — India (New Delhi, Mumbai, Kolkata)',
+    'Asia/Colombo': 'Sri Lanka',
+    'Asia/Kathmandu': 'NPT — Nepal',
+    'Asia/Dhaka': 'Bangladesh — Dhaka',
+    'Asia/Almaty': 'Kazakhstan — Almaty',
+    'Asia/Yangon': 'Myanmar — Yangon',
+    'Asia/Bangkok': 'Thailand — Bangkok',
+    'Asia/Ho_Chi_Minh': 'Vietnam',
+    'Asia/Jakarta': 'Western Indonesia — Jakarta',
+    'Asia/Shanghai': 'China — Beijing, Shanghai',
+    'Asia/Hong_Kong': 'HKT — Hong Kong',
+    'Asia/Singapore': 'SGT — Singapore',
+    'Asia/Manila': 'PHT — Philippines',
+    'Asia/Taipei': 'Taiwan — Taipei',
+    'Asia/Kuala_Lumpur': 'MYT — Malaysia',
+    'Australia/Perth': 'AWST — Perth',
+    'Asia/Tokyo': 'JST — Japan (Tokyo)',
+    'Asia/Seoul': 'KST — South Korea (Seoul)',
+    'Asia/Yakutsk': 'Yakutsk',
+    'Australia/Darwin': 'ACST — Darwin',
+    'Australia/Adelaide': 'ACST / ACDT — Adelaide',
+    'Australia/Brisbane': 'AEST — Brisbane',
+    'Australia/Sydney': 'AEST / AEDT — Sydney, Melbourne',
+    'Australia/Hobart': 'Tasmania — Hobart',
+    'Australia/Lord_Howe': 'Lord Howe Island',
+    'Pacific/Guam': 'Guam',
+    'Pacific/Port_Moresby': 'Papua New Guinea',
+    'Pacific/Noumea': 'New Caledonia',
+    'Pacific/Guadalcanal': 'Solomon Islands',
+    'Pacific/Auckland': 'NZST / NZDT — New Zealand',
+    'Pacific/Fiji': 'FJT — Fiji',
+    'Pacific/Chatham': 'Chatham Islands',
+    'Pacific/Tongatapu': 'Tonga',
+    'Pacific/Apia': 'Samoa',
+    'Pacific/Kiritimati': 'Kiribati',
+}
 try:
     import dns.exception
     import dns.resolver
@@ -559,6 +652,7 @@ def ensure_user_profile_columns(conn):
     profile_columns = {
         "session_version": "ALTER TABLE users ADD COLUMN session_version INTEGER NOT NULL DEFAULT 0",
         "theme_preference": "ALTER TABLE users ADD COLUMN theme_preference TEXT NOT NULL DEFAULT 'auto' CHECK (theme_preference IN ('auto', 'light', 'dark'))",
+        "timezone_preference": "ALTER TABLE users ADD COLUMN timezone_preference TEXT NOT NULL DEFAULT 'UTC'",
         "display_name": "ALTER TABLE users ADD COLUMN display_name TEXT NOT NULL DEFAULT ''",
         "bio": "ALTER TABLE users ADD COLUMN bio TEXT NOT NULL DEFAULT ''",
         "website": "ALTER TABLE users ADD COLUMN website TEXT NOT NULL DEFAULT ''",
@@ -1048,9 +1142,35 @@ def render(template_name, **context):
     context.setdefault("current_url_with_page", current_url_with_page)
     context.setdefault("current_url_with_params", current_url_with_params)
     context.setdefault("ref_option_label", ref_option_label)
+    zone = context['user']['timezone_preference'] if context['user'] else 'UTC'
+    context.setdefault("format_timestamp", lambda value: format_timestamp(value, zone))
+    context.setdefault("timezones", timezone_options() if template_name == "edit_profile.tpl" else {})
     return rewrite_html_links(template(template_name, **context), site_url=request.url)
 
 
+def timezone_options():
+    now = dt.datetime.now(dt.timezone.utc)
+    options = []
+    for key, label in TIMEZONE_CHOICES.items():
+        minutes = int(now.astimezone(ZoneInfo(key)).utcoffset().total_seconds() // 60)
+        sign = '+' if minutes >= 0 else '-'
+        hours, remaining = divmod(abs(minutes), 60)
+        options.append((minutes, label, key, f"(UTC{sign}{hours:02}:{remaining:02}) {label}"))
+    return {key: label for _, _, key, label in sorted(options)}
+
+
+def format_timestamp(value, timezone='UTC'):
+    if not value:
+        return ''
+    try:
+        moment = dt.datetime.fromisoformat(str(value).replace('Z', '+00:00'))
+        if moment.tzinfo is None:
+            moment = moment.replace(tzinfo=dt.timezone.utc)
+        return moment.astimezone(ZoneInfo(timezone)).isoformat(timespec='seconds').replace('+00:00', 'Z')
+    except (ValueError, ZoneInfoNotFoundError):
+        return str(value)
+
+
 def login_user(user):
     response.set_cookie(
         "session",
@@ -5240,6 +5360,37 @@ def edit_profile():
         return render("edit_profile.tpl", profile=values, error=str(exc))
 
 
[email protected]("/settings/site")
+def save_site_settings():
+    user = require_login()
+    theme = request.forms.get('theme_preference', user['theme_preference']).strip()
+    timezone = request.forms.get('timezone_preference', user['timezone_preference']).strip()
+    if theme not in {'auto', 'light', 'dark'} or timezone not in TIMEZONE_CHOICES:
+        response.status = 400
+        return render('edit_profile.tpl', profile=user, error='Choose a valid theme and time zone.')
+    with db_connect() as conn:
+        conn.execute('UPDATE users SET theme_preference = ?, timezone_preference = ? WHERE id = ?', (theme, timezone, user['id']))
+    refreshed = get_user_by_id(user['id'])
+    request.environ['gitman.user'] = refreshed
+    return render('edit_profile.tpl', profile=refreshed, notice='Site settings updated.')
+
+
[email protected]("/settings/password/check")
+def check_current_password():
+    user = require_login()
+    identifier = str(user['id'])
+    headers = {'Cache-Control': 'no-store'}
+    if rate_limit_blocked('password-change', identifier):
+        return HTTPResponse(json.dumps({'valid': False, 'error': 'Too many attempts. Try again later.'}), status=429, content_type='application/json', headers=headers)
+    current = request.forms.get('current_password', '')
+    valid = bool(current) and len(current) <= 1024 and verify_password(current, user['password_hash'])
+    if valid:
+        clear_auth_failures('password-change', identifier)
+    else:
+        record_auth_failure('password-change', identifier)
+    return HTTPResponse(json.dumps({'valid': valid}), content_type='application/json', headers=headers)
+
+
 @app.post("/settings/password")
 def change_password():
     user = require_login()
diff --git a/static/password-settings.js b/static/password-settings.js
new file mode 100644
index 0000000..033af1a
--- /dev/null
+++ b/static/password-settings.js
@@ -0,0 +1,65 @@
+(() => {
+  document.querySelectorAll('form[data-password-settings]').forEach((form) => {
+    const current = form.elements.current_password;
+    const next = form.elements.new_password;
+    const confirmation = form.elements.confirm_password;
+    const button = form.querySelector('button[type="submit"]');
+    const status = form.querySelector('[data-current-password-status]');
+    const hint = form.querySelector('#password-hint');
+    const defaultHint = hint.textContent;
+    let verified = null;
+    let requestId = 0;
+    current.value = '';
+    const ready = () => Boolean(verified && verified === current.value && next.value.length >= 8 && next.value.length <= 1024 && next.value !== current.value && next.value === confirmation.value);
+    const sync = () => {
+      button.disabled = !ready();
+      hint.textContent = next.value && next.value.length < 8 ? 'Use at least 8 characters for your new password.'
+        : next.value && next.value === current.value ? 'Choose a different password from your current one.'
+        : confirmation.value && next.value !== confirmation.value ? 'New passwords do not match.' : defaultHint;
+    };
+    const verify = async () => {
+      if (!current.value || current.value === verified) return;
+      const password = current.value;
+      const id = ++requestId;
+      status.textContent = 'Checking current password…';
+      const data = new FormData();
+      data.set('current_password', password);
+      data.set('_csrf_token', form.elements._csrf_token.value);
+      try {
+        const response = await fetch('/settings/password/check', { method: 'POST', body: data, headers: { Accept: 'application/json' } });
+        const result = await response.json();
+        if (id !== requestId || current.value !== password) return;
+        verified = response.ok && result.valid ? password : null;
+        status.textContent = verified ? 'Current password verified.' : result.error || 'Current password is incorrect.';
+      } catch (_) {
+        if (id !== requestId) return;
+        verified = null;
+        status.textContent = 'Unable to verify your password. Leave this field again to retry.';
+      }
+      sync();
+    };
+    current.addEventListener('focus', () => { current.readOnly = false; });
+    current.addEventListener('blur', () => { current.readOnly = true; verify(); });
+    current.addEventListener('input', () => {
+      requestId += 1;
+      verified = null;
+      status.textContent = 'Leave this field to verify your current password.';
+      sync();
+    });
+    next.addEventListener('input', sync);
+    next.addEventListener('change', sync);
+    confirmation.addEventListener('input', sync);
+    confirmation.addEventListener('change', sync);
+    form.addEventListener('submit', (event) => { if (!ready()) event.preventDefault(); });
+    window.addEventListener('pageshow', (event) => {
+      if (!event.persisted) return;
+      current.value = next.value = confirmation.value = '';
+      current.readOnly = true;
+      verified = null;
+      requestId += 1;
+      status.textContent = 'Enter your current password, then leave this field to verify it.';
+      sync();
+    });
+    sync();
+  });
+})();
diff --git a/static/save-on-change.js b/static/save-on-change.js
index 38e1506..5694588 100644
--- a/static/save-on-change.js
+++ b/static/save-on-change.js
@@ -30,9 +30,27 @@
     const input = form.querySelector('input[name="confirm_name"]');
     const button = form.querySelector('button[type="submit"]');
     const sync = () => { button.disabled = input.value.trim() !== form.dataset.confirmDelete; };
+    const dialog = document.querySelector('[data-delete-confirmation]');
+    let confirmed = false;
     input.addEventListener('input', sync);
     input.addEventListener('change', sync);
     window.addEventListener('pageshow', sync);
+    form.addEventListener('submit', (event) => {
+      if (input.value.trim() !== form.dataset.confirmDelete) {
+        event.preventDefault();
+      } else if (!confirmed) {
+        event.preventDefault();
+        dialog.showModal();
+        dialog.querySelector('[data-delete-cancel]').focus();
+      }
+      confirmed = false;
+    });
+    dialog.querySelector('[data-delete-cancel]').addEventListener('click', () => dialog.close());
+    dialog.querySelector('[data-delete-final]').addEventListener('click', () => {
+      dialog.close();
+      confirmed = true;
+      form.requestSubmit(button);
+    });
     sync();
   });
 })();
diff --git a/static/styles.css b/static/styles.css
index 43acada..a9fc53b 100644
--- a/static/styles.css
+++ b/static/styles.css
@@ -535,6 +535,13 @@ th { color: var(--ink); font-weight: 700; }
 .notice { margin-bottom: 1rem; color: var(--text); }
 
 .settings-page { width: 100%; }
+.confirmation-dialog { width: min(32rem, calc(100% - 3rem)); padding: 1.5rem; border: 1px solid var(--surface-border); border-radius: 8px; background: var(--page-bg); color: var(--text); }
+.confirmation-dialog::backdrop { background: rgb(0 0 0 / .65); }
+.dialog-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .75rem; margin-top: 1.5rem; }
+.timezone-field > label { margin-bottom: .5rem; }
+.timezone-menu { position: fixed; right: auto; z-index: 40; max-width: none; }
+.timezone-option { display: block; width: 100%; min-height: 40px; padding: .5rem .75rem; border: 0; border-radius: 4px; background: transparent; color: var(--ink); text-align: left; font-weight: 400; line-height: 1.4; }
+.timezone-option:hover, .timezone-option.active { background: var(--chip); color: var(--ink); }
 .settings-cards { display: grid; gap: 1.5rem; margin-top: 1.5rem; }
 .settings-card > :last-child { margin-bottom: 0; }
 .settings-card > form { margin-block: 1.25rem; }
diff --git a/static/timezone-picker.js b/static/timezone-picker.js
new file mode 100644
index 0000000..db56094
--- /dev/null
+++ b/static/timezone-picker.js
@@ -0,0 +1,115 @@
+(() => {
+  document.querySelectorAll('[data-timezone-picker]').forEach((field, index) => {
+    const select = field.querySelector('select');
+    const options = Array.from(select.options);
+    const input = document.createElement('input');
+    input.type = 'text';
+    input.id = `timezone-search-${index}`;
+    input.autocomplete = 'off';
+    input.spellcheck = false;
+    input.setAttribute('role', 'combobox');
+    input.setAttribute('aria-autocomplete', 'list');
+    input.setAttribute('aria-expanded', 'false');
+    input.setAttribute('aria-describedby', 'timezone-help');
+    input.placeholder = 'Search time zones';
+    const menu = document.createElement('div');
+    menu.id = `timezone-options-${index}`;
+    menu.className = 'repo-search-menu timezone-menu';
+    menu.setAttribute('role', 'listbox');
+    menu.setAttribute('aria-label', 'Time zones');
+    menu.hidden = true;
+    input.setAttribute('aria-controls', menu.id);
+    field.querySelector('label').htmlFor = input.id;
+    select.hidden = true;
+    field.append(input);
+    document.body.append(menu);
+    let matches = [];
+    let active = -1;
+    const selectedLabel = () => select.selectedOptions[0]?.textContent || '';
+    input.value = selectedLabel();
+    const close = () => {
+      menu.hidden = true;
+      input.value = selectedLabel();
+      input.setAttribute('aria-expanded', 'false');
+      input.removeAttribute('aria-activedescendant');
+    };
+    const position = () => {
+      const rect = input.getBoundingClientRect();
+      const below = innerHeight - rect.bottom - 12;
+      const above = rect.top - 12;
+      const placeAbove = below < 180 && above > below;
+      menu.style.width = `${Math.min(rect.width, innerWidth - 32)}px`;
+      menu.style.maxHeight = `${Math.max(48, Math.min(288, placeAbove ? above : below))}px`;
+      menu.style.left = `${Math.max(16, Math.min(rect.left, innerWidth - menu.offsetWidth - 16))}px`;
+      menu.style.top = `${placeAbove ? Math.max(8, rect.top - menu.offsetHeight - 4) : rect.bottom + 4}px`;
+    };
+    const highlight = (value) => {
+      active = value;
+      Array.from(menu.querySelectorAll('[role="option"]')).forEach((button, i) => {
+        button.classList.toggle('active', i === active);
+        if (i === active) {
+          input.setAttribute('aria-activedescendant', button.id);
+          button.scrollIntoView({ block: 'nearest' });
+        }
+      });
+    };
+    const choose = (option) => {
+      select.value = option.value;
+      select.dispatchEvent(new Event('change', { bubbles: true }));
+      close();
+    };
+    const render = (query) => {
+      const tokens = query.toLowerCase().split(/\s+/).filter(Boolean);
+      matches = options.filter((option) => {
+        const name = `${option.textContent.replace(/^\([^)]*\)\s*/, '')} ${option.value}`.toLowerCase();
+        return tokens.every((token) => /^[a-z]{1,3}$/.test(token)
+          ? name.split(/[^a-z0-9]+/).some((word) => word.startsWith(token))
+          : (/[+-]\d/.test(token) ? option.textContent.toLowerCase() : name).includes(token));
+      });
+      menu.replaceChildren();
+      matches.forEach((option, i) => {
+        const button = document.createElement('button');
+        button.type = 'button';
+        button.tabIndex = -1;
+        button.id = `${menu.id}-${i}`;
+        button.className = 'timezone-option';
+        button.setAttribute('role', 'option');
+        button.setAttribute('aria-selected', String(option.selected));
+        button.textContent = option.textContent;
+        button.addEventListener('mousedown', (event) => event.preventDefault());
+        button.addEventListener('click', () => choose(option));
+        menu.append(button);
+      });
+      if (!matches.length) {
+        const empty = document.createElement('p');
+        empty.className = 'ref-picker-empty';
+        empty.setAttribute('role', 'status');
+        empty.textContent = 'No time zones found.';
+        menu.append(empty);
+      }
+      menu.hidden = false;
+      input.setAttribute('aria-expanded', 'true');
+      position();
+      const selected = matches.findIndex((option) => option.selected);
+      highlight(selected >= 0 ? selected : matches.length ? 0 : -1);
+    };
+    input.addEventListener('focus', () => { input.select(); render(''); });
+    input.addEventListener('click', () => { if (menu.hidden) { input.select(); render(''); } });
+    input.addEventListener('input', () => render(input.value));
+    input.addEventListener('blur', close);
+    input.addEventListener('keydown', (event) => {
+      if (event.key === 'Escape') { event.preventDefault(); close(); }
+      else if (event.key === 'Enter') {
+        event.preventDefault();
+        if (!menu.hidden && matches[active]) choose(matches[active]);
+      } else if (['ArrowDown', 'ArrowUp'].includes(event.key)) {
+        event.preventDefault();
+        if (menu.hidden) render('');
+        else if (matches.length) highlight(Math.max(0, Math.min(matches.length - 1, active + (event.key === 'ArrowDown' ? 1 : -1))));
+      }
+    });
+    document.addEventListener('pointerdown', (event) => { if (!field.contains(event.target) && !menu.contains(event.target)) close(); });
+    window.addEventListener('resize', () => { if (!menu.hidden) position(); });
+    window.addEventListener('scroll', () => { if (!menu.hidden) position(); }, { capture: true, passive: true });
+  });
+})();
diff --git a/templates/activity_card_content.tpl b/templates/activity_card_content.tpl
index b6e152d..a0ba3df 100644
--- a/templates/activity_card_content.tpl
+++ b/templates/activity_card_content.tpl
@@ -3,7 +3,7 @@
   % if show_repo_context:
     in {{action['repo_owner_username']}}/{{action['repo_name']}} ·
   % end
-  {{action['occurred_at']}}
+  {{format_timestamp(action['occurred_at'])}}
 </span>
 % if action['detail']:
   <span class="activity-detail">{{!render_markdown_links(action['detail'], links=False)}}</span>
diff --git a/templates/base.tpl b/templates/base.tpl
index ab2f649..1b61cf2 100644
--- a/templates/base.tpl
+++ b/templates/base.tpl
@@ -20,7 +20,7 @@
   % if not get('landing', False) and theme != 'light':
     <link rel="stylesheet" href="/static/vendor/highlight.js/github-dark.min.css"{{!' media="(prefers-color-scheme: dark)"' if theme == 'auto' else ''}}>
   % end
-  <link rel="stylesheet" href="/static/styles.css?v=23">
+  <link rel="stylesheet" href="/static/styles.css?v=24">
 </head>
 <body class="{{'landing-page' if get('landing', False) else ''}}">
   % if not get("landing", False):
@@ -52,6 +52,7 @@
             <a href="/{{user['username']}}">View Profile</a>
             <a href="/new">New Repository</a>
             <a href="/settings">Settings</a>
+            <a href="/logout">Log out</a>
           </div>
         </details>
       % else:
@@ -93,7 +94,9 @@
   <script src="/static/mentions.js?v=2" defer></script>
   % if user:
     <script src="/static/contributor-picker.js?v=2" defer></script>
-    <script src="/static/save-on-change.js?v=2" defer></script>
+    <script src="/static/save-on-change.js?v=4" defer></script>
+    <script src="/static/password-settings.js?v=1" defer></script>
+    <script src="/static/timezone-picker.js?v=1" defer></script>
   % end
   % if user:
     <script src="/static/notifications.js?v=2" defer></script>
diff --git a/templates/comment.tpl b/templates/comment.tpl
index 1e886a6..9b669c3 100644
--- a/templates/comment.tpl
+++ b/templates/comment.tpl
@@ -1,7 +1,7 @@
 <article class="comment">
   <header class="comment-meta">
     <strong><a href="/{{comment["author_username"]}}">@{{comment["author_username"]}}</a></strong>
-    <small class="muted">{{comment["created_at"]}}</small>
+    <small class="muted">{{format_timestamp(comment["created_at"])}}</small>
   </header>
   <div class="comment-body markdown-body">{{!render_markdown(comment["body"])}}</div>
 </article>
diff --git a/templates/commit_detail.tpl b/templates/commit_detail.tpl
index 9768983..11dba5d 100644
--- a/templates/commit_detail.tpl
+++ b/templates/commit_detail.tpl
@@ -12,7 +12,7 @@
 
 <section class="panel">
   <h2>{{commit["description"].splitlines()[0] if commit["description"] else commit["short_node"]}}</h2>
-  <p class="muted">Commit {{commit["short_node"]}} · {{commit["author"]}} · {{commit["date"]}}</p>
+  <p class="muted">Commit {{commit["short_node"]}} · {{commit["author"]}} · {{format_timestamp(commit["date"])}}</p>
   <dl class="meta-list">
     <dt>Changeset</dt>
     <dd>
diff --git a/templates/commits.tpl b/templates/commits.tpl
index f285194..10f4bda 100644
--- a/templates/commits.tpl
+++ b/templates/commits.tpl
@@ -18,7 +18,7 @@
         <li>
           <a class="feed-card" href="{{url_with_ref('/' + repo['owner_username'] + '/' + repo['name'] + '/commits/' + commit['node'], selected_ref)}}">
             <span class="activity-title"><strong>{{commit['summary']}}</strong></span>
-            <span class="muted"><code>{{commit['short_node']}}</code> · {{commit['author']}} · {{commit['date']}}</span>
+            <span class="muted"><code>{{commit['short_node']}}</code> · {{commit['author']}} · {{format_timestamp(commit['date'])}}</span>
           </a>
         </li>
       % end
diff --git a/templates/edit_profile.tpl b/templates/edit_profile.tpl
index d604e52..521be3a 100644
--- a/templates/edit_profile.tpl
+++ b/templates/edit_profile.tpl
@@ -22,15 +22,31 @@
           Website
           <input name="website" value="{{profile['website']}}" placeholder="https://example.com" maxlength="255">
         </label>
+        <button class="button" type="submit">Save profile</button>
+      </form>
+    </section>
+    <section class="settings-card" aria-labelledby="site-settings-title">
+      <h2 id="site-settings-title">Site settings</h2>
+      <form method="post" action="/settings/site" data-save-on-change>
+        {{!csrf_field()}}
         <label>
           Theme
           <select name="theme_preference">
             % for value, label in [('auto', 'Auto (use system setting)'), ('light', 'Light'), ('dark', 'Dark')]:
-              <option value="{{value}}" {{'selected' if profile['theme_preference'] == value else ''}}>{{label}}</option>
+              <option value="{{value}}" {{'selected' if user['theme_preference'] == value else ''}}>{{label}}</option>
             % end
           </select>
         </label>
-        <button class="button" type="submit">Save profile</button>
+        <div class="timezone-field" data-timezone-picker>
+          <label for="timezone-value">Time zone</label>
+          <select id="timezone-value" name="timezone_preference" aria-describedby="timezone-help">
+            % for zone, label in timezones.items():
+              <option value="{{zone}}" {{'selected' if user['timezone_preference'] == zone else ''}}>{{label}}</option>
+            % end
+          </select>
+        </div>
+        <p id="timezone-help" class="muted">Dates and times across GitMan use this time zone, including daylight saving time.</p>
+        <button class="button" type="submit">Save site settings</button>
       </form>
     </section>
     <section class="settings-card" aria-labelledby="password-settings-title">
@@ -38,13 +54,16 @@
       % if get('password_error'):
         <p class="alert" role="alert">{{password_error}}</p>
       % end
-      <form method="post" action="/settings/password">
+      <form method="post" action="/settings/password" data-password-settings>
         {{!csrf_field()}}
         <input type="text" name="username" value="{{user['username']}}" autocomplete="username" hidden>
-        <label>
-          Current password
-          <input type="password" name="current_password" autocomplete="current-password" maxlength="1024" required>
-        </label>
+        <div>
+          <label>
+            Current password
+            <input type="password" name="current_password" autocomplete="off" data-lpignore="true" data-1p-ignore="true" maxlength="1024" required readonly aria-describedby="current-password-status">
+          </label>
+          <p id="current-password-status" class="field-help" role="status" data-current-password-status>Enter your current password, then leave this field to verify it.</p>
+        </div>
         <label>
           New password
           <input type="password" name="new_password" autocomplete="new-password" minlength="8" maxlength="1024" required aria-describedby="password-hint">
@@ -54,12 +73,8 @@
           <input type="password" name="confirm_password" autocomplete="new-password" minlength="8" maxlength="1024" required>
         </label>
         <p class="muted" id="password-hint">At least 8 characters. Other browser sessions will be signed out.</p>
-        <button class="button" type="submit">Change password</button>
+        <button class="button" type="submit" disabled>Change password</button>
       </form>
     </section>
   </div>
-  <nav class="settings-back" aria-label="Account actions">
-    <a href="/{{profile['username']}}">Back to profile</a>
-    <a href="/logout">Log out</a>
-  </nav>
 </section>
diff --git a/templates/issue_detail.tpl b/templates/issue_detail.tpl
index 02921dd..8722cff 100644
--- a/templates/issue_detail.tpl
+++ b/templates/issue_detail.tpl
@@ -14,7 +14,7 @@
   <div class="panel-heading">
     <div>
       <h2>(#{{issue["number"]}}) {{!render_mentions(issue["title"])}}</h2>
-      <p class="muted"><strong>{{issue["status"]}}</strong> by {{issue["author_username"]}} on {{issue["created_at"]}}</p>
+      <p class="muted"><strong>{{issue["status"]}}</strong> by {{issue["author_username"]}} on {{format_timestamp(issue["created_at"])}}</p>
     </div>
     % if can_maintain:
       <form method="post">
diff --git a/templates/issues.tpl b/templates/issues.tpl
index 93a04b8..4bc41ac 100644
--- a/templates/issues.tpl
+++ b/templates/issues.tpl
@@ -41,7 +41,7 @@
           <li>
             <a class="feed-card" href="/{{repo['owner_username']}}/{{repo['name']}}/issues/{{issue['number']}}">
               <span class="activity-title"><strong>#{{issue['number']}} {{issue['title']}}</strong></span>
-              <span class="muted"><strong>{{issue['status']}}</strong> by {{issue['author_username']}} on {{issue['created_at']}}</span>
+              <span class="muted"><strong>{{issue['status']}}</strong> by {{issue['author_username']}} on {{format_timestamp(issue['created_at'])}}</span>
             </a>
           </li>
         % end
diff --git a/templates/profile.tpl b/templates/profile.tpl
index 012c1f5..60edfbd 100644
--- a/templates/profile.tpl
+++ b/templates/profile.tpl
@@ -10,7 +10,7 @@
   % end
   </h1>
   <p class="muted"><small>
-    Joined {{profile_user["created_at"]}}
+    Joined {{format_timestamp(profile_user["created_at"])}}
   </small></p>
   % if profile_user["bio"]:
     <div class="markdown-body profile-bio">{{!render_markdown(profile_user["bio"])}}</div>
@@ -44,7 +44,7 @@
         <a class="feed-card repo-card" href="/{{repo['owner_username']}}/{{repo['name']}}">
           <span class="activity-title"><strong>{{repo['owner_username']}}/{{repo['name']}}</strong></span>
           <span class="activity-detail">{{!render_markdown_links(repo['description'], links=False) or 'No description yet.'}}</span>
-          <span class="muted">Updated {{repo['updated_at']}} · {{repo['star_count']}} stars</span>
+          <span class="muted">Updated {{format_timestamp(repo['updated_at'])}} · {{repo['star_count']}} stars</span>
         </a>
       % end
     </div>
diff --git a/templates/pull_request_detail.tpl b/templates/pull_request_detail.tpl
index 8df5005..d9a1071 100644
--- a/templates/pull_request_detail.tpl
+++ b/templates/pull_request_detail.tpl
@@ -14,7 +14,7 @@
   <div class="panel-heading">
     <div>
       <h2>(#{{pr["number"]}}) {{!render_mentions(pr["title"])}}</h2>
-      <p class="muted"><strong>{{pr["status"]}}</strong> <small>(created by <a href="/{{pr["author_username"]}}">{{pr["author_username"]}}</a> on {{pr["created_at"]}})</small></p>
+      <p class="muted"><strong>{{pr["status"]}}</strong> <small>(created by <a href="/{{pr["author_username"]}}">{{pr["author_username"]}}</a> on {{format_timestamp(pr["created_at"])}})</small></p>
       <p class="muted"><a href="/{{pr["source_owner_username"]}}/{{pr["source_repo_name"]}}">{{pr["source_owner_username"]}}/{{pr["source_repo_name"]}}</a> into <a href="/{{pr["target_owner_username"]}}/{{pr["target_repo_name"]}}">{{pr["target_owner_username"]}}/{{pr["target_repo_name"]}}</a></p>
       <p class="muted">{{format_ref_label(pr["source_ref_type"], pr["source_ref_name"])}} into {{format_ref_label(pr["target_ref_type"], pr["target_ref_name"])}}</p>
     </div>
@@ -39,7 +39,7 @@
     <p class="empty">No description.</p>
   % end
   % if pr["status"] == "merged":
-    <p class="notice">Merged by {{pr["merged_by_username"] or "unknown"}} on {{pr["merged_at"]}} as <code>{{pr["merge_node"]}}</code>.</p>
+    <p class="notice">Merged by {{pr["merged_by_username"] or "unknown"}} on {{format_timestamp(pr["merged_at"])}} as <code>{{pr["merge_node"]}}</code>.</p>
   % end
 </section>
 
diff --git a/templates/reference_card.tpl b/templates/reference_card.tpl
index d4a4837..2917726 100644
--- a/templates/reference_card.tpl
+++ b/templates/reference_card.tpl
@@ -2,7 +2,7 @@
   <a class="reference-main" href="/{{repo['owner_username']}}/{{repo['name']}}/commits/{{reference['short_node']}}">
     <span class="activity-title"><strong>{{reference['name']}}</strong></span>
     <span class="activity-detail">{{reference['summary']}}</span>
-    <span class="muted"><code>{{reference['short_node']}}</code> · {{reference['date']}}</span>
+    <span class="muted"><code>{{reference['short_node']}}</code> · {{format_timestamp(reference['date'])}}</span>
   </a>
   <nav class="reference-actions" aria-label="Actions for {{reference['name']}}">
     <a href="{{url_with_ref('/' + repo['owner_username'] + '/' + repo['name'] + '/src', reference, True)}}">Browse code</a>
diff --git a/templates/repo_settings.tpl b/templates/repo_settings.tpl
index 7e10fb1..2165e84 100644
--- a/templates/repo_settings.tpl
+++ b/templates/repo_settings.tpl
@@ -90,7 +90,7 @@
             <small class="muted">{{custom_domain["status"]}}</small>
           % end
           % if custom_domain and custom_domain["verified_at"]:
-            <small class="notice">@{{custom_domain["verified_at"]}}.</small>
+            <small class="notice">@{{format_timestamp(custom_domain["verified_at"])}}.</small>
           % end
         </p>
         % if not pages_settings["custom_domain_ready"]:
@@ -141,3 +141,11 @@
 </section>
   </div>
 </section>
+<dialog class="confirmation-dialog" data-delete-confirmation aria-labelledby="delete-confirmation-title" aria-describedby="delete-confirmation-description">
+  <h2 id="delete-confirmation-title">Delete {{repo['owner_username']}}/{{repo['name']}}?</h2>
+  <p id="delete-confirmation-description">This permanently deletes the repository, its issues, pull requests, and Git data. This cannot be undone.</p>
+  <div class="dialog-actions">
+    <button type="button" data-delete-cancel>Cancel</button>
+    <button class="button danger" type="button" data-delete-final>Delete permanently</button>
+  </div>
+</dialog>
diff --git a/tests/test_app.py b/tests/test_app.py
index 17e8b0c..3f7dfcb 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -2854,6 +2854,59 @@ def test_git_upload_spooling_stops_at_bound_without_declared_length():
         gitman.spool_request_body(BytesIO(b'x' * 1025), max_bytes=1024)
 
 
+def test_site_settings_persist_timezone_and_localize_dates(isolated_app):
+    owner = create_user('alice')
+    isolated_app.create_repository(owner, 'demo', '')
+    repo = isolated_app.get_repo('alice', 'demo')
+    with isolated_app.db_connect() as conn:
+        conn.execute("UPDATE users SET created_at='2026-01-08T02:29:44Z' WHERE id=?", (owner['id'],))
+        conn.execute("INSERT INTO issues (repo_id,author_id,number,title,body,status,created_at,updated_at) VALUES (?,?,1,'Summer issue','','open','2026-05-08T02:29:44Z','2026-05-08T02:29:44Z')", (repo['id'], owner['id']))
+    client = WsgiClient(isolated_app.app)
+    login_client(client, 'alice')
+    saved = client.post('/settings/site', {'theme_preference': 'dark', 'timezone_preference': 'America/New_York'})
+    assert saved.status_code == 200
+    assert 'Site settings updated.' in saved.text
+    assert saved.text.index('id="profile-settings-title"') < saved.text.index('id="site-settings-title"') < saved.text.index('id="password-settings-title"')
+    assert '2026-01-07T21:29:44-05:00' in client.get('/alice').text
+    assert '2026-05-07T22:29:44-04:00' in client.get('/alice/demo/issues').text
+    assert '2026-05-08T02:29:44Z' in WsgiClient(isolated_app.app).get('/alice/demo/issues').text
+    second = WsgiClient(isolated_app.app)
+    login_client(second, 'alice')
+    assert '2026-05-07T22:29:44-04:00' in second.get('/alice/demo/issues').text
+    assert isolated_app.get_user_by_id(owner['id'])['timezone_preference'] == 'America/New_York'
+    invalid = client.post('/settings/site', {'theme_preference': 'light', 'timezone_preference': 'Invalid/Zone'})
+    assert invalid.status_code == 400
+    assert isolated_app.get_user_by_id(owner['id'])['theme_preference'] == 'dark'
+    assert client.post('/settings/site', {'_csrf_token': 'wrong', 'timezone_preference': 'UTC'}).status_code == 403
+    client.post('/settings', {'bio': 'Profile update'})
+    assert isolated_app.get_user_by_id(owner['id'])['timezone_preference'] == 'America/New_York'
+    client.post('/settings/site', {'theme_preference': 'auto', 'timezone_preference': 'Asia/Kolkata'})
+    assert '2026-05-08T07:59:44+05:30' in client.get('/alice/demo/issues').text
+
+
+def test_current_password_check_requires_csrf_and_throttles_without_changing_credentials(isolated_app, monkeypatch):
+    monkeypatch.setattr(gitman, 'RATE_LIMIT_ENABLED', True)
+    monkeypatch.setattr(gitman, 'RATE_LIMIT_MAX_FAILURES', 2)
+    owner = create_user('alice')
+    client = WsgiClient(isolated_app.app)
+    client.get('/login')
+    assert client.post('/settings/password/check', {'current_password': 'anything'}).status_code == 303
+    login_client(client, 'alice')
+    assert client.post('/settings/password/check', {'_csrf_token': 'wrong', 'current_password': 'anything'}).status_code == 403
+    incorrect = client.post('/settings/password/check', {'current_password': 'incorrect'})
+    assert json.loads(incorrect.text) == {'valid': False}
+    verified = client.post('/settings/password/check', {'current_password': 'correct horse battery staple'})
+    assert json.loads(verified.text) == {'valid': True}
+    assert verified.header('Cache-Control') == 'no-store'
+    assert 'correct horse battery staple' not in verified.text
+    for _ in range(2):
+        client.post('/settings/password/check', {'current_password': 'incorrect'})
+    assert client.post('/settings/password/check', {'current_password': 'correct horse battery staple'}).status_code == 429
+    unchanged = isolated_app.get_user_by_id(owner['id'])
+    assert unchanged['password_hash'] == owner['password_hash']
+    assert unchanged['session_version'] == owner['session_version']
+
+
 def test_change_password_revokes_other_sessions_and_git_credentials(isolated_app):
     from bottle import cookie_encode
     owner = create_user('alice')
@@ -2865,17 +2918,20 @@ def test_change_password_revokes_other_sessions_and_git_credentials(isolated_app
     assert legacy.get('/settings/profile').status_code == 200
     profile = client.get('/alice').text
     assert 'href="/settings">Settings</a>' in profile
-    assert 'href="/logout"' not in profile
+    assert 'href="/logout">Log out</a>' in profile
     assert profile.index('aria-label="Notifications"') < profile.index('aria-label="Account menu"')
     assert 'href="/alice">View Profile</a>' in profile
     assert 'href="/new">New Repository</a>' in profile
     assert 'aria-label="New repository"' not in profile
     profile_content = profile.split('<main class="page">', 1)[1]
     assert 'href="/settings"' not in profile_content
+    assert 'href="/logout"' not in profile_content
     assert 'href="/settings">Settings</a>' not in WsgiClient(isolated_app.app).get('/alice').text
     settings = client.get('/settings').text
     assert '<h1>Settings</h1>' in settings
     assert 'href="/logout"' in settings
+    assert 'Back to profile' not in settings
+    assert 'href="/logout"' not in settings.split('<main class="page">', 1)[1]
     assert 'action="/settings/password"' in settings
     result = client.post('/settings/password', {'current_password': 'correct horse battery staple',
         'new_password': 'a different secure password', 'confirm_password': 'a different secure password'})