diff --git a/app/admin.py b/app/admin.py new file mode 100644 index 0000000..0ba2810 --- /dev/null +++ b/app/admin.py @@ -0,0 +1,36 @@ +"Haldis admin related views and models" + +import flask_login as login +from flask import Flask +from flask_admin import Admin +from flask_admin.contrib.sqla import ModelView +from flask_sqlalchemy import SQLAlchemy + +from models import Order, OrderItem, OrderItemChoice, User + + +class ModelBaseView(ModelView): + "Base model for admin related things" + # pylint: disable=R0201, R0903 + def is_accessible(self) -> bool: + "Check if the user has admin permission" + if login.current_user.is_anonymous(): + return False + return login.current_user.is_admin() + + +class UserAdminModel(ModelBaseView): + "Model for user admin" + # pylint: disable=R0903 + column_searchable_list = ("username",) + inline_models = None + + +def init_admin(app: Flask, database: SQLAlchemy) -> None: + "Initialize the admin related things in the app." + admin = Admin(app, name="Haldis", url="/admin", template_mode="bootstrap3") + + admin.add_view(UserAdminModel(User, database.session)) + admin.add_view(ModelBaseView(Order, database.session)) + admin.add_view(ModelBaseView(OrderItem, database.session)) + admin.add_view(ModelBaseView(OrderItemChoice, database.session)) diff --git a/app/app.py b/app/app.py index 42f018d..e5e4f22 100755 --- a/app/app.py +++ b/app/app.py @@ -19,6 +19,7 @@ from flask_oauthlib.client import OAuth, OAuthException from flask_script import Manager, Server from markupsafe import Markup +from admin import init_admin from login import init_login from models import db from models.anonymous_user import AnonymouseUser @@ -68,6 +69,8 @@ def register_plugins(app: Flask) -> Manager: app_manager = Manager(app) app_manager.add_command("db", MigrateCommand) app_manager.add_command("runserver", Server(port=8000)) + # Add admin interface + init_admin(app, db) # Init login manager login_manager = LoginManager() diff --git a/app/templates/layout.html b/app/templates/layout.html index b19d9b7..ede4835 100644 --- a/app/templates/layout.html +++ b/app/templates/layout.html @@ -9,6 +9,9 @@ ('general_bp.about', 'About'), ('stats_blueprint.stats', 'Stats'), ] -%} +{% if not current_user.is_anonymous() and current_user.is_admin() -%} + {% set navbar = navbar + [('admin.index', 'Admin')] -%} +{% endif -%} {% set active_page = active_page|default('index') -%} {% block title %}