from flask import Blueprint, request, session, render_template, redirect, url_for, abort from user_agents import parse as user_agent from .database import Database from .admin_log import AdminLog from .users import Users from .exceptions import * from .config import * bp = Blueprint("admin", __name__, url_prefix="/admin") db = Database(DATABASE_PATH) users = Users(USERS_PATH) admin_log = AdminLog(ADMIN_LOG_PATH) @bp.before_request def check_privilege(): # only clients who have obtained a session and sent it in the Cookie header # will have a decryptable username here if "username" not in session: return redirect(url_for("auth.login")) username = session["username"] user = users.find(username) # under normal circumstances it must exist if user["role"] != "admin": abort(403) @bp.route("/") def index(): umbrellas = db.read() statuses = Database.group_by_status(umbrellas) return render_template( "admin/index.html", umbrellas=umbrellas, available=statuses["available"], lent=statuses["lent"], overdue=statuses["overdue"], mobile=user_agent(request.user_agent.string).is_mobile, ) @bp.route("/umbrellas") def umbrellas(): umbrellas = db.read() edit = request.args.get("edit") error = request.args.get("error") template = ( "admin/umbrellas_mobile.html" if user_agent(request.user_agent.string).is_mobile else "admin/umbrellas_desktop.html" ) return render_template( template, umbrellas=umbrellas, edit=int(edit) if edit else None, error=error, ) @bp.route("/umbrellas/edit", methods=["POST"]) def umbrellas_edit(): data = {} for key in [ "serial", "alias", "status", "tenant_name", "tenant_id", "tenant_phone", "tenant_email", "lent_at", ]: data[key] = request.form.get(key) error = None try: db.update(data) except UmbrellaValueError as e: # invalid field is in `e.message`. return redirect( "{0}?edit={1}&error={2}".format( url_for("admin.umbrellas"), request.form.get("serial"), e.message ) ) except UmbrellaNotFoundError: pass # impossible on web console return redirect(url_for("admin.umbrellas")) @bp.route("/logs") def logs(): logs = admin_log.read() return render_template("admin/logs.html", logs=logs)