1
0
Fork 0
mirror of https://codeberg.org/Mo8it/AdvLabDB.git synced 2024-11-08 21:21:06 +00:00
AdvLabDB/advlabdb/routes.py

282 lines
10 KiB
Python

import json
from advlabdb import app, user_datastore
from flask import render_template, request, url_for, flash, redirect, session
from flask_security import auth_required, roles_required, hash_password, current_user
from advlabdb.utils import *
from advlabdb.models import *
from advlabdb.forms import *
@app.context_processor
def util_processor():
def semesterDropDownItems():
semesters = Semester.query.all()
items = []
for semester in semesters:
items.append('<li><a class="dropdown-item" href="' + url_for("set_semester") + "?semester_id=" +
str(semester.id) + '">' + semester.label + '</a></li>')
return items
def activeSemesterLabel():
lastSemesterId = Semester.query.all()[-1].id
if "activeSemesterId" not in session:
session["activeSemesterId"] = lastSemesterId
elif session["activeSemesterId"] != lastSemesterId:
flash(f"You are in the old semester {Semester.query.get(session['activeSemesterId']).label}!",
"warning")
return Semester.query.get(session["activeSemesterId"]).label
def navbarItems(title):
adminPages = ["Students", "Assistants", "Experiments", "Appointments", "Groups", "Users", "Semesters"]
assistantPages = ["Students", "Assistants", "Experiments", "Appointments", "Groups"]
if current_user.is_authenticated:
roleNames = [role.name for role in current_user.roles]
if "assistant" in roleNames:
pages = assistantPages
if "admin" in roleNames:
for p in adminPages:
if p not in pages:
pages.append(p)
elif "admin" in roleNames:
pages = adminPages
pages.append("Logout")
else:
pages = ["Login"]
items = []
for page in pages:
if page == title:
active = " active"
else:
active = ""
items.append('<a class="nav-link' + active + '" href="' + titleToTemplate(page) + '">' + page + '</a>')
return items
return dict(semesterDropDownItems=semesterDropDownItems,
activeSemesterLabel=activeSemesterLabel,
navbarItems=navbarItems,
current_user=current_user,
)
@app.route("/")
def index():
return render_template("index.html",
)
@app.route("/students")
@roles_required("admin")
def students():
semester = Semester.query.get(session["activeSemesterId"])
parts = semester.parts
tables = []
tablesLabels = []
headerAndDataList = [["Student number", "row.student.student_number"],
["First name", "row.student.first_name"],
["Last name", "row.student.last_name"],
["Email", "row.student.email"],
["GN", "row.group.number"],
["Bachelor thesis", "row.student.bachelor_thesis"],
["BT WG", "row.student.bachelor_thesis_work_group"],
["Note", "row.student.note"],
["Final part mark", "row.final_part_mark"],
["Experiemt marks", "row.experiment_marks"],
["Parts", "[ps.part for ps in row.student.part_students]"]]
for part in parts:
tablesLabels.append("Part " + part.label + ":")
tables.append(makeTable(headerAndDataList=headerAndDataList,
rows=part.part_students))
return render_template("students.html",
tables=tables,
tablesLabels=tablesLabels,
)
@app.route("/assistants")
@roles_required("admin")
def assistants():
headerAndDataList = [["First name", "row.first_name"],
["Last name", "row.last_name"],
["Email", "row.email"],
["Phone number", "row.phone_number"],
["Mobile phone number", "row.mobile_phone_number"],
["Room", "row.room"],
["Building", "row.building"],
["User", "row.user"],
["Appointments", "row.appointments"],
["Experiemt marks", "row.experiment_marks"]]
table = makeTable(headerAndDataList=headerAndDataList,
rows=Assistant.query.filter(Assistant.user_id != None).all())
return render_template("assistants.html",
table=table,
)
@app.route("/experiments")
@roles_required("admin")
def experiments():
semester = Semester.query.get(session["activeSemesterId"])
parts = semester.parts
tables = []
tablesLabels = []
headerAndDataList = [["Number", "row.experiment.number"],
["Name", "row.experiment.name"],
["Assistants", "row.assistants"],
["Groups with this ex.", "[gEx.group.number for gEx in row.group_experiments]"]]
for part in parts:
tablesLabels.append("Part " + part.label + ":")
tables.append(makeTable(headerAndDataList=headerAndDataList,
rows=part.part_experiments))
return render_template("experiments.html",
tables=tables,
tablesLabels=tablesLabels,
)
@app.route("/appointments")
@roles_required("admin")
def appointments():
return render_template("appointments.html",
)
@app.route("/groups")
@roles_required("admin")
def groups():
semester = Semester.query.get(session["activeSemesterId"])
parts = semester.parts
tables = []
tablesLabels = []
headerAndDataList = [["Number", "row.number"],
["Students",
"[ps.student.first_name + ' ' + ps.student.last_name for ps in row.part_students]"],
["Experiments (appointments)",
"[str(gx.part_experiment.experiment.number) + ' (' + str([appointmentDate(a.date) for a in gx.appointments]) + ')' for gx in row.group_experiments]"]]
for part in parts:
tablesLabels.append("Part " + part.label + ":")
tables.append(makeTable(headerAndDataList=headerAndDataList,
rows=part.groups))
return render_template("groups.html",
tables=tables,
tablesLabels=tablesLabels,
)
@app.route("/users", methods=["GET", "POST"])
@roles_required("admin")
def users():
if request.method == 'POST':
if "registerUser" in request.form:
return redirect(url_for("register"))
else:
headerAndDataList = [["Email", "row.email"],
["Roles", "[role.name for role in row.roles]"],
["Assistant", "row.assistant"]]
activeUsersTable = makeTable(headerAndDataList=headerAndDataList,
rows=User.query.filter(User.active == True).all(),
tableId="activeUsersTable")
inactiveUsersTable = makeTable(headerAndDataList=headerAndDataList,
rows=User.query.filter(User.active == False).all(),
tableId="inactiveUsersTable")
return render_template("users.html",
activeUsersTable=activeUsersTable,
inactiveUsersTable=inactiveUsersTable,
)
@app.route("/deactivate_users", methods=["GET"])
@roles_required("admin")
def deactivate_users():
usersEmails = json.loads(request.args.get("json"))
deactivatedUsersEmails = []
for email in usersEmails:
user = User.query.filter(User.email == email).first()
if user == current_user:
flash("You have tried to deactivate yourself as user!", "danger")
continue
if user_datastore.deactivate_user(user):
deactivatedUsersEmails.append(email)
db.session.commit()
deactivatedUsersEmailsLen = len(deactivatedUsersEmails)
if deactivatedUsersEmailsLen == 0:
flash(f"No users deactivated!", "warning")
else:
flash(f"{deactivatedUsersEmailsLen} Users with emails {deactivatedUsersEmails} deactivated!", "success")
return redirect(url_for("users"))
@app.route("/semesters")
@roles_required("admin")
def semesters():
headerAndDataList = [["Label", "row.label"],
["Parts", "row.parts"]]
table = makeTable(headerAndDataList=headerAndDataList,
rows=Semester.query.all())
return render_template("semesters.html",
table=table,
)
@app.route("/set_semester", methods=["GET"])
@auth_required()
def set_semester():
session["activeSemesterId"] = int(request.args.get("semester_id"))
return redirect(request.referrer)
@app.route("/register", methods=["GET", "POST"])
@roles_required("admin")
def register():
form = RegistrationForm()
if form.validate_on_submit():
password = randomPassword()
passwordHash = hash_password(password)
email = form.email.data.lower()
assistant = form.assistant.data
admin = form.admin.data
registered = True
if admin:
if assistant:
roles = ["admin", "assistant"]
else:
roles = ["admin"]
flash("You have registered a new admin!", "danger")
elif assistant:
roles = ["assistant"]
else:
flash("The user has to be assistant and/or admin!", "warning")
registered = False
if registered:
newUser = user_datastore.create_user(email=email, password=passwordHash, roles=roles)
db.session.commit()
return render_template("registered.html",
email=email,
password=password,
roles=[role.name for role in newUser.roles],
)
return render_template("register.html",
form=form,
)