from flask import flash, url_for from flask_admin.menu import MenuLink from flask_security import current_user from sqlalchemy import func, select from . import app, db from .models import Semester def flashRandomPassword(password): flash(f"Random password: {password}", category="warning") def sortedSemestersStartingWithNewest(limit=0): # Inserting an older semester is not allowed! # Therefore, the id is enough. stmt = select(Semester).order_by(Semester.id.desc()) if limit > 0: stmt = stmt.limit(limit) return db.session.execute(stmt).scalars() def lastSemester(): return sortedSemestersStartingWithNewest(limit=1).first() def userActiveSemester(flashWarning=False): lastSemesterId = lastSemester().id if current_user.active_semester_id is None: current_user.active_semester_id = lastSemesterId db.session.commit() elif current_user.active_semester_id != lastSemesterId: activeSemester = db.session.get(Semester, current_user.active_semester_id) if activeSemester is not None: if flashWarning: flash(f"You are in the old semester {activeSemester.repr()}!", "warning") else: current_user.active_semester_id = lastSemesterId db.session.commit() flash("Semester changed!", "warning") return db.session.get(Semester, current_user.active_semester_id) def setUserActiveSemester(semesterId): if current_user.active_semester_id != semesterId: semester = db.session.get(Semester, semesterId) if semester is not None: try: current_user.active_semester_id = semesterId db.session.commit() except Exception as ex: flash(str(ex), "error") db.session.rollback() else: flash(f"Active semester changed to {semester.repr()}!", "warning") else: flash(f"No semester with ID {semesterId}!", "error") def initActiveSemesterMenuLinks(space): with app.app_context(): try: semesters = sortedSemestersStartingWithNewest() for semester in semesters: space.add_link( MenuLink( name=semester.repr(), url=url_for("set_semester") + "?semester_id=" + str(semester.id), category="Active semester", ) ) except Exception as ex: print( "ERROR: The Semester table does not exist yet! Therefore, menu links could not be generated. You can ignore this error if you are just initializing the database." ) else: space.add_link(MenuLink(name="Logout", url=url_for("security.logout"))) def reportBadAttempt(message): print("BAD ATTEMPT:", message) # TODO: Log def get_count(table): return db.session.scalar(select(func.count()).select_from(table))