linuxrouter/docker/routlin-dash/app/pages/accountlogin/action.py
2026-05-27 22:04:04 -04:00

59 lines
1.9 KiB
Python

from pathlib import Path
from flask import Blueprint, request, session, redirect, flash
import json, bcrypt
from auth import require_level
from config_utils import ACCOUNTS_FILE
import sanitize
_PAGE = Path(__file__).parent.name
bp = Blueprint(_PAGE, __name__)
def _load_accounts():
try:
with open(ACCOUNTS_FILE) as f:
return json.load(f)
except Exception:
return {'accounts': []}
@bp.route('/action/accountlogin/form_login', methods=['POST'])
@require_level('nothing')
def form_login():
# Abort if already logged in
if session.get('access_level', 'nothing') != 'nothing':
return redirect('/overview')
email = sanitize.email(request.form.get('email', ''))
password = request.form.get('password', '')
if not email or not password:
flash('Email address and password are required.', 'error')
return redirect(f'/{_PAGE}')
accounts = _load_accounts().get('accounts', [])
account = next((a for a in accounts if a.get('email_address', '').lower() == email), None)
if account is None:
flash('Email address not recognised.', 'error')
return redirect(f'/{_PAGE}')
if not account.get('hashed_password'):
flash('Account setup is not complete. Please use Create Account to set your password first.', 'error')
return redirect(f'/{_PAGE}')
stored_hash = account['hashed_password'].encode('utf-8')
if not bcrypt.checkpw(password.encode('utf-8'), stored_hash):
flash('Invalid email address or password.', 'error')
return redirect(f'/{_PAGE}')
session.clear()
session['email_address'] = account['email_address']
session['access_level'] = account.get('access_level', 'viewer')
session['timezone'] = account.get('timezone', '')
session['apply_changes_immediately'] = False
session.permanent = True
return redirect('/overview')