@admin_bp.route('/key/edit/<key_id>', methods=['GET', 'POST'])
@admin_bp.route('/key/edit', methods=['GET', 'POST'])
@login_required
@operator_role_required
def edit_key(key_id=None):
    domains = Domain.query.all()
    accounts = Account.query.all()
    roles = Role.query.all()
    apikey = None
    create = True
    plain_key = None
    if key_id:
        apikey = ApiKey.query.filter((ApiKey.id == key_id)).first()
        create = False
        if (not apikey):
            return (render_template('errors/404.html'), 404)
    if (request.method == 'GET'):
        return render_template('admin_edit_key.html', key=apikey, domains=domains, accounts=accounts, roles=roles, create=create)
    if (request.method == 'POST'):
        fdata = request.form
        description = fdata['description']
        role = fdata.getlist('key_role')[0]
        domain_list = fdata.getlist('key_multi_domain')
        account_list = fdata.getlist('key_multi_account')
        if create:
            if (role == 'User'):
                domain_obj_list = Domain.query.filter(Domain.name.in_(domain_list)).all()
                account_obj_list = Account.query.filter(Account.name.in_(account_list)).all()
            else:
                (account_obj_list, domain_obj_list) = ([], [])
            apikey = ApiKey(desc=description, role_name=role, domains=domain_obj_list, accounts=account_obj_list)
            try:
                apikey.create()
            except Exception as e:
                current_app.logger.error('Error: {0}'.format(e))
                raise ApiKeyCreateFail(message='Api key create failed')
            plain_key = apikey_plain_schema.dump([apikey])[0]['plain_key']
            plain_key = b64encode(plain_key.encode('utf-8')).decode('utf-8')
            history_message = 'Created API key {0}'.format(apikey.id)
        else:
            try:
                if (role != 'User'):
                    (domain_list, account_list) = ([], [])
                apikey.update(role, description, domain_list, account_list)
                history_message = 'Updated API key {0}'.format(apikey.id)
            except Exception as e:
                current_app.logger.error('Error: {0}'.format(e))
        history = History(msg=history_message, detail=json.dumps({'key': apikey.id, 'role': apikey.role.name, 'description': apikey.description, 'domains': [domain.name for domain in apikey.domains], 'accounts': [a.name for a in apikey.accounts]}), created_by=current_user.username)
        history.add()
        return render_template('admin_edit_key.html', key=apikey, domains=domains, accounts=accounts, roles=roles, create=create, plain_key=plain_key)
@admin_bp.route('/key/edit/<key_id>', methods=['GET', 'POST'])
@admin_bp.route('/key/edit', methods=['GET', 'POST'])
@login_required
@operator_role_required
def edit_key(key_id=None):
    domains = Domain.query.all()
    accounts = Account.query.all()
    roles = Role.query.all()
    apikey = None
    create = True
    plain_key = None
    if key_id:
        apikey = ApiKey.query.filter((ApiKey.id == key_id)).first()
        create = False
        if (not apikey):
            return (render_template('errors/404.html'), 404)
    if (request.method == 'GET'):
        return render_template('admin_edit_key.html', key=apikey, domains=domains, accounts=accounts, roles=roles, create=create)
    if (request.method == 'POST'):
        fdata = request.form
        description = fdata['description']
        role = fdata.getlist('key_role')[0]
        domain_list = fdata.getlist('key_multi_domain')
        account_list = fdata.getlist('key_multi_account')
        if create:
            if (role == 'User'):
                domain_obj_list = Domain.query.filter(Domain.name.in_(domain_list)).all()
                account_obj_list = Account.query.filter(Account.name.in_(account_list)).all()
            else:
                (account_obj_list, domain_obj_list) = ([], [])
            apikey = ApiKey(desc=description, role_name=role, domains=domain_obj_list, accounts=account_obj_list)
            try:
                apikey.create()
            except Exception as e:
                current_app.logger.error('Error: {0}'.format(e))
                raise ApiKeyCreateFail(message='Api key create failed')
            plain_key = apikey_plain_schema.dump([apikey])[0]['plain_key']
            plain_key = b64encode(plain_key.encode('utf-8')).decode('utf-8')
            history_message = 'Created API key {0}'.format(apikey.id)
        else:
            try:
                if (role != 'User'):
                    (domain_list, account_list) = ([], [])
                apikey.update(role, description, domain_list, account_list)
                history_message = 'Updated API key {0}'.format(apikey.id)
            except Exception as e:
                current_app.logger.error('Error: {0}'.format(e))
        history = History(msg=history_message, detail=json.dumps({'key': apikey.id, 'role': apikey.role.name, 'description': apikey.description, 'domains': [domain.name for domain in apikey.domains], 'accounts': [a.name for a in apikey.accounts]}), created_by=current_user.username)
        history.add()
        return render_template('admin_edit_key.html', key=apikey, domains=domains, accounts=accounts, roles=roles, create=create, plain_key=plain_key)