summaryrefslogtreecommitdiff
path: root/sw
diff options
context:
space:
mode:
authorTom Harley2021-07-31 14:06:45 +0000
committerTom Harley2021-07-31 19:30:35 +0000
commit68703447d8fc57c7b77b66a6acc05bf22fb7d71b (patch)
tree715006453d66889e210fd41f17aff9153f9a5092 /sw
parentAdd templates (diff)
downloadswap-68703447d8fc57c7b77b66a6acc05bf22fb7d71b.tar.gz
swap-68703447d8fc57c7b77b66a6acc05bf22fb7d71b.zip

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.

Diffstat (limited to 'sw')
-rw-r--r--sw/__init__.py3
-rw-r--r--sw/auth.py46
-rw-r--r--sw/db.py80
-rw-r--r--sw/items.py8
-rw-r--r--sw/schema.sql15
-rw-r--r--sw/templates/base.html2
-rw-r--r--sw/templates/get_user_inbox_page.json6
-rw-r--r--sw/templates/get_user_outbox_page.json6
-rw-r--r--sw/templates/login.html14
-rw-r--r--sw/users.py80
-rw-r--r--sw/util.py43
11 files changed, 224 insertions, 79 deletions
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("/<item_id>")
+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 @@
<li><a href="{{ url_for('auth.logout') }}">Log Out</a></li>
{% else %}
<li><a href="{{ url_for('auth.register') }}">Register</a></li>
- <li><a href="{{ url_for('auth.login') }}">Log In</a></li>
+ <li><a href="{{ url_for('auth.get_login') }}">Log In</a></li>
{% endif %}
</ul>
</nav>
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 %}
+<form action="{{ url_for('.get_login') }}">
+ <label for="username">Username:</label><br>
+ <input type="text" id="username" name="username"><br>
+ <label for="password">Password:</label><br>
+ <input type="password" id="password" name="password"><br>
+ <input type="submit" value="Log in">
+</form>
+{% 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("/<username>")
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("/<username>/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<? "
- "order by sent desc "
- "limit ? "
+ "select * from items "
+ "where actor=:actor "
+ "and (id <= :max_id or :max_id is null) "
+ "order by id desc "
+ "limit :limit "
";",
- (username, page_index, outbox_fetch_limit),
+ {
+ "actor": username,
+ "max_id": max_id,
+ "limit": outbox_fetch_limit,
+ },
).fetchall()
def ap(r):
def f(k):
- return k.startswith("ap_") and r[k] is not None
+ return r[k] is not None
- res = {k[3:]: r[k] for k in filter(f, r.keys())}
+ res = {k: r[k] for k in filter(f, r.keys())}
return res
+ ids = [x["id"] for x in res]
+
return prepared_output(
"get_user_outbox_page",
user=g.user,
- items=[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),
)
@@ -228,7 +196,7 @@ def post_user_outbox_item(username):
item_id = None
if "id" not in data:
res = db.exec(
- "insert into items (created, updated, ap_content) "
+ "insert into items (created, updated, content_id) "
"output Inserted.id "
"values (?,?,?) "
";",
@@ -247,7 +215,7 @@ def post_user_outbox_item(username):
if not is_ap_activity(data):
activity = create_wrapper(item_id)
res = db.exec(
- "insert into items (created, updated, ap_content) "
+ "insert into items (created, updated, content_id) "
"output Inserted.id "
"values (?,?,?) "
";",
diff --git a/sw/util.py b/sw/util.py
new file mode 100644
index 0000000..de80466
--- /dev/null
+++ b/sw/util.py
@@ -0,0 +1,43 @@
+from flask import request, abort, Response, render_template
+
+from jinja2.exceptions import TemplateNotFound
+
+
+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, status=200, **kwargs):
+ ext, mime = decide_response_filetype()
+
+ try:
+ body = render_template(f"{filename}{ext}", **kwargs)
+
+ except TemplateNotFound:
+ # TODO
+ # Should probably try the other file extensions available
+ # rather than error out if the first one fails
+ abort(406)
+
+ return Response(body, content_type=mime, status=status)