From 68703447d8fc57c7b77b66a6acc05bf22fb7d71b Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 31 Jul 2021 14:06:45 +0000 Subject: Display inbox/outbox contents correctly As per previous commit, the contents of inboxes and outboxes were not being properly displayed, which was difficult to test because of there being very few items in the test DB. This commit includes moving functions such as prepared_output into a new file sw/util.py; including them in sw/users.py made little sense and caused a circular dependency with sw/auth.py. A stub function for item info retreival has also been created, in new file sw/items.py. --- sw/__init__.py | 3 +- sw/auth.py | 46 +++++++++++++++---- sw/db.py | 80 ++++++++++++++++++++++++++++++++++ sw/items.py | 8 ++++ sw/schema.sql | 15 +++---- sw/templates/base.html | 2 +- sw/templates/get_user_inbox_page.json | 6 ++- sw/templates/get_user_outbox_page.json | 6 ++- sw/templates/login.html | 14 ++++++ sw/users.py | 80 ++++++++++------------------------ sw/util.py | 43 ++++++++++++++++++ tests/data.sql | 2 +- tests/test_users.py | 13 ++++++ 13 files changed, 238 insertions(+), 80 deletions(-) create mode 100644 sw/items.py create mode 100644 sw/templates/login.html create mode 100644 sw/util.py diff --git a/sw/__init__.py b/sw/__init__.py index 6f2869a..cb9e8c9 100644 --- a/sw/__init__.py +++ b/sw/__init__.py @@ -2,7 +2,7 @@ import os from flask import Flask -from sw import auth, db, users +from sw import auth, db, users, items def create_app(test_config=None): @@ -27,5 +27,6 @@ def create_app(test_config=None): app.register_blueprint(auth.bp) app.register_blueprint(users.bp) + app.register_blueprint(items.bp) return app diff --git a/sw/auth.py b/sw/auth.py index 4fd0f68..1f9e5d8 100644 --- a/sw/auth.py +++ b/sw/auth.py @@ -4,6 +4,7 @@ import logging from flask import ( abort, + redirect, Blueprint, flash, g, @@ -18,6 +19,7 @@ from flask import ( from werkzeug.security import generate_password_hash, check_password_hash from sw.db import get_db +from sw.util import prepared_output bp = Blueprint("auth", __name__, url_prefix="/auth") @@ -92,24 +94,50 @@ def register(): return response -@bp.route("/login", methods=["POST"]) -@json_input -def login(): - username = request.json["username"] - password = request.json["password"] - +def login(username, password): db = get_db() user = db.execute("select * from users where username=?", (username,)).fetchone() if (user is None) or (password is None): - return "Username or password incorrect", 403 + abort(403) if not check_password_hash(user["password"], password): - return "Username or password incorrect", 403 + return False session.clear() session["user_id"] = user["id"] - return "Login Successful", 200 + + return True + + +@bp.route("/login", methods=["GET"]) +def get_login(): + if request.args: + username = request.args.get("username") + password = request.args.get("password") + + if login(username, password): + url = url_for("users.get_user_info", username=username) + return redirect(url, 200) + + # I saw it suggested online that this response should have a 401 + # status code, but lynx acts funny when this is the case. Since + # other (maybe more popular) browsers might also behave this way, + # this is being left as 200 for now. + return prepared_output("login", status=200) + + +@bp.route("/login", methods=["POST"]) +@json_input +def post_login(): + username = request.json.get("username") + password = request.json.get("password") + + if login(username, password): + return Response(status=200) + + else: + abort(403) @bp.route("/logout") diff --git a/sw/db.py b/sw/db.py index 55c0bfe..3739a62 100644 --- a/sw/db.py +++ b/sw/db.py @@ -6,6 +6,7 @@ from flask.cli import with_appcontext from werkzeug.security import generate_password_hash +from sw.time import now def get_db(): if "db" not in g: @@ -52,7 +53,86 @@ def add_user_command(username, password): db.commit() +def db_add_item(db=None, time=now(), commit=None, **kwargs): + if commit is None: + commit = db is None + + if db is None: + db = get_db() + + if "created" not in kwargs: + kwargs["created"] = time + + if "updated" not in kwargs: + kwargs["updated"] = kwargs["created"] + + db.execute( + "insert into items (actor, created, updated, content, target) " + "values (:actor, :created, :updated, :content, :target) " + ";", + defaultdict(lambda: None, kwargs), + ) + + res = db.execute("select last_insert_rowid();").fetchone()[0] + + if "actor" in kwargs: + db.execute( + "update users " + "set outbox_size = outbox_size + 1 " + "where id = :actor " + ";", + kwargs, + ) + + if commit: + db.commit() + + return res + + +def db_create_item(db=None, commit=True, **kwargs): + if commit is None: + commit = db is None + + if db is None: + db = get_db() + + item_id = db_add_item(db=db, **kwargs) + create_id = db_add_item(db=db, target=item_id, type="Create") + + if commit: + db.commit() + + return (item_id, create_id) + + +@click.command("create-note") +@click.argument("username") +@click.argument("content") +@with_appcontext +def create_note_command(username, content): + time = now() + + db = get_db() + + user = db.execute( + "select * from users " "where username=? " ";", (username,) + ).fetchone() + + # user_id = url_for("users.get_user_info", username=user["username"]) + user_id = username + + note_id, create_id = db_create_item( + db=db, actor=user_id, content=content, time=time + ) + + db.commit() + + click.echo(f"Note created at ID: {note_id} (create ID: {create_id})") + + def init_app(app): app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) app.cli.add_command(add_user_command) + app.cli.add_command(create_note_command) diff --git a/sw/items.py b/sw/items.py new file mode 100644 index 0000000..2295d02 --- /dev/null +++ b/sw/items.py @@ -0,0 +1,8 @@ +from flask import Blueprint + +bp = Blueprint("items", __name__, url_prefix="/i") + + +@bp.route("/") +def get_item_info(item_id): + pass # TODO diff --git a/sw/schema.sql b/sw/schema.sql index 97f4785..2dbd1ec 100644 --- a/sw/schema.sql +++ b/sw/schema.sql @@ -6,16 +6,7 @@ create table inbox ( recipient text, received text, - ap_content text -); - -drop table if exists outbox; - -create table outbox ( - sender text, - sent text, - - ap_content text + content_id text ); drop table if exists items; @@ -23,6 +14,10 @@ drop table if exists items; create table items ( id integer primary key, + actor text, + type text, + target text, + created text, updated text, diff --git a/sw/templates/base.html b/sw/templates/base.html index 4f2acf1..2917e0f 100644 --- a/sw/templates/base.html +++ b/sw/templates/base.html @@ -8,7 +8,7 @@
  • Log Out
  • {% else %}
  • Register
  • -
  • Log In
  • +
  • Log In
  • {% endif %} diff --git a/sw/templates/get_user_inbox_page.json b/sw/templates/get_user_inbox_page.json index 50a9f06..96bf9e8 100644 --- a/sw/templates/get_user_inbox_page.json +++ b/sw/templates/get_user_inbox_page.json @@ -12,5 +12,9 @@ "current": "{{ url_for('.get_user_inbox_page', username=user['username']) }}", "partOf": "{{ url_for('.get_user_inbox', username=user['username']) }}", -"items": {{ items }}, +"items": [ + {% for item in items %} + "{{ item }}"{{ ',' if not loop.last }} + {% endfor %} +], {% endblock %} diff --git a/sw/templates/get_user_outbox_page.json b/sw/templates/get_user_outbox_page.json index b25a5ce..2f3936f 100644 --- a/sw/templates/get_user_outbox_page.json +++ b/sw/templates/get_user_outbox_page.json @@ -12,5 +12,9 @@ "current": "{{ url_for('.get_user_outbox_page', username=user['username']) }}", "partOf": "{{ url_for('.get_user_outbox', username=user['username']) }}", -"items": {{ items }}, +"items": [ + {% for item in items %} + "{{ item }}"{{ "," if not loop.last }} + {% endfor %} +], {% endblock %} diff --git a/sw/templates/login.html b/sw/templates/login.html new file mode 100644 index 0000000..87cd386 --- /dev/null +++ b/sw/templates/login.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + + +{% block header %}{% block title %}Log In{% endblock %}{% endblock %} + +{% block content %} +
    +
    +
    +
    +
    + +
    +{% endblock %} diff --git a/sw/users.py b/sw/users.py index 573b58f..2df6039 100644 --- a/sw/users.py +++ b/sw/users.py @@ -14,6 +14,7 @@ import json from sw.db import get_db from sw.time import now from sw.auth import specific_user_required, json_input, from_trusted_server +from sw.util import prepared_output bp = Blueprint("users", __name__, url_prefix="/u") @@ -33,39 +34,6 @@ def ap(r): return res -def decide_response_filetype(): - res = request.accept_mimetypes.best_match( - [ - "text/html", - "application/ld+json", - "application/json", - ] - ) - - if not request.accept_mimetypes: - return (".json", "application/ld+json") - - elif res == "text/html": - return (".html", "text/html") - - elif res == "application/json": - return (".json", "application/json") - - elif res == "application/ld+json": - return (".json", "application/ld+json") - - else: # res is None - abort(406) - - -def prepared_output(filename, **kwargs): - ext, mime = decide_response_filetype() - - body = render_template(f"{filename}{ext}", **kwargs) - - return Response(body, content_type=mime) - - @bp.route("/") def get_user_info(username): db = get_db() @@ -108,20 +76,12 @@ def get_user_inbox_page(username): (username, max_id, max_id, inbox_fetch_limit), ).fetchall() - def ap(r): - def f(k): - return k.startswith("ap_") and r[k] is not None - - res = {k[3:]: r[k] for k in filter(f, r.keys())} - - return json.dumps(res) - ids = [x["id"] for x in res] return prepared_output( "get_user_inbox_page", user=g.user, - items=json.dumps([ap(x) for x in res]), + items=[url_for("items.get_item_info", item_id=x) for x in ids], max_id=max(ids, default=None), min_id=min(ids, default=None), ) @@ -163,8 +123,10 @@ def post_user_inbox_item(username): db = get_db() time = now() + # TODO: this currently doesn't store anonymous/dereferenced objects correctly + res = db.execute( - "insert into inbox (recipient, received, ap_content) values (?,?,?) ;", + "insert into inbox (recipient, received, content_id) values (?,?,?) ;", (username, time, str(data)), ) @@ -182,8 +144,8 @@ def get_user_outbox(username): return prepared_output("get_user_outbox", user=g.user) -@bp.route("/username/outbox/items") -def get_user_outbox_page(username, page_index): +@bp.route("//outbox/items") +def get_user_outbox_page(username): db = get_db() outbox_fetch_limit = 10 # TODO: give this variable a home @@ -191,27 +153,33 @@ def get_user_outbox_page(username, page_index): max_id = request.args.get("max_id") res = db.execute( - "select * from outbox " - "where sender=? " - "and sent 0 + assert all([("id" in item or isinstance(item, str)) for item in items]) + + def test_get_user_inbox_page_after_logout(app, client, auth): with app.app_context(): inbox_id = url_for("users.get_user_inbox", username="test") -- cgit v1.2.1