from flask import redirect
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.$ADMIN_MODEL_ENGINE import ModelView
$ADMIN_DATABASE_IMPORT
$ADMIN_USER_ROLE_IMPORT
from application_tpl.ext.admin.basic_auth import basic_auth, AuthException


class ProtectedAdminIndexView(AdminIndexView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException("Not authenticated.")
        else:
            return True

    def inaccessible_callback(self, name, **kwargs):
        return redirect(basic_auth.challenge())


class ProtectedModelView(ModelView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException("Not authenticated.")
        else:
            return True

    def inaccessible_callback(self, name, **kwargs):
        return redirect(basic_auth.challenge())


admin = Admin(index_view=ProtectedAdminIndexView())


def init_app(app):
    admin.name = app.config.get("ADMIN_NAME", "Admin")
    admin.template_mode = app.config.get("ADMIN_TEMPLATE_MODE", "bootstrap3")
    $ADMIN_VIEW_USER
    $ADMIN_VIEW_ROLE
    admin.init_app(app)