linuxrouter/docker/routlin-dash/app/pages/accountadd/action.py
2026-05-27 20:56:30 -04:00

64 lines
2.1 KiB
Python

from flask import Blueprint, request, session, redirect, flash
import json, re
from datetime import datetime, timezone
from auth import require_level
from config_utils import ACCOUNTS_FILE
import sanitize
bp = Blueprint('accountadd', __name__)
VALID_LEVELS = {'viewer', 'administrator', 'manager'}
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/add_account', methods=['POST'])
@require_level('manager')
def add_account():
email = sanitize.email(request.form.get('email_address', ''))
access_level = request.form.get('access_level', '').strip()
if not email:
flash('Email address is required.', 'error')
return redirect('/view/view_manageaccounts')
if not re.match(r'^[^@\s]+@[^@\s]+\.[^@\s]+$', email):
flash('Email address does not appear to be valid.', 'error')
return redirect('/view/view_manageaccounts')
if access_level not in VALID_LEVELS:
flash('Invalid access level.', 'error')
return redirect('/view/view_manageaccounts')
data = _load_accounts()
accounts = data.get('accounts', [])
if any(a.get('email_address', '').lower() == email for a in accounts):
flash('An account with that email address already exists.', 'error')
return redirect('/view/view_manageaccounts')
now = datetime.now(tz=timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
accounts.append({
'email_address': email,
'access_level': access_level,
'account_created_utc': now,
'account_created_by': session.get('email_address', ''),
'hashed_password': '',
'timezone': '',
})
data['accounts'] = accounts
_save_accounts(data)
flash(f'Authorization added for {email}. User must complete account setup via the Create Account page.', 'success')
return redirect('/view/view_manageaccounts')