/
main.py
251 lines (227 loc) · 9.64 KB
/
main.py
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# -*- coding: utf-8 -*-
from datetime import datetime, timezone
from pathlib import Path
from typing import Union
import store
import werkzeug
from db import db
from encryption import EncryptionManager
from flask import (
Blueprint,
Markup,
abort,
current_app,
escape,
flash,
g,
redirect,
render_template,
request,
url_for,
)
from flask_babel import gettext
from journalist_app.forms import ReplyForm
from journalist_app.sessions import session
from journalist_app.utils import bulk_delete, download, get_source, validate_user
from models import Reply, SeenReply, Source, SourceStar, Submission
from sdconfig import SDConfig
from sqlalchemy.orm import joinedload
from sqlalchemy.sql import func
from store import Storage
def make_blueprint(config: SDConfig) -> Blueprint:
view = Blueprint("main", __name__)
@view.route("/login", methods=("GET", "POST"))
def login() -> Union[str, werkzeug.Response]:
if request.method == "POST":
user = validate_user(
request.form["username"],
request.form["password"],
request.form["token"],
)
if user:
current_app.logger.info(
"'{}' logged in with the two-factor code {}".format(
request.form["username"], request.form["token"]
)
)
# Update access metadata
user.last_access = datetime.now(timezone.utc)
db.session.add(user)
db.session.commit()
session["uid"] = user.id
session.regenerate()
return redirect(url_for("main.index"))
return render_template("login.html")
@view.route("/logout")
def logout() -> werkzeug.Response:
session.destroy()
return redirect(url_for("main.index"))
@view.route("/")
def index() -> str:
# Gather the count of unread submissions for each source
# ID. This query will be joined in the queries for starred and
# unstarred sources below, and the unread counts added to
# their result sets as an extra column.
unread_stmt = (
db.session.query(Submission.source_id, func.count("*").label("num_unread"))
.filter_by(seen_files=None, seen_messages=None)
.group_by(Submission.source_id)
.subquery()
)
# Query for starred sources, along with their unread
# submission counts.
starred = (
db.session.query(Source, unread_stmt.c.num_unread)
.filter_by(pending=False, deleted_at=None)
.filter(Source.last_updated.isnot(None))
.filter(SourceStar.starred.is_(True))
.outerjoin(SourceStar)
.options(joinedload(Source.submissions))
.options(joinedload(Source.star))
.outerjoin(unread_stmt, Source.id == unread_stmt.c.source_id)
.order_by(Source.last_updated.desc())
.all()
)
# Now, add "num_unread" attributes to the source entities.
for source, num_unread in starred:
source.num_unread = num_unread or 0
starred = [source for source, num_unread in starred]
# Query for sources without stars, along with their unread
# submission counts.
unstarred = (
db.session.query(Source, unread_stmt.c.num_unread)
.filter_by(pending=False, deleted_at=None)
.filter(Source.last_updated.isnot(None))
.filter(~Source.star.has(SourceStar.starred.is_(True)))
.options(joinedload(Source.submissions))
.options(joinedload(Source.star))
.outerjoin(unread_stmt, Source.id == unread_stmt.c.source_id)
.order_by(Source.last_updated.desc())
.all()
)
# Again, add "num_unread" attributes to the source entities.
for source, num_unread in unstarred:
source.num_unread = num_unread or 0
unstarred = [source for source, num_unread in unstarred]
response = render_template("index.html", unstarred=unstarred, starred=starred)
return response
@view.route("/reply", methods=("POST",))
def reply() -> werkzeug.Response:
"""Attempt to send a Reply from a Journalist to a Source. Empty
messages are rejected, and an informative error message is flashed
on the client. In the case of unexpected errors involving database
transactions (potentially caused by racing request threads that
modify the same the database object) logging is done in such a way
so as not to write potentially sensitive information to disk, and a
generic error message is flashed on the client.
Returns:
flask.Response: The user is redirected to the same Source
collection view, regardless if the Reply is created
successfully.
"""
form = ReplyForm()
if not form.validate_on_submit():
for error in form.message.errors:
flash(error, "error")
return redirect(url_for("col.col", filesystem_id=g.filesystem_id))
g.source.interaction_count += 1
filename = "{0}-{1}-reply.gpg".format(
g.source.interaction_count, g.source.journalist_filename
)
EncryptionManager.get_default().encrypt_journalist_reply(
for_source_with_filesystem_id=g.filesystem_id,
reply_in=form.message.data,
encrypted_reply_path_out=Path(Storage.get_default().path(g.filesystem_id, filename)),
)
try:
reply = Reply(session.get_user(), g.source, filename, Storage.get_default())
db.session.add(reply)
seen_reply = SeenReply(reply=reply, journalist=session.get_user())
db.session.add(seen_reply)
db.session.commit()
store.async_add_checksum_for_file(reply, Storage.get_default())
except Exception as exc:
flash(
gettext("An unexpected error occurred! Please " "inform your admin."),
"error",
)
# We take a cautious approach to logging here because we're dealing
# with responses to sources. It's possible the exception message
# could contain information we don't want to write to disk.
current_app.logger.error(
"Reply from '{}' (ID {}) failed: {}!".format(
session.get_user().username, session.get_uid(), exc.__class__
)
)
else:
flash(
Markup(
"<b>{}</b> {}".format(
# Translators: Precedes a message confirming the success of an operation.
escape(gettext("Success!")),
escape(
gettext("The source will receive your reply " "next time they log in.")
),
)
),
"success",
)
finally:
return redirect(url_for("col.col", filesystem_id=g.filesystem_id))
@view.route("/bulk", methods=("POST",))
def bulk() -> Union[str, werkzeug.Response]:
action = request.form["action"]
error_redirect = url_for("col.col", filesystem_id=g.filesystem_id)
doc_names_selected = request.form.getlist("doc_names_selected")
selected_docs = [doc for doc in g.source.collection if doc.filename in doc_names_selected]
if selected_docs == []:
if action == "download":
flash(
Markup(
"<b>{}</b> {}".format(
# Translators: Error shown when a user has not selected items to act on.
escape(gettext("Nothing Selected")),
escape(gettext("You must select one or more items for download")),
)
),
"error",
)
elif action == "delete":
flash(
Markup(
"<b>{}</b> {}".format(
# Translators: Error shown when a user has not selected items to act on.
escape(gettext("Nothing Selected")),
escape(gettext("You must select one or more items for deletion")),
)
),
"error",
)
else:
abort(400)
return redirect(error_redirect)
if action == "download":
source = get_source(g.filesystem_id)
return download(
source.journalist_filename,
selected_docs,
on_error_redirect=error_redirect,
)
elif action == "delete":
return bulk_delete(g.filesystem_id, selected_docs)
else:
abort(400)
@view.route("/download_unread/<filesystem_id>")
def download_unread_filesystem_id(filesystem_id: str) -> werkzeug.Response:
unseen_submissions = (
Submission.query.join(Source)
.filter(Source.deleted_at.is_(None), Source.filesystem_id == filesystem_id)
.filter(~Submission.seen_files.any(), ~Submission.seen_messages.any())
.all()
)
if len(unseen_submissions) == 0:
flash(gettext("No unread submissions for this source."), "error")
return redirect(url_for("col.col", filesystem_id=filesystem_id))
source = get_source(filesystem_id)
return download(source.journalist_filename, unseen_submissions)
return view