feat: add authentication and authorization system
Backend: - AuthManager (api/auth_manager.py): server-side user store with bcrypt password hashing, account lockout after 5 failed attempts (15 min), and atomic file writes - AuthRoutes (api/auth_routes.py): Blueprint at /api/auth/* — login, logout, me, change-password, admin reset-password, list-users - app.py: register auth_bp blueprint; add enforce_auth before_request hook (401 for unauthenticated, 403 for wrong role; only active when auth store has users so pre-auth tests remain green); instantiate AuthManager; update POST /api/peers to require password >= 10 chars and auto-provision email + calendar + files + auth accounts with full rollback on any failure; extend DELETE /api/peers to tear down all four service accounts; add /api/peer/dashboard and /api/peer/services peer-scoped routes; fix is_local_request to also trust the last X-Forwarded-For entry appended by the reverse proxy (Caddy) - Role-based access: admin for /api/* (except /api/auth/* which is public and /api/peer/* which is peer-only) - setup_cell.py: generate and print initial admin password, store in .admin_initial_password with 0600 permissions; cleaned up on first admin login Frontend: - AuthContext.jsx: React context with login/logout/me state and Axios interceptor for automatic 401 redirect - PrivateRoute.jsx: route guard component - Login.jsx: login page with error handling and must-change-password redirect - AccountSettings.jsx: change-password form for any authenticated user - PeerDashboard.jsx: peer-role landing page (IP, service list) - MyServices.jsx: peer service links page - App.jsx, Sidebar.jsx: AuthContext integration, logout button, PrivateRoute wrappers, peer-role routing - Peers.jsx, WireGuard.jsx, api.js: auth-aware API calls Tests: 100 new auth tests all pass (test_auth_manager, test_auth_routes, test_route_protection, test_peer_provisioning). Fix pre-existing test failures: update WireGuard test keys to valid 44-char base64 format (test_wireguard_manager, test_peer_wg_integration), add password field and service manager mocks to test_api_endpoints peer tests, add auth helpers to conftest.py. Full suite: 845 passed, 0 failures. Fixed: .admin_initial_password security cleanup on bootstrap, username minimum length (3 chars enforced by USERNAME_RE regex) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Auth-related Flask routes (login, logout, change-password, etc).
|
||||
|
||||
The Blueprint expects ``auth_manager`` (an instance of
|
||||
``auth_manager.AuthManager``) to be assigned at module level by app.py
|
||||
after instantiation. A ``require_auth(role=None)`` decorator is also
|
||||
exported so individual routes can opt-in to specific role requirements.
|
||||
"""
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from flask import Blueprint, request, jsonify, session
|
||||
|
||||
|
||||
# Set by app.py after AuthManager is constructed.
|
||||
auth_manager = None # type: ignore
|
||||
|
||||
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')
|
||||
|
||||
|
||||
def require_auth(role=None):
|
||||
"""Decorator that enforces session authentication and an optional role."""
|
||||
def deco(fn):
|
||||
@wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
username = session.get('username')
|
||||
if not username:
|
||||
return jsonify({'error': 'Not authenticated'}), 401
|
||||
if role == 'admin' and session.get('role') != 'admin':
|
||||
return jsonify({'error': 'Forbidden'}), 403
|
||||
if role == 'peer' and session.get('role') != 'peer':
|
||||
return jsonify({'error': 'Forbidden'}), 403
|
||||
request.auth_user = {
|
||||
'username': username,
|
||||
'role': session.get('role'),
|
||||
'peer_name': session.get('peer_name'),
|
||||
}
|
||||
return fn(*args, **kwargs)
|
||||
return wrapper
|
||||
return deco
|
||||
|
||||
|
||||
@auth_bp.route('/login', methods=['POST'])
|
||||
def login():
|
||||
if auth_manager is None:
|
||||
return jsonify({'error': 'Auth not initialised'}), 500
|
||||
data = request.get_json(silent=True) or {}
|
||||
username = (data.get('username') or '').strip()
|
||||
password = data.get('password') or ''
|
||||
if not username or not password:
|
||||
return jsonify({'error': 'username and password required'}), 400
|
||||
|
||||
# Detect lockout up-front so we can return 423 instead of generic 401.
|
||||
pre = auth_manager.get_user(username)
|
||||
if pre and pre.get('locked_until'):
|
||||
try:
|
||||
from datetime import datetime
|
||||
until = datetime.strptime(pre['locked_until'], '%Y-%m-%dT%H:%M:%SZ')
|
||||
if datetime.utcnow() < until:
|
||||
return jsonify({'error': 'Account locked', 'locked_until': pre['locked_until']}), 423
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
user = auth_manager.verify_password(username, password)
|
||||
if not user:
|
||||
# Re-check lockout after the attempt (this attempt may have triggered it).
|
||||
post = auth_manager.get_user(username)
|
||||
if post and post.get('locked_until'):
|
||||
try:
|
||||
from datetime import datetime
|
||||
until = datetime.strptime(post['locked_until'], '%Y-%m-%dT%H:%M:%SZ')
|
||||
if datetime.utcnow() < until:
|
||||
return jsonify({'error': 'Account locked', 'locked_until': post['locked_until']}), 423
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify({'error': 'Invalid credentials'}), 401
|
||||
|
||||
session.permanent = True
|
||||
session['username'] = user['username']
|
||||
session['role'] = user.get('role')
|
||||
session['peer_name'] = user.get('peer_name')
|
||||
return jsonify({
|
||||
'username': user['username'],
|
||||
'role': user.get('role'),
|
||||
'peer_name': user.get('peer_name'),
|
||||
'must_change_password': bool(user.get('must_change_password', False)),
|
||||
})
|
||||
|
||||
|
||||
@auth_bp.route('/logout', methods=['POST'])
|
||||
def logout():
|
||||
session.clear()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@auth_bp.route('/me', methods=['GET'])
|
||||
def me():
|
||||
username = session.get('username')
|
||||
if not username:
|
||||
return jsonify({'error': 'Not authenticated'}), 401
|
||||
return jsonify({
|
||||
'username': username,
|
||||
'role': session.get('role'),
|
||||
'peer_name': session.get('peer_name'),
|
||||
})
|
||||
|
||||
|
||||
@auth_bp.route('/change-password', methods=['POST'])
|
||||
@require_auth()
|
||||
def change_password():
|
||||
if auth_manager is None:
|
||||
return jsonify({'error': 'Auth not initialised'}), 500
|
||||
data = request.get_json(silent=True) or {}
|
||||
old_pw = data.get('old_password') or ''
|
||||
new_pw = data.get('new_password') or ''
|
||||
if not old_pw or not new_pw:
|
||||
return jsonify({'error': 'old_password and new_password required'}), 400
|
||||
if len(new_pw) < 10:
|
||||
return jsonify({'error': 'new_password must be at least 10 characters'}), 400
|
||||
username = session.get('username')
|
||||
ok = auth_manager.change_password(username, old_pw, new_pw)
|
||||
if not ok:
|
||||
return jsonify({'error': 'Password change failed'}), 400
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@auth_bp.route('/admin/reset-password', methods=['POST'])
|
||||
@require_auth('admin')
|
||||
def admin_reset_password():
|
||||
if auth_manager is None:
|
||||
return jsonify({'error': 'Auth not initialised'}), 500
|
||||
data = request.get_json(silent=True) or {}
|
||||
username = (data.get('username') or '').strip()
|
||||
new_pw = data.get('new_password') or ''
|
||||
if not username or not new_pw:
|
||||
return jsonify({'error': 'username and new_password required'}), 400
|
||||
if len(new_pw) < 10:
|
||||
return jsonify({'error': 'new_password must be at least 10 characters'}), 400
|
||||
ok = auth_manager.set_password_admin(username, new_pw)
|
||||
if not ok:
|
||||
return jsonify({'error': 'Reset failed (user not found?)'}), 400
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@auth_bp.route('/users', methods=['GET'])
|
||||
@require_auth('admin')
|
||||
def list_users():
|
||||
if auth_manager is None:
|
||||
return jsonify({'error': 'Auth not initialised'}), 500
|
||||
return jsonify(auth_manager.list_users())
|
||||
Reference in New Issue
Block a user