from flask import Blueprint, request, session, redirect, flash import json, bcrypt from auth import require_level bp = Blueprint('action_change_password', __name__) DATA_DIR = '/data' ACCOUNTS_FILE = f'{DATA_DIR}/authorized_accounts.json' def _load_accounts(): try: with open(ACCOUNTS_FILE) as f: return json.load(f) except Exception: return {'accounts': []} def _save_accounts(data): with open(ACCOUNTS_FILE, 'w') as f: json.dump(data, f, indent=2) @bp.route('/action/change_password', methods=['POST']) @require_level('viewer') def change_password(): current_password = request.form.get('current_password', '') new_password = request.form.get('new_password', '') confirm_password = request.form.get('confirm_password', '') if not current_password or not new_password or not confirm_password: flash('All fields are required.', 'error') return redirect('/view/view_preferences') if new_password != confirm_password: flash('New passwords do not match.', 'error') return redirect('/view/view_preferences') if len(new_password) < 8: flash('New password must be at least 8 characters.', 'error') return redirect('/view/view_preferences') email = session.get('email_address', '').lower() data = _load_accounts() accounts = data.get('accounts', []) account = next((a for a in accounts if a.get('email_address', '').lower() == email), None) if account is None: flash('Account not found. Please log in again.', 'error') return redirect('/view/view_log_in') stored_hash = account.get('hashed_password', '').encode('utf-8') if not bcrypt.checkpw(current_password.encode('utf-8'), stored_hash): flash('Current password is incorrect.', 'error') return redirect('/view/view_preferences') salt = bcrypt.gensalt() hashed = bcrypt.hashpw(new_password.encode('utf-8'), salt) account['hashed_password'] = hashed.decode('utf-8') account['salt'] = salt.decode('utf-8') _save_accounts(data) flash('Password changed successfully.', 'success') return redirect('/view/view_preferences')