from flask import url_for, render_template, flash from advlabdb.customClasses import SecureModelView from flask_admin.menu import MenuLink from flask_security import hash_password from wtforms import BooleanField from advlabdb import admin, app, user_datastore, db from advlabdb.models import * from advlabdb.utils import randomPassword partsLabels = ["A/1", "A/2", "B/1", "B/2"] class UserModelView(SecureModelView): column_list = ["email", "active", "roles", "assistant"] column_searchable_list = ["email"] column_filters = ["active"] form_columns = ["email", "roles"] def create_model(self, form): password = randomPassword() passwordHash = hash_password(password) email = form.email.data.lower() print(form.roles.data[0].name) roles = [role.name for role in form.roles.data] if "admin" in roles: flash("You have registered a new admin!", "danger") model = user_datastore.create_user(email=email, password=passwordHash, roles=roles) db.session.commit() flash(f"{email} registered with roles: {', '.join([role.name for role in form.roles.data])}.", category="success") flash(f"Random password: {password}", category="warning") return model class RoleModelView(SecureModelView): column_exclude_list = ["update_datetime"] class SemesterModelView(SecureModelView): column_list = ["label", "parts"] form_columns = ["label", "create_parts"] form_extra_fields = { "create_parts": BooleanField("Create parts:" + ", ".join(partsLabels) + ".", default=True) } def after_model_change(self, form, model, is_created): if is_created and form.create_parts.data: for part in self.parts: db.session.add(Part(label=part, semester=model)) db.session.commit() class PartModelView(SecureModelView): can_view_details = True column_details_list = ["label", "semester", "part_experiments", "part_students", "groups"] form_columns = ["label", "semester"] class StudentModelView(SecureModelView): can_view_details = True column_list = ["student_number", "first_name", "last_name", "email", "part_students"] column_details_list = column_list + ["bachelor_thesis", "bachelor_thesis_work_group"] column_searchable_list = ["student_number", "email", "first_name", "last_name"] form_columns = column_list admin.add_view(StudentModelView(Student, db.session)) admin.add_view(SecureModelView(PartStudent, db.session)) admin.add_view(SecureModelView(Group, db.session)) admin.add_view(SecureModelView(GroupExperiment, db.session)) admin.add_view(SecureModelView(Experiment, db.session)) admin.add_view(SecureModelView(PartExperiment, db.session)) admin.add_view(SecureModelView(Assistant, db.session)) admin.add_view(SecureModelView(Appointment, db.session)) admin.add_view(PartModelView(Part, db.session)) admin.add_view(SemesterModelView(Semester, db.session)) admin.add_view(SecureModelView(ExperimentMark, db.session)) admin.add_view(UserModelView(User, db.session)) admin.add_view(RoleModelView(Role, db.session)) with app.app_context(): admin.add_link(MenuLink(name="Home", url=url_for("index"), category="Links"))