Skip to content

Commit

Permalink
cleanup, move routes to routes.py, add test for protected zones & bro…
Browse files Browse the repository at this point in the history
…ken templates
  • Loading branch information
sondregronas committed Aug 6, 2023
1 parent 724b703 commit 8d56fc0
Show file tree
Hide file tree
Showing 31 changed files with 1,028 additions and 859 deletions.
16 changes: 13 additions & 3 deletions BookingSystem/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ def get_items() -> flask.Response:
return flask.jsonify([item.api_repr() for item in items])


@api.route('/items/available', methods=['GET'])
@login_required(admin_only=True, api=True)
def get_items_available() -> flask.Response:
"""Get all items in the database for frontend display."""
items = inventory.get_all_available()
return flask.jsonify([item.api_repr() for item in items])


@api.route('/items/unavailable', methods=['GET'])
@login_required(admin_only=True, api=True)
def get_items_unavailable() -> flask.Response:
Expand Down Expand Up @@ -68,7 +76,6 @@ def add_item() -> flask.Response:
def edit_item(item_id: str) -> flask.Response:
"""Edit an item in the database."""
form = flask.request.form
print(form)
item = {key: form.get(key) for key in form.keys() if key in Item.__annotations__}
item = Item(**item)

Expand Down Expand Up @@ -119,12 +126,12 @@ def print_label(item_id: str) -> flask.Response:
def book_equipment() -> flask.Response:
"""Book out equipment for a user."""
form = flask.request.form
user = form.get('user')
userid = form.get('user')
days = form.get('days')
item_ids = form.getlist('equipment')

for item in item_ids:
inventory.register_out(item_id=item, user=user, days=days)
inventory.register_out(item_id=item, userid=userid, days=days)
return flask.Response('Utstyr ble utlevert.', status=200)


Expand Down Expand Up @@ -179,6 +186,7 @@ def update_groups() -> flask.Response:
"""Update a class in the database."""
con = sqlite3.connect(DATABASE)
cur = con.cursor()
# noinspection SqlWithoutWhere
cur.execute('DELETE FROM groups')
con.commit()

Expand All @@ -198,6 +206,7 @@ def update_categories() -> flask.Response:
"""Update every category in the database."""
con = sqlite3.connect(DATABASE)
cur = con.cursor()
# noinspection SqlWithoutWhere
cur.execute('DELETE FROM categories')
con.commit()

Expand All @@ -217,6 +226,7 @@ def update_emails() -> flask.Response:
"""Update every email in the database."""
con = sqlite3.connect(DATABASE)
cur = con.cursor()
# noinspection SqlWithoutWhere
cur.execute('DELETE FROM emails')
con.commit()

Expand Down
120 changes: 9 additions & 111 deletions BookingSystem/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,9 @@

import api
import feide
import groups
import inventory
import mail
import user
from __init__ import logger, KIOSK_FQDN, LABEL_SERVER
from db import init_db, add_admin
from utils import login_required
import routes
from __init__ import logger
from db import init_db


def create_app() -> flask.Flask:
Expand All @@ -31,8 +27,10 @@ def create_app() -> flask.Flask:

Session(app)

# Register blueprints
app.register_blueprint(api.api)
app.register_blueprint(feide.feide)
app.register_blueprint(routes.app)

@app.template_filter('strftime')
def _jinja2_filter_datetime(date, fmt='%d.%m.%Y') -> str:
Expand All @@ -43,115 +41,15 @@ def _jinja2_filter_strftime(date, fmt='%d.%m.%Y') -> str:
return datetime.fromtimestamp(float(date)).strftime(fmt)

@app.errorhandler(401)
def unauthorized(e) -> flask.Response:
def unauthorized(_) -> flask.Response:
logger.warning(f'Unauthorized access: {flask.request.url} from {flask.request.remote_addr}')
return flask.redirect(flask.url_for('login'))
return flask.redirect(flask.url_for('app.login'))

@app.errorhandler(403)
def unauthorized(e) -> flask.Response:
def unauthorized(_) -> flask.Response:
flask.session.clear()
logger.warning(f'Unauthorized access: {flask.request.url} from {flask.request.remote_addr}')
return flask.redirect(flask.url_for('login'))

@app.route('/')
@login_required()
def index() -> str:
if flask.session.get("user").is_admin:
return flask.render_template('index_admin.html', overdue_items=inventory.get_all_overdue())
return flask.render_template('index_student.html', all_groups=groups.get_all())

@app.route('/login')
def login() -> str | flask.Response:
if flask.session.get("user"):
return flask.redirect(flask.url_for('index'))
if KIOSK_FQDN and flask.request.headers.get('Host') == KIOSK_FQDN:
flask.session['method'] = 'kiosk'
r = flask.request.referrer
if r and r != flask.url_for('login'):
return flask.redirect(r)
return flask.redirect(flask.url_for('index'))
return flask.render_template('login.html')

@app.route('/register')
@login_required()
def register() -> flask.Response:
user = flask.session.get("user")
if user.is_admin and not user.exists:
add_admin(flask.session.get("user").__dict__)

return flask.redirect(flask.url_for('index'))

@app.route('/logout')
def logout() -> flask.Response:
flask.session.clear()
return flask.redirect(flask.url_for('login'))

@app.route('/admin')
@login_required(admin_only=True)
def admin_settings() -> str:
return flask.render_template('admin_settings.html', all_groups=groups.get_all(),
all_categories=inventory.all_categories(),
all_emails=mail.get_all_emails(),
last_sent=mail.get_last_sent())

@app.route('/audits')
@login_required(admin_only=True)
def audits() -> str:
"""All audits in data/audits.log"""
log = open('data/audits.log', 'r').readlines()
log = [{
'timestamp': audit.split('|')[0].strip(),
'event': audit.split('|')[1].split(' - ')[0].strip(),
'message': ''.join(audit.split(' - ')[1:]).strip()
} for audit in log if audit.strip()]
return flask.render_template('audits.html', audits=log)

@app.route('/inventar')
@login_required(admin_only=True)
def inventar() -> str:
return flask.render_template('inventar.html', items=inventory.get_all())

@app.route('/inventar/add')
@login_required(admin_only=True)
def inventar_add() -> str:
return flask.render_template('inventar_add.html', categories=inventory.all_categories())

@app.route('/inventar/edit/<item_id>')
@login_required(admin_only=True)
def edit_item(item_id: str) -> str:
return flask.render_template('inventar_edit.html', item=inventory.get(item_id),
categories=inventory.all_categories())

@app.route('/inventar/print/<item_id>')
@login_required(admin_only=True)
def print_item(item_id: str) -> str:
return flask.render_template('inventar_print.html', item=inventory.get(item_id))

@app.route('/booking')
@login_required(admin_only=True)
def booking() -> str:
return flask.render_template('booking.html',
all_users=user.get_all_active_users(),
all_items=inventory.get_all())

@app.route('/innlevering')
@login_required(admin_only=True)
def innlevering() -> str:
return flask.render_template('innlevering.html',
unavailable_items=inventory.get_all_unavailable())

@app.route('/etikettserver')
@login_required(admin_only=True)
def labelserver() -> str:
return flask.render_template('labelserver.html', labelserver_url=LABEL_SERVER)

@app.route('/ansvarsavtale')
def responsibility() -> str:
return flask.render_template('responsibility.html')

@app.route('/personvern')
def privacy() -> str:
return flask.render_template('privacy.html')
return flask.redirect(flask.url_for('app.login'))

return app

Expand Down
2 changes: 1 addition & 1 deletion BookingSystem/groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
def get_all() -> list[str]:
"""Return a list of all groups in the database."""
con = sqlite3.connect(DATABASE)
groups = [row[0] for row in con.execute('SELECT classroom FROM groups ORDER BY classroom ASC')]
groups = [row[0] for row in con.execute('SELECT classroom FROM groups ORDER BY classroom')]
con.close()
return groups
6 changes: 3 additions & 3 deletions BookingSystem/import.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
This script imports all items from the label server into the database, if they don't already exist.
You shouldn't really need this script, but it's here just in case. Whenever you print a label, the label server
keeps track of it in it's audit log. This script reads the audit log and imports all items into the database.
keeps track of it in its audit log. This script reads the audit log and imports all items into the database.
"""

import sqlite3
Expand All @@ -19,8 +19,8 @@ def get_items_from_label_server() -> list:
response = requests.get(f'{LABEL_SERVER}/audits')
json = response.json()
filtered = []
for item in [{key: value.strip() for key, value in item.items()} for item in json]:
if item['id'] not in [i['id'] for i in filtered]:
for i in [{key: value.strip() for key, value in i.items()} for i in json]:
if i['id'] not in [ii['id'] for ii in filtered]:
filtered.append(item)
return filtered

Expand Down
12 changes: 10 additions & 2 deletions BookingSystem/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,14 @@ def get_all() -> list[Item]:
return items


def get_all_available() -> list[Item]:
"""Return a JSON list of all available items in the database."""
con = sqlite3.connect(DATABASE)
items = [Item(*row) for row in con.execute('SELECT * FROM inventory WHERE available=1')]
con.close()
return items


def get_all_unavailable() -> list[Item]:
"""Return a JSON list of all unavailable items in the database."""
con = sqlite3.connect(DATABASE)
Expand Down Expand Up @@ -179,7 +187,7 @@ def _update_last_seen(item_id: str) -> None:
con.close()


def register_out(item_id: str, user: str, days: str = 1) -> None:
def register_out(item_id: str, userid: str, days: str = 1) -> None:
"""Set the item with the given ID to unavailable and register the order details."""
due_date = datetime.now() + timedelta(days=datetime.strptime(days, '%d').day)

Expand All @@ -190,7 +198,7 @@ def register_out(item_id: str, user: str, days: str = 1) -> None:
con = sqlite3.connect(DATABASE)
try:
sql = 'UPDATE inventory SET available=0, borrowed_to=:borrowed_to, order_due_date=:order_due_date WHERE id=:id'
con.execute(sql, {'id': item_id, 'borrowed_to': user, 'order_due_date': due_date})
con.execute(sql, {'id': item_id, 'borrowed_to': userid, 'order_due_date': due_date})
con.commit()
logger.info(f'{item_id} er ikke lenger tilgjengelig.')
except sqlite3.IntegrityError:
Expand Down
4 changes: 2 additions & 2 deletions BookingSystem/mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
def get_all_emails() -> list[str]:
"""Return a list of all emails in the database."""
con = sqlite3.connect(DATABASE)
emails = [row[0] for row in con.execute('SELECT email FROM emails ORDER BY email ASC')]
emails = [row[0] for row in con.execute('SELECT email FROM emails ORDER BY email')]
con.close()
return emails

Expand Down Expand Up @@ -72,7 +72,7 @@ def formatted_overdue_items() -> str:


def send_report() -> flask.Response:
"""Send an email to all emails in the database."""
"""Send an e-mail to all emails in the database."""
items = [item for item in inventory.get_all_unavailable() if item.overdue]
if not items:
update_last_sent()
Expand Down
Loading

0 comments on commit 8d56fc0

Please sign in to comment.