aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/views.py
blob: 5408fa48d3f455afe275a7743f9851ac8ced35e1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import uuid
from typing import cast
from urllib.parse import urlsplit

import sqlalchemy as sa
import sqlalchemy.exc as sa_exc
from flask import (
    Blueprint,
    Response,
    abort,
    flash,
    redirect,
    render_template,
    request,
    url_for,
)
from flask.typing import ResponseReturnValue
from flask_login import current_user, login_required, login_user, logout_user

from . import DATABASE as db
from . import forms
from .models import ReceivedWebmention, User
from .tasks.receiver import verify_webmention

root_page = Blueprint("root", __name__)


@root_page.route("/")
def index() -> ResponseReturnValue:
    return redirect(url_for("root.received"))


@root_page.route("/login", methods=["GET", "POST"])
def login() -> ResponseReturnValue:
    if current_user.is_authenticated:
        return redirect(url_for("root.index"))

    form = forms.LoginForm()

    if form.validate_on_submit():
        user = db.session.scalar(
            sa.select(User).where(User.username == form.username.data)
        )

        if user is None or not user.check_password(form.password.data):
            flash("Invalid username or password", "danger")
            return redirect(url_for("root.login"))

        login_user(user)

        next_page = request.args.get("next")
        if not next_page or urlsplit(next_page).netloc != "":
            next_page = url_for("root.index")
        return redirect(next_page)

    return render_template("login.html", form=form)


@root_page.route("/logout")
def logout() -> ResponseReturnValue:
    logout_user()
    return redirect(url_for("root.index"))


@root_page.route("/received")
@login_required
def received() -> ResponseReturnValue:
    webmentions = db.paginate(
        sa.select(ReceivedWebmention).order_by(ReceivedWebmention.uuid.desc()),
        per_page=25,
    )

    return render_template(
        "received.html",
        title="Received Webmentions",
        webmentions=webmentions,
    )


@root_page.route("/endpoint", methods=["POST"])
def endpoint() -> ResponseReturnValue:
    form = forms.EndpointForm(meta={"csrf": False})

    if not form.validate_on_submit():
        return form.errors, 400

    source = cast(str, form.source.data)
    target = cast(str, form.target.data)

    webmention = db.session.execute(
        sa.select(ReceivedWebmention).where(
            ReceivedWebmention.source == source,
            ReceivedWebmention.target == target,
        )
    ).scalar_one_or_none()

    if webmention is None:
        identifier = uuid.uuid7()

        webmention = ReceivedWebmention(
            uuid=identifier,
            source=source,
            target=target,
        )

        db.session.add(webmention)

        try:
            db.session.commit()
        except sa_exc.IntegrityError:
            db.session.rollback()

            # Another request may have inserted the same source/target pair
            # after our SELECT but before our COMMIT.
            webmention = db.session.execute(
                sa.select(ReceivedWebmention).where(
                    ReceivedWebmention.source == source,
                    ReceivedWebmention.target == target,
                )
            ).scalar_one()

            identifier = webmention.uuid
            webmention.status = "received"
            webmention.failure_reason = None

            db.session.commit()

    else:
        identifier = webmention.uuid

        # Re-sent webmention: re-verify the existing row.
        webmention.status = "received"
        webmention.failure_reason = None

        db.session.commit()

    verify_webmention(webmention.uuid)

    status_url = url_for(
        "root.status",
        identifier=str(identifier),
        _external=True,
    )

    return Response(
        status=201,
        headers={"Location": status_url},
    )


@root_page.route("/status/<uuid:identifier>")
def status(identifier: uuid.UUID) -> ResponseReturnValue:
    webmention = db.session.get(ReceivedWebmention, identifier)

    if webmention is None:
        return abort(404)

    return render_template(
        "status.html", title="Webmention status", webmention=webmention
    )