linuxrouter/docker/routlin-dash/app/action_change_password.py
2026-05-24 00:47:43 -04:00

63 lines
2.1 KiB
Python

from flask import Blueprint, request, session, redirect, flash
import json, bcrypt
from auth import require_level
from config_utils import ACCOUNTS_FILE
bp = Blueprint('action_change_password', __name__)
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')