Added admin view stuffs

This commit is contained in:
Pünkösd Marcell 2020-11-29 01:57:07 +01:00
parent d28cc70519
commit 116ef34a9a
5 changed files with 72 additions and 5 deletions

View File

@ -7,12 +7,15 @@ from healthcheck import HealthCheck
from flask_cors import CORS from flask_cors import CORS
from flask_mail import Mail from flask_mail import Mail
from flask_admin import Admin
from utils import Config from utils import Config
from utils import health_database_status, init_security_real_good from utils import health_database_status
from utils import init_security_real_good, user_datastore, AuthenticatedModelView, AuthenticatedAdminIndexView
from utils import storage from utils import storage
from views import ItemView, ProfileView, UploadView, IndexView, ContentView, PurchaseView from views import ItemView, ProfileView, UploadView, IndexView, ContentView, PurchaseView
from models import db from models import db, Comment, Item, Purchase, User, Role
""" """
Main Flask entrypoint Main Flask entrypoint
@ -51,7 +54,31 @@ for view in [ItemView, ProfileView, UploadView, IndexView, ContentView, Purchase
health.add_check(health_database_status) health.add_check(health_database_status)
app.add_url_rule("/healthz", "healthcheck", view_func=lambda: health.run()) app.add_url_rule("/healthz", "healthcheck", view_func=lambda: health.run())
admin = Admin(app, index_view=AuthenticatedAdminIndexView())
admin.add_view(AuthenticatedModelView(User, db.session))
admin.add_view(AuthenticatedModelView(Comment, db.session))
admin.add_view(AuthenticatedModelView(Item, db.session))
admin.add_view(AuthenticatedModelView(Purchase, db.session))
@app.before_first_request @app.before_first_request
def init_db(): def init_db():
db.create_all() db.create_all()
if Role.query.count() == 0:
user_datastore.create_role(name='administrator')
app.logger.info("Roles table is empty. Default roles created!")
default_admin_email = app.config.get('DEFAULT_ADMIN_EMAIL')
default_admin_password = app.config.get('DEFAULT_ADMIN_PASSWORD')
if default_admin_email and default_admin_password: # Create only if the default credentials are provided
if User.query.count() == 0: # Create default user, only if the user table is empty
default_admin_username = app.config.get('DEFAULT_ADMIN_USER')
user = user_datastore.create_user(email=default_admin_email, password=default_admin_password,
roles=['administrator'])
user.name = default_admin_username
db.session.add(user)
db.session.commit()

View File

@ -36,9 +36,15 @@
<li class="nav-item active"> <li class="nav-item active">
<a class="nav-link" href="{{ url_for('UploadView:index') }}">Upload</a> <a class="nav-link" href="{{ url_for('UploadView:index') }}">Upload</a>
</li> </li>
{% if current_user.has_role('administrator') %}
<li class="nav-item active">
<a class="nav-link text-danger" href="/admin">Administrate</a>
</li>
{% endif %}
<li class="nav-item active"> <li class="nav-item active">
<a class="nav-link" href="{{ url_for_security('logout') }}">Logout</a> <a class="nav-link" href="{{ url_for_security('logout') }}">Logout</a>
</li> </li>
{% else %} {% else %}
<li class="nav-item active"> <li class="nav-item active">
<a class="nav-link" href="{{ url_for_security('login') }}">Login</a> <a class="nav-link" href="{{ url_for_security('login') }}">Login</a>

View File

@ -1,5 +1,5 @@
from .healthchecks import health_database_status from .healthchecks import health_database_status
from .security import security, init_security_real_good from .security import security, user_datastore, init_security_real_good, AuthenticatedModelView, AuthenticatedAdminIndexView
from .config import Config from .config import Config
from .storage import storage from .storage import storage
from .md5stuffs import calculate_md5_sum_for_file, write_file_from_stream_to_file_like_while_calculating_md5 from .md5stuffs import calculate_md5_sum_for_file, write_file_from_stream_to_file_like_while_calculating_md5

View File

@ -38,6 +38,11 @@ class Config:
MINIO_SECRET_KEY = os.environ["MINIO_SECRET_KEY"] MINIO_SECRET_KEY = os.environ["MINIO_SECRET_KEY"]
MINIO_SECURE = os.environ.get("MINIO_SECURE", "true").upper() == 'TRUE' MINIO_SECURE = os.environ.get("MINIO_SECURE", "true").upper() == 'TRUE'
# Admin stuff
DEFAULT_ADMIN_USER = os.environ.get("DEFAULT_ADMIN_USER")
DEFAULT_ADMIN_PASSWORD = os.environ.get("DEFAULT_ADMIN_PASSWORD")
DEFAULT_ADMIN_EMAIL = os.environ.get("DEFAULT_ADMIN_EMAIL")
# Some constant configured stuff configs # Some constant configured stuff configs
SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_TRACK_MODIFICATIONS = False
SECURITY_REGISTERABLE = True SECURITY_REGISTERABLE = True

View File

@ -1,9 +1,12 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from flask import abort
from flask_security import Security, SQLAlchemyUserDatastore from flask_security import Security, SQLAlchemyUserDatastore, current_user
from flask_security.forms import RegisterForm, Required from flask_security.forms import RegisterForm, Required
from wtforms import StringField from wtforms import StringField
from flask_admin.contrib.sqla import ModelView
from flask_admin import AdminIndexView
from models import db, User, Role from models import db, User, Role
""" """
@ -26,3 +29,29 @@ security = Security() # Will be initiated at init_app
def init_security_real_good(app): def init_security_real_good(app):
security.init_app(app, datastore=user_datastore, register_form=ExtendedRegisterForm) security.init_app(app, datastore=user_datastore, register_form=ExtendedRegisterForm)
class AuthenticatedModelView(ModelView):
def is_accessible(self):
return (
current_user.is_active and
current_user.is_authenticated and
current_user.has_role('administrator')
)
def _handle_view(self, name):
if not self.is_accessible():
abort(401)
class AuthenticatedAdminIndexView(AdminIndexView):
def is_accessible(self):
return (
current_user.is_active and
current_user.is_authenticated and
current_user.has_role('administrator')
)
def _handle_view(self, name):
if not self.is_accessible():
abort(401)