July 4 - Implement TOTP 2FA
This commit is contained in:
@@ -33,6 +33,15 @@ class User(UserMixin, db.Model):
|
||||
set_password_token = db.Column(db.String(64), nullable=True, index=True)
|
||||
set_password_token_expires = db.Column(db.DateTime, nullable=True)
|
||||
|
||||
# ── Two-factor auth (phase35) — opt-in TOTP ───────────────────────────
|
||||
# mfa_enabled gates the second-factor step at login. mfa_secret is the
|
||||
# base32 TOTP shared secret. mfa_recovery_codes is a JSON list of hashed
|
||||
# one-time backup codes (never stored in plaintext). All default off so
|
||||
# existing accounts are unaffected until a user enrolls.
|
||||
mfa_enabled = db.Column(db.Boolean, nullable=False, default=False)
|
||||
mfa_secret = db.Column(db.String(64), nullable=True)
|
||||
mfa_recovery_codes = db.Column(db.JSON, nullable=True)
|
||||
|
||||
# Relationships
|
||||
inspections = db.relationship('Inspection', backref='inspector', lazy='dynamic')
|
||||
|
||||
|
||||
+130
-1
@@ -1,10 +1,11 @@
|
||||
from flask import Blueprint, render_template, redirect, url_for, flash, request, abort
|
||||
from flask import Blueprint, render_template, redirect, url_for, flash, request, abort, session
|
||||
from urllib.parse import urlparse
|
||||
from flask_login import login_user, logout_user, login_required, current_user
|
||||
from app import db, limiter
|
||||
from app.models.user import User
|
||||
from app.utils.forms import LoginForm, UserForm, ProfileForm, ForgotPasswordForm, ResetPasswordForm
|
||||
from app.utils.decorators import admin_required, supervisor_required, safe_redirect_url
|
||||
from app.utils import mfa
|
||||
import logging
|
||||
from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE, ACTION_LOGIN, ACTION_LOGOUT
|
||||
from app.tenancy.gates import quota_soft_check
|
||||
@@ -35,6 +36,17 @@ def login():
|
||||
'warning'
|
||||
)
|
||||
return render_template('auth/login.html', form=form)
|
||||
# ── Two-factor gate (phase35) ────────────────────────────────
|
||||
# If this account has TOTP enabled, defer login_user() to the
|
||||
# second-factor step. Password is verified; identity is NOT yet
|
||||
# established until the code is confirmed at /auth/mfa.
|
||||
if user.mfa_enabled and user.mfa_secret:
|
||||
session['mfa_pending_user_id'] = user.id
|
||||
session['mfa_pending_remember'] = bool(form.remember_me.data)
|
||||
session['mfa_pending_next'] = safe_redirect_url(request.args.get('next'))
|
||||
logger.info('MFA_CHALLENGE | user=%s', user.username)
|
||||
return redirect(url_for('auth.mfa_challenge'))
|
||||
|
||||
login_user(user, remember=form.remember_me.data)
|
||||
# Use validated next URL — never redirect blindly to request.args['next']
|
||||
next_page = safe_redirect_url(request.args.get('next'))
|
||||
@@ -59,6 +71,123 @@ def logout():
|
||||
return redirect(url_for('auth.login'))
|
||||
|
||||
|
||||
# ── Two-factor authentication (phase35) ─────────────────────────────────────
|
||||
|
||||
@bp.route('/mfa', methods=['GET', 'POST'])
|
||||
@limiter.limit('10 per minute; 3 per second')
|
||||
def mfa_challenge():
|
||||
"""Second-factor step during login. Reached only after a correct password
|
||||
for an MFA-enabled account (identity is held pending in the session)."""
|
||||
uid = session.get('mfa_pending_user_id')
|
||||
if not uid:
|
||||
return redirect(url_for('auth.login'))
|
||||
user = db.session.get(User, uid)
|
||||
if user is None or not user.mfa_enabled or not user.active:
|
||||
session.pop('mfa_pending_user_id', None)
|
||||
return redirect(url_for('auth.login'))
|
||||
|
||||
if request.method == 'POST':
|
||||
code = request.form.get('code', '')
|
||||
use_recovery = bool(request.form.get('recovery'))
|
||||
verified = False
|
||||
via = 'totp'
|
||||
|
||||
if use_recovery:
|
||||
matched, remaining = mfa.check_and_consume_recovery(user.mfa_recovery_codes, code)
|
||||
if matched:
|
||||
user.mfa_recovery_codes = remaining
|
||||
db.session.commit()
|
||||
verified = True
|
||||
via = 'recovery'
|
||||
else:
|
||||
verified = mfa.verify_totp(user.mfa_secret, code)
|
||||
|
||||
if verified:
|
||||
remember = session.pop('mfa_pending_remember', False)
|
||||
next_page = session.pop('mfa_pending_next', None)
|
||||
session.pop('mfa_pending_user_id', None)
|
||||
login_user(user, remember=remember)
|
||||
log_action(ACTION_LOGIN, 'User', user.id, user.username, f'2fa via {via}')
|
||||
if via == 'recovery':
|
||||
remaining_n = len(user.mfa_recovery_codes or [])
|
||||
flash(f'Signed in with a recovery code. {remaining_n} recovery '
|
||||
f'code(s) remaining.', 'warning')
|
||||
else:
|
||||
flash(f'Welcome back, {user.username}!', 'success')
|
||||
return redirect(safe_redirect_url(next_page))
|
||||
|
||||
logger.warning('MFA_FAILED | user=%s ip=%s recovery=%s',
|
||||
user.username, request.remote_addr, use_recovery)
|
||||
flash('Invalid verification code. Please try again.', 'danger')
|
||||
|
||||
return render_template('auth/mfa_challenge.html')
|
||||
|
||||
|
||||
@bp.route('/mfa/setup', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@supervisor_required # admin + director
|
||||
def mfa_setup():
|
||||
"""Enroll the current account in TOTP two-factor. Opt-in.
|
||||
|
||||
The candidate secret is held in the session until the user proves they can
|
||||
generate a valid code, so a half-finished enrollment never locks anyone out.
|
||||
"""
|
||||
if current_user.mfa_enabled:
|
||||
flash('Two-factor authentication is already enabled on your account.', 'info')
|
||||
return redirect(url_for('auth.profile'))
|
||||
|
||||
if request.method == 'POST':
|
||||
secret = session.get('mfa_setup_secret')
|
||||
code = request.form.get('code', '')
|
||||
if not secret:
|
||||
flash('Your setup session expired. Please start again.', 'warning')
|
||||
return redirect(url_for('auth.mfa_setup'))
|
||||
if mfa.verify_totp(secret, code):
|
||||
plaintext, hashed = mfa.generate_recovery_codes()
|
||||
current_user.mfa_secret = secret
|
||||
current_user.mfa_enabled = True
|
||||
current_user.mfa_recovery_codes = hashed
|
||||
db.session.commit()
|
||||
session.pop('mfa_setup_secret', None)
|
||||
log_action(ACTION_UPDATE, 'User', current_user.id, current_user.username,
|
||||
'enabled two-factor authentication')
|
||||
logger.info('MFA_ENABLED | user=%s', current_user.username)
|
||||
# Recovery codes are shown exactly once, right here.
|
||||
return render_template('auth/mfa_recovery.html', codes=plaintext)
|
||||
flash('That code did not match. Make sure your device clock is correct '
|
||||
'and try again.', 'danger')
|
||||
|
||||
# GET, or a failed POST: (re)present the QR for the pending secret.
|
||||
secret = session.get('mfa_setup_secret') or mfa.new_secret()
|
||||
session['mfa_setup_secret'] = secret
|
||||
uri = mfa.provisioning_uri(secret, current_user.email or current_user.username)
|
||||
return render_template('auth/mfa_setup.html', secret=secret, qr_svg=mfa.qr_svg(uri))
|
||||
|
||||
|
||||
@bp.route('/mfa/disable', methods=['POST'])
|
||||
@login_required
|
||||
def mfa_disable():
|
||||
"""Turn off two-factor. Requires a current authenticator code OR the account
|
||||
password, so a merely-hijacked session can't silently strip 2FA."""
|
||||
if not current_user.mfa_enabled:
|
||||
return redirect(url_for('auth.profile'))
|
||||
code = request.form.get('code', '')
|
||||
pw = request.form.get('password', '')
|
||||
if not (mfa.verify_totp(current_user.mfa_secret, code)
|
||||
or (pw and current_user.check_password(pw))):
|
||||
flash('Enter a valid authenticator code or your password to disable 2FA.', 'danger')
|
||||
return redirect(url_for('auth.profile'))
|
||||
current_user.mfa_enabled = False
|
||||
current_user.mfa_secret = None
|
||||
current_user.mfa_recovery_codes = None
|
||||
db.session.commit()
|
||||
log_action(ACTION_UPDATE, 'User', current_user.id, current_user.username,
|
||||
'disabled two-factor authentication')
|
||||
logger.info('MFA_DISABLED | user=%s', current_user.username)
|
||||
flash('Two-factor authentication has been disabled.', 'success')
|
||||
return redirect(url_for('auth.profile'))
|
||||
|
||||
|
||||
@bp.route('/profile', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def profile():
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Two-Factor Verification{% endblock %}
|
||||
{% block content %}
|
||||
<div class="row justify-content-center mt-4">
|
||||
<div class="col-md-5 col-lg-4">
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-body p-4">
|
||||
<div class="text-center mb-3">
|
||||
<i class="bi bi-shield-lock fs-1 text-primary"></i>
|
||||
<h4 class="mt-2 mb-1">Two-factor verification</h4>
|
||||
<p class="text-muted small mb-0">
|
||||
Enter the 6-digit code from your authenticator app.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="{{ url_for('auth.mfa_challenge') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
|
||||
<div class="mb-3">
|
||||
<input type="text" name="code" class="form-control form-control-lg text-center"
|
||||
inputmode="numeric" autocomplete="one-time-code" autofocus
|
||||
placeholder="123456" style="letter-spacing:.4em;">
|
||||
</div>
|
||||
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" type="checkbox" name="recovery" id="useRecovery" value="1">
|
||||
<label class="form-check-label small" for="useRecovery">
|
||||
I'll use a recovery code instead
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary w-100">
|
||||
<i class="bi bi-check2-circle"></i> Verify
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="text-center mt-3">
|
||||
<a href="{{ url_for('auth.login') }}" class="small text-muted">Back to login</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// When "use recovery code" is toggled, relax the numeric hints for the code box.
|
||||
(function () {
|
||||
var chk = document.getElementById('useRecovery');
|
||||
var box = document.querySelector('input[name="code"]');
|
||||
if (!chk || !box) return;
|
||||
chk.addEventListener('change', function () {
|
||||
if (chk.checked) {
|
||||
box.setAttribute('inputmode', 'text');
|
||||
box.setAttribute('placeholder', 'xxxx-xxxx');
|
||||
box.style.letterSpacing = '.15em';
|
||||
} else {
|
||||
box.setAttribute('inputmode', 'numeric');
|
||||
box.setAttribute('placeholder', '123456');
|
||||
box.style.letterSpacing = '.4em';
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,47 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Recovery Codes{% endblock %}
|
||||
{% block content %}
|
||||
<div class="row justify-content-center mt-3">
|
||||
<div class="col-md-8 col-lg-6">
|
||||
<div class="alert alert-success">
|
||||
<i class="bi bi-shield-check"></i>
|
||||
<strong>Two-factor authentication is now enabled.</strong>
|
||||
</div>
|
||||
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-body">
|
||||
<h4 class="mb-2"><i class="bi bi-key"></i> Save your recovery codes</h4>
|
||||
<p class="text-muted">
|
||||
Each code works <strong>once</strong> if you lose access to your authenticator
|
||||
app. Store them somewhere safe — <strong>they will not be shown again.</strong>
|
||||
</p>
|
||||
|
||||
<div class="bg-light border rounded p-3 mb-3">
|
||||
<div class="row row-cols-2 g-2 font-monospace text-center" id="codeList">
|
||||
{% for code in codes %}
|
||||
<div class="col"><span class="badge bg-white text-dark border fs-6 w-100 py-2">{{ code }}</span></div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex gap-2">
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="copyCodes()">
|
||||
<i class="bi bi-clipboard"></i> Copy codes
|
||||
</button>
|
||||
<a href="{{ url_for('auth.profile') }}" class="btn btn-primary ms-auto">
|
||||
<i class="bi bi-check-lg"></i> I've saved them — Done
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function copyCodes() {
|
||||
var codes = Array.from(document.querySelectorAll('#codeList .badge'))
|
||||
.map(function (b) { return b.textContent.trim(); }).join('\n');
|
||||
navigator.clipboard.writeText(codes);
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,62 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Enable Two-Factor{% endblock %}
|
||||
{% block content %}
|
||||
<div class="row justify-content-center mt-3">
|
||||
<div class="col-md-8 col-lg-6">
|
||||
<h3 class="mb-3"><i class="bi bi-shield-lock"></i> Enable two-factor authentication</h3>
|
||||
|
||||
<div class="card shadow-sm mb-3">
|
||||
<div class="card-body">
|
||||
<ol class="mb-3 ps-3">
|
||||
<li class="mb-1">Install an authenticator app (Google Authenticator, Authy, 1Password, …).</li>
|
||||
<li class="mb-1">Scan the QR code below, or enter the setup key manually.</li>
|
||||
<li>Enter the 6-digit code the app shows to confirm and finish.</li>
|
||||
</ol>
|
||||
|
||||
<div class="text-center mb-3">
|
||||
<div class="d-inline-block p-2 bg-white border rounded" style="width:220px;height:220px;">
|
||||
{{ qr_svg | safe }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label small text-muted mb-1">Manual setup key</label>
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control font-monospace" id="secretKey"
|
||||
value="{{ secret }}" readonly>
|
||||
<button class="btn btn-outline-secondary" type="button" onclick="copySecret()">
|
||||
<i class="bi bi-clipboard"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="{{ url_for('auth.mfa_setup') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<label class="form-label fw-semibold">Enter the 6-digit code to confirm</label>
|
||||
<div class="input-group input-group-lg mb-3">
|
||||
<input type="text" name="code" class="form-control text-center"
|
||||
inputmode="numeric" autocomplete="one-time-code" autofocus
|
||||
placeholder="123456" style="letter-spacing:.4em;">
|
||||
<button type="submit" class="btn btn-primary">
|
||||
<i class="bi bi-check2-circle"></i> Enable
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="{{ url_for('auth.profile') }}" class="btn btn-outline-secondary">
|
||||
<i class="bi bi-x-lg"></i> Cancel
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function copySecret() {
|
||||
var el = document.getElementById('secretKey');
|
||||
el.select();
|
||||
el.setSelectionRange(0, 99999);
|
||||
navigator.clipboard.writeText(el.value);
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -157,6 +157,48 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if current_user.role in ['admin', 'director'] %}
|
||||
<!-- Two-factor authentication (phase35) -->
|
||||
<div class="card shadow-sm mb-4">
|
||||
<div class="card-header bg-light d-flex justify-content-between align-items-center">
|
||||
<h6 class="mb-0 fw-semibold"><i class="bi bi-shield-lock me-1"></i>Two-Factor Authentication</h6>
|
||||
{% if current_user.mfa_enabled %}
|
||||
<span class="badge bg-success">Enabled</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">Disabled</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="card-body">
|
||||
{% if current_user.mfa_enabled %}
|
||||
<p class="text-muted small mb-3">
|
||||
Your account is protected with an authenticator app. You'll be asked
|
||||
for a 6-digit code each time you sign in.
|
||||
</p>
|
||||
<form method="POST" action="{{ url_for('auth.mfa_disable') }}"
|
||||
onsubmit="return confirm('Disable two-factor authentication? Your account will be less secure.');">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<label class="form-label small">Enter a current code or your password to disable:</label>
|
||||
<div class="input-group">
|
||||
<input type="text" name="code" class="form-control" placeholder="6-digit code"
|
||||
inputmode="numeric" autocomplete="off">
|
||||
<input type="password" name="password" class="form-control" placeholder="…or password"
|
||||
autocomplete="off">
|
||||
<button type="submit" class="btn btn-outline-danger">Disable 2FA</button>
|
||||
</div>
|
||||
</form>
|
||||
{% else %}
|
||||
<p class="text-muted small mb-3">
|
||||
Add a second layer of security. After entering your password you'll
|
||||
confirm a one-time code from an authenticator app.
|
||||
</p>
|
||||
<a href="{{ url_for('auth.mfa_setup') }}" class="btn btn-primary">
|
||||
<i class="bi bi-shield-plus me-1"></i>Enable Two-Factor
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- Recent Inspections -->
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header bg-light d-flex justify-content-between align-items-center">
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
app/utils/mfa.py
|
||||
----------------
|
||||
TOTP two-factor helpers, shared by the main app (admin/director accounts) and
|
||||
the superadmin control panel.
|
||||
|
||||
Design notes
|
||||
------------
|
||||
* TOTP secret is a base32 string (RFC 6238). It is a *shared* secret by nature;
|
||||
we store it as-is, exactly like every standard authenticator integration.
|
||||
* Recovery codes are one-time backup codes shown ONCE at enrollment and stored
|
||||
only as salted hashes (werkzeug). A consumed code is removed from the list.
|
||||
* The QR is rendered as an inline SVG (no Pillow / no external request), so it
|
||||
works under the app's strict CSP and in the standalone panel app alike.
|
||||
|
||||
This module has no Flask-app or model dependencies — pure functions — so both
|
||||
apps and the test-suite can use it directly.
|
||||
"""
|
||||
|
||||
import io
|
||||
|
||||
import pyotp
|
||||
import qrcode
|
||||
import qrcode.image.svg
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
ISSUER = 'JQC'
|
||||
_RECOVERY_CODE_COUNT = 10
|
||||
|
||||
|
||||
def new_secret() -> str:
|
||||
"""Return a fresh base32 TOTP secret."""
|
||||
return pyotp.random_base32()
|
||||
|
||||
|
||||
def provisioning_uri(secret: str, account_name: str, issuer: str = ISSUER) -> str:
|
||||
"""otpauth:// URI to encode in the enrollment QR / manual entry."""
|
||||
return pyotp.totp.TOTP(secret).provisioning_uri(name=account_name, issuer_name=issuer)
|
||||
|
||||
|
||||
def verify_totp(secret: str, code: str) -> bool:
|
||||
"""Validate a 6-digit TOTP code. valid_window=1 tolerates ±30s clock drift."""
|
||||
if not secret or not code:
|
||||
return False
|
||||
code = code.strip().replace(' ', '')
|
||||
if not code.isdigit():
|
||||
return False
|
||||
try:
|
||||
return pyotp.totp.TOTP(secret).verify(code, valid_window=1)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def qr_svg(uri: str) -> str:
|
||||
"""Return an inline SVG string for the given otpauth URI (no Pillow needed)."""
|
||||
buf = io.BytesIO()
|
||||
qrcode.make(uri, image_factory=qrcode.image.svg.SvgPathImage).save(buf)
|
||||
return buf.getvalue().decode('utf-8')
|
||||
|
||||
|
||||
def generate_recovery_codes(n: int = _RECOVERY_CODE_COUNT):
|
||||
"""Return (plaintext_codes, hashed_codes).
|
||||
|
||||
Plaintext is shown to the user ONCE. Only the hashes are persisted.
|
||||
Codes are formatted xxxx-xxxx for readability.
|
||||
"""
|
||||
import secrets
|
||||
plaintext, hashed = [], []
|
||||
for _ in range(n):
|
||||
raw = secrets.token_hex(4) # 8 hex chars
|
||||
code = f'{raw[:4]}-{raw[4:]}'
|
||||
plaintext.append(code)
|
||||
hashed.append(generate_password_hash(code))
|
||||
return plaintext, hashed
|
||||
|
||||
|
||||
def _normalise(code: str) -> str:
|
||||
return (code or '').strip().lower().replace(' ', '')
|
||||
|
||||
|
||||
def check_and_consume_recovery(hashed_codes, code):
|
||||
"""Check a recovery code against the stored hashes.
|
||||
|
||||
Returns (matched: bool, remaining_hashes: list). On a match the consumed
|
||||
hash is removed so each recovery code works exactly once. `hashed_codes`
|
||||
is never mutated in place.
|
||||
"""
|
||||
remaining = list(hashed_codes or [])
|
||||
candidate = _normalise(code)
|
||||
if not candidate:
|
||||
return False, remaining
|
||||
for h in list(remaining):
|
||||
if check_password_hash(h, candidate):
|
||||
remaining.remove(h)
|
||||
return True, remaining
|
||||
return False, remaining
|
||||
Reference in New Issue
Block a user