summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Harley2021-07-03 00:18:13 +0000
committerTom Harley2021-07-03 00:18:13 +0000
commit7c5c6c52250ca57257ab4af2cc9cdf4425595ec0 (patch)
treed36019286125bf984e0c267645d53ff562533ebf
downloadswap-7c5c6c52250ca57257ab4af2cc9cdf4425595ec0.tar.gz
swap-7c5c6c52250ca57257ab4af2cc9cdf4425595ec0.zip

Initial commit

-rw-r--r--.gitignore5
-rw-r--r--MANIFEST.in5
-rw-r--r--conftest.py0
-rw-r--r--default.nix36
-rw-r--r--requirements.txt4
-rw-r--r--run.sh5
-rw-r--r--setup.cfg7
-rw-r--r--setup.py10
-rw-r--r--sw/__init__.py35
-rw-r--r--sw/ap.py9
-rw-r--r--sw/auth.py119
-rw-r--r--sw/db.py46
-rw-r--r--sw/schema.sql48
-rw-r--r--tests/conftest.py53
-rw-r--r--tests/data.sql4
-rw-r--r--tests/test_auth.py40
-rw-r--r--tests/test_db.py30
-rw-r--r--tests/test_factory.py11
18 files changed, 467 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..858c3ef
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+__pycache__/
+.coverage
+.venv/
+instance/
+sw.egg-info/
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..9d49a90
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,5 @@
+include sw/schema.sql
+graft sw/static
+graft sw/templates
+graft tests
+global-exclude *.pyc
diff --git a/conftest.py b/conftest.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/conftest.py
diff --git a/default.nix b/default.nix
new file mode 100644
index 0000000..91d8df4
--- /dev/null
+++ b/default.nix
@@ -0,0 +1,36 @@
+with import <nixpkgs> {};
+
+let
+
+ # werkzeug workaround related to:
+ # https://github.com/NixOS/nixpkgs/issues/72345#issuecomment-812970457
+
+ my-python-packages = (pypkgs: let
+ werkzeug' = pypkgs.werkzeug.overrideAttrs (old: {
+ postPatch = ''
+ substituteInPlace src/werkzeug/_reloader.py \
+ --replace "rv = [sys.executable]" "return sys.argv"
+ '';
+ doCheck = false;
+ });
+
+ flask' = pypkgs.flask.override { werkzeug = werkzeug'; };
+
+ in with pypkgs; [
+ flask'
+ pytest
+ docopt
+ coverage
+ black
+ ]);
+
+ python' = python3.withPackages my-python-packages;
+
+in
+ stdenv.mkDerivation {
+ name = "trseubgti";
+ buildInputs = [
+ python'
+ ag
+ ];
+ }
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..8bed372
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,4 @@
+flask
+docopt
+pytest
+coverage
diff --git a/run.sh b/run.sh
new file mode 100644
index 0000000..8d8a962
--- /dev/null
+++ b/run.sh
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+
+echo flask "$@"
+FLASK_APP=sw FLASK_ENV=development flask "$@"
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..ce934b4
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,7 @@
+[tool:pytest]
+testpaths = tests
+
+[coverage:run]
+branch = True
+source =
+ sw
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..2715667
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,10 @@
+from setuptools import find_packages, setup
+
+setup(
+ name="sw",
+ version="1.0.0",
+ packages=find_packages(),
+ include_package_data=True,
+ zip_safe=False,
+ install_requires=["flask",],
+)
diff --git a/sw/__init__.py b/sw/__init__.py
new file mode 100644
index 0000000..2601940
--- /dev/null
+++ b/sw/__init__.py
@@ -0,0 +1,35 @@
+import os
+
+from flask import Flask
+
+from sw import auth, ap, db
+
+
+def create_app(test_config=None):
+ app = Flask(__name__, instance_relative_config=True)
+ app.config.from_mapping(
+ SECRET_KEY="dev", DATABASE=os.path.join(app.instance_path, "sw.sqlite"),
+ )
+
+ if test_config is None:
+ app.config.from_pyfile("config.py", silent=True)
+
+ else:
+ app.config.update(test_config)
+
+ try:
+ os.makedirs(app.instance_path)
+
+ except OSError:
+ pass
+
+ @app.route("/hello")
+ def hello():
+ return "Hello, World!"
+
+ db.init_app(app)
+
+ app.register_blueprint(auth.bp)
+ app.register_blueprint(ap.bp)
+
+ return app
diff --git a/sw/ap.py b/sw/ap.py
new file mode 100644
index 0000000..c3301f2
--- /dev/null
+++ b/sw/ap.py
@@ -0,0 +1,9 @@
+from flask import Blueprint
+
+bp = Blueprint("ap", __name__)
+
+bp.route("/u/<user>", methods=["GET"])
+
+
+def get_user(user):
+ return 500
diff --git a/sw/auth.py b/sw/auth.py
new file mode 100644
index 0000000..5429171
--- /dev/null
+++ b/sw/auth.py
@@ -0,0 +1,119 @@
+import functools
+
+from flask import (
+ Blueprint,
+ flash,
+ g,
+ redirect,
+ render_template,
+ request,
+ session,
+ url_for,
+ Response,
+)
+
+from werkzeug.security import generate_password_hash, check_password_hash
+
+from sw.db import get_db
+
+bp = Blueprint("auth", __name__, url_prefix="/auth")
+
+
+@bp.before_app_request
+def load_logged_in_user():
+ user_id = session.get("user_id")
+
+ if user_id is None:
+ g.user = None
+
+ else:
+ g.user = (
+ get_db().execute("select * from user where id=?", (user_id,)).fetchone()
+ )
+
+
+@bp.route("/register", methods=["POST"])
+def register():
+ if not request.is_json:
+ return "Request body is not JSON", 422
+
+ data = request.json
+
+ if "username" not in data:
+ return "Username required", 400
+
+ if "password" not in data:
+ return "Password required", 400
+
+ username = data["username"]
+ password = data["password"]
+
+ if username is None:
+ return "Username required", 400
+
+ if password is None:
+ return "Password required", 400
+
+ if username == "":
+ return "Username must not be empty", 400
+
+ if password == "":
+ return "Password must not be empty", 400
+
+ db = get_db()
+ existing_user = db.execute(
+ "select id from user where username=?", (username,)
+ ).fetchone()
+
+ if existing_user is not None:
+ return f"Username {username} is taken", 409
+
+ db.execute(
+ "insert into user (username, password) values (?, ?)",
+ (username, generate_password_hash(password)),
+ )
+ db.commit()
+
+ response = Response(status=201)
+ # response.location = url_for("ap.get_user", user=username)
+
+ return response
+
+
+@bp.route("/login", methods=["POST"])
+def login():
+ if not request.is_json:
+ return "Request body is not JSON", 422
+
+ username = request.json["username"]
+ password = request.json["password"]
+
+ db = get_db()
+ user = db.execute("select * from user where username=?", (username,)).fetchone()
+
+ if user is None:
+ return "Username or password incorrect", 403
+
+ if not check_password_hash(user["password"], password):
+ return "Username or password incorrect", 403
+
+ session.clear()
+ session["user_id"] = user["id"]
+ return 200
+
+
+@bp.route("/logout")
+def logout():
+ session.clear()
+ return 200
+
+
+def login_required(view):
+ @functools.wraps(view)
+ def wrapped_view(**kwargs):
+ if g.user is None:
+ return "Login required", 403
+
+ return view(**kwargs)
+
+ return wrapped_view
diff --git a/sw/db.py b/sw/db.py
new file mode 100644
index 0000000..372d7ae
--- /dev/null
+++ b/sw/db.py
@@ -0,0 +1,46 @@
+import sqlite3
+
+import click
+from flask import current_app, g
+from flask.cli import with_appcontext
+
+
+def get_db():
+ if "db" not in g:
+ g.db = sqlite3.connect(
+ current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES,
+ )
+
+ g.db.row_factory = sqlite3.Row
+
+ return g.db
+
+
+def get_db_cursor():
+ return get_db().cursor()
+
+
+def close_db(e=None):
+ db = g.pop("db", None)
+
+ if db is not None:
+ db.close()
+
+
+def init_db():
+ db = get_db()
+
+ with current_app.open_resource("schema.sql") as f:
+ db.executescript(f.read().decode("utf8"))
+
+
+@click.command("init-db")
+@with_appcontext
+def init_db_command():
+ init_db()
+ click.echo("Initialised the database.")
+
+
+def init_app(app):
+ app.teardown_appcontext(close_db)
+ app.cli.add_command(init_db_command)
diff --git a/sw/schema.sql b/sw/schema.sql
new file mode 100644
index 0000000..d6ee27a
--- /dev/null
+++ b/sw/schema.sql
@@ -0,0 +1,48 @@
+drop table if exists inbox;
+
+create table inbox (
+ recipient text,
+ received int,
+
+ ap_attachment text,
+ ap_attributedTo text,
+ ap_audience text,
+ ap_content text,
+ ap_context text,
+ ap_name text,
+ ap_endTime text,
+ ap_generator text,
+ ap_icon text,
+ ap_image text,
+ ap_inReplyTo text,
+ ap_location text,
+ ap_preview text,
+ ap_published text,
+ ap_replies text,
+ ap_startTime text,
+ ap_summary text,
+ ap_tag text,
+ ap_updated text,
+ ap_url text,
+ ap_to text,
+ ap_bto text,
+ ap_cc text,
+ ap_bcc text,
+ ap_mediaType text,
+ ap_duration text,
+
+ ap_actor text,
+ ap_object text,
+ ap_target text,
+ ap_result text,
+ ap_origin text,
+ ap_instrument text
+);
+
+drop table if exists user;
+
+create table user (
+ id integer primary key autoincrement,
+ username text unique not null,
+ password text not null
+);
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..fb8c751
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,53 @@
+import os
+import tempfile
+
+import pytest
+from sw import create_app
+from sw.db import get_db, init_db
+
+with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f:
+ _data_sql = f.read().decode("utf8")
+
+
+@pytest.fixture
+def app():
+ db_fd, db_path = tempfile.mkstemp()
+
+ app = create_app({"TESTING": True, "DATABASE": db_path,})
+
+ with app.app_context():
+ init_db()
+ get_db().executescript(_data_sql)
+
+ yield app
+
+ os.close(db_fd)
+ os.unlink(db_path)
+
+
+@pytest.fixture
+def client(app):
+ return app.test_client()
+
+
+@pytest.fixture
+def runner(app):
+ return app.test_cli_runner()
+
+
+class AuthActions(object):
+ def __init__(self, client):
+ self._client = client
+
+ def login(self, username="test", password="test"):
+ return self._client.post(
+ "/auth/login", data=jsonify({"username": username, "password": password,})
+ )
+
+ def logout(self):
+ return self._client.get("/auth/logout")
+
+
+@pytest.fixture
+def auth(client):
+ return AuthActions(client)
diff --git a/tests/data.sql b/tests/data.sql
new file mode 100644
index 0000000..4579284
--- /dev/null
+++ b/tests/data.sql
@@ -0,0 +1,4 @@
+insert into user (username, password)
+values
+ ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),
+ ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');
diff --git a/tests/test_auth.py b/tests/test_auth.py
new file mode 100644
index 0000000..3fb2493
--- /dev/null
+++ b/tests/test_auth.py
@@ -0,0 +1,40 @@
+import pytest
+
+from flask import g, session, json
+
+from sw.db import get_db
+
+
+def test_register(client, app):
+ response = client.post(
+ "/auth/register",
+ data=json.dumps({"username": "a", "password": "a",}),
+ content_type="application/json",
+ )
+
+ # TODO assert "/u/a" in response.headers["Location"]
+
+ with app.app_context():
+ db_result = (
+ get_db().execute("select * from user where username='a'",).fetchone()
+ )
+ assert db_result is not None
+
+
+@pytest.mark.parametrize(
+ ("username", "password", "message"),
+ (
+ (None, "", b"Username required"),
+ ("", "", b"Username must not be empty"),
+ ("a", None, b"Password required"),
+ ("a", "", b"Password must not be empty"),
+ ("test", "test", b"Username test is taken"),
+ ),
+)
+def test_register_validate_input(client, username, password, message):
+ response = client.post(
+ "/auth/register",
+ data=json.dumps({"username": username, "password": password,}),
+ content_type="application/json",
+ )
+ assert message in response.data
diff --git a/tests/test_db.py b/tests/test_db.py
new file mode 100644
index 0000000..7a35593
--- /dev/null
+++ b/tests/test_db.py
@@ -0,0 +1,30 @@
+import pytest
+
+import sqlite3
+
+from sw.db import get_db
+
+
+def test_get_close_db(app):
+ with app.app_context():
+ db = get_db()
+ assert db is get_db()
+
+ with pytest.raises(sqlite3.ProgrammingError) as e:
+ db.execute("select 1")
+
+ assert "closed" in str(e.value)
+
+
+def test_init_db_command(runner, monkeypatch):
+ class Recorder(object):
+ called = False
+
+ def fake_init_db():
+ Recorder.called = True
+
+ monkeypatch.setattr("sw.db.init_db", fake_init_db)
+ result = runner.invoke(args=["init-db"])
+
+ assert "Initialised" in result.output
+ assert Recorder.called
diff --git a/tests/test_factory.py b/tests/test_factory.py
new file mode 100644
index 0000000..bf2b321
--- /dev/null
+++ b/tests/test_factory.py
@@ -0,0 +1,11 @@
+from sw import create_app
+
+
+def test_config():
+ assert not create_app().testing
+ assert create_app({"TESTING": True}).testing
+
+
+def test_hello(client):
+ response = client.post("/auth/login")
+ assert response.status_code == 422