From e1214eeb40c0b5c3060b370c19f10696eb62f135 Mon Sep 17 00:00:00 2001 From: Paul Brinkmeier Date: Sun, 20 Aug 2023 11:29:20 +0200 Subject: [PATCH] Use session to store authentication info instead of cookie --- jon/__init__.py | 3 ++- jon/auth.py | 42 ++++++++++++++----------------- jon/templates/base.html | 10 ++++---- jon/templates/location/index.html | 2 +- 4 files changed, 27 insertions(+), 30 deletions(-) diff --git a/jon/__init__.py b/jon/__init__.py index 01498d4..44ed8af 100644 --- a/jon/__init__.py +++ b/jon/__init__.py @@ -34,7 +34,8 @@ def create_app(): app.register_blueprint(location.bp) app.register_blueprint(inventory.bp) app.register_blueprint(entry.bp) - app.register_blueprint(auth.auth) + app.register_blueprint(auth.bp) + @app.route("/") def index(): return render_template("index.html") diff --git a/jon/auth.py b/jon/auth.py index b843f2d..be92f46 100644 --- a/jon/auth.py +++ b/jon/auth.py @@ -1,17 +1,18 @@ -from flask import Blueprint, request, redirect, make_response -from . import db import random import string -auth = Blueprint('auth', __name__) +from flask import Blueprint, make_response, request, redirect, session + +bp = Blueprint('auth', __name__, url_prefix="/auth") + ACCESS_TOKEN = ''.join(random.choice(string.ascii_lowercase) for i in range(64)) + ERROR_TEXT = """ For security-reasons we must make sure you are the person who executed jon :D
-

@@ -20,25 +21,20 @@ ERROR_TEXT = """ def before_request(): - token = request.cookies.get('token') - if token == ACCESS_TOKEN: - pass - else: - token = request.args.get('token') - next: str = request.args.get('next') or "/" - if token is None: - # TODO: make template - return ERROR_TEXT.format(next=next) + "No token provided!" - if token != ACCESS_TOKEN: - return ERROR_TEXT.format(next=next) + "Invalid token!" - else: - resp = make_response(redirect(next)) - resp.set_cookie('token', token) - return resp + """ + If the correct token query parameter is passed along with any request, + we mark this session authenticated by setting `session["authenticated"]`. + """ + if "token" in request.args: + if request.args["token"] == ACCESS_TOKEN: + session["authenticated"] = () + return redirect(request.path) + + if not "authenticated" in session: + return ERROR_TEXT, 403 -@auth.route('/logout') +@bp.get("/logout") def logout(): - resp = make_response(redirect("/")) - resp.set_cookie('token', "") - return resp + session.pop("authenticated", None) + return redirect("/") diff --git a/jon/templates/base.html b/jon/templates/base.html index 4398641..07b30b8 100644 --- a/jon/templates/base.html +++ b/jon/templates/base.html @@ -76,10 +76,10 @@

jon

diff --git a/jon/templates/location/index.html b/jon/templates/location/index.html index c66f8d2..c395213 100644 --- a/jon/templates/location/index.html +++ b/jon/templates/location/index.html @@ -1,7 +1,7 @@ {% extends "base.html" %} {% block content %} -
+