linuxrouter/docker/router-dash/app/action_add_account.py

65 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
import sanitize
bp = Blueprint('action_add_account', __name__)
DATA_DIR = '/data'
ACCOUNTS_FILE = f'{DATA_DIR}/authorized_accounts.json'
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_manage_accounts')
if not re.match(r'^[^@\s]+@[^@\s]+\.[^@\s]+$', email):
flash('Email address does not appear to be valid.', 'error')
return redirect('/view/view_manage_accounts')
if access_level not in VALID_LEVELS:
flash('Invalid access level.', 'error')
return redirect('/view/view_manage_accounts')
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_manage_accounts')
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_manage_accounts')