linuxrouter/docker/routlin-dash/app/pages/accountlogin/action.py

66 lines
2.1 KiB
Python
Raw Normal View History

2026-05-27 22:04:04 -04:00
from pathlib import Path
2026-05-17 03:26:01 -04:00
from flask import Blueprint, request, session, redirect, flash
import json, bcrypt
2026-06-07 00:21:08 -04:00
import auth
import config_utils
2026-05-17 03:26:01 -04:00
import sanitize
2026-05-27 22:04:04 -04:00
_PAGE = Path(__file__).parent.name
bp = Blueprint(_PAGE, __name__)
2026-05-17 03:26:01 -04:00
def _load_accounts():
try:
2026-06-07 00:21:08 -04:00
with open(config_utils.ACCOUNTS_FILE) as f:
2026-05-17 03:26:01 -04:00
return json.load(f)
except Exception:
return {'accounts': []}
2026-05-27 22:04:04 -04:00
@bp.route('/action/accountlogin/form_login', methods=['POST'])
2026-06-07 00:21:08 -04:00
@auth.require_level('nothing')
2026-05-27 22:04:04 -04:00
def form_login():
2026-05-17 03:26:01 -04:00
# Abort if already logged in
if session.get('access_level', 'nothing') != 'nothing':
2026-05-27 22:04:04 -04:00
return redirect('/overview')
2026-05-17 03:26:01 -04:00
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')
2026-05-27 22:04:04 -04:00
return redirect(f'/{_PAGE}')
2026-05-17 03:26:01 -04:00
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')
2026-05-27 22:04:04 -04:00
return redirect(f'/{_PAGE}')
2026-05-17 03:26:01 -04:00
if not account.get('hashed_password'):
flash('Account setup is not complete. Please use Create Account to set your password first.', 'error')
2026-05-27 22:04:04 -04:00
return redirect(f'/{_PAGE}')
2026-05-17 03:26:01 -04:00
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')
2026-05-27 22:04:04 -04:00
return redirect(f'/{_PAGE}')
2026-05-17 03:26:01 -04:00
session.clear()
session['email_address'] = account['email_address']
session['access_level'] = account.get('access_level', 'viewer')
session['timezone'] = account.get('timezone', '')
2026-05-25 13:49:23 -04:00
session['apply_changes_immediately'] = False
2026-05-17 03:26:01 -04:00
session.permanent = True
2026-06-10 10:06:13 -04:00
import uuid as _uuid
sid = str(_uuid.uuid4())
session['session_id'] = sid
import config_utils as _cu
_cu.record_session_login(sid, account['email_address'], account.get('access_level', 'viewer'))
2026-05-27 22:04:04 -04:00
return redirect('/overview')