-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
handles.ts
334 lines (277 loc) · 9.55 KB
/
handles.ts
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2023 the .NET Foundation
// A "handle" is a public-facing account such as `@jwst`. We distinguish between
// handles and Keycloak user accounts since we expect that handles will
// regularly be administered by multiple users.
//
// See `SCHEMA.md` for more information about the schema used here.
import { Response } from "express";
import { Request as JwtRequest } from "express-jwt";
import { isLeft } from "fp-ts/lib/Either.js";
import * as t from "io-ts";
import { PathReporter } from "io-ts/lib/PathReporter.js";
import { UpdateFilter } from "mongodb";
import { State } from "./globals.js";
import { sceneToJson } from "./scenes.js";
export interface MongoHandle {
handle: string;
display_name: string;
creation_date: Date;
owner_accounts: string[];
}
function isOwner(req: JwtRequest, handle: MongoHandle): boolean {
return req.auth && req.auth.sub && handle.owner_accounts.includes(req.auth.sub) || false;
}
export type HandleCapability =
"addImages" |
"addScenes" |
"editImages" |
"editScenes" |
"editSettings" |
"viewDashboard"
;
export function isAllowed(req: JwtRequest, handle: MongoHandle, _cap: HandleCapability): boolean {
// One day we might have finer-grained permissions, but not yet.
return isOwner(req, handle);
}
export function initializeHandleEndpoints(state: State) {
// GET /handle/:handle - Get general information about a handle
state.app.get("/handle/:handle", async (req: JwtRequest, res: Response) => {
try {
const result = await state.handles.findOne({ "handle": req.params.handle });
if (result === null) {
res.statusCode = 404;
res.json({ error: true, message: "Not found" });
return;
}
res.json({
error: false,
handle: result.handle,
display_name: result.display_name,
});
} catch (err) {
console.error(`${req.method} ${req.path} exception:`, err);
res.statusCode = 500;
res.json({ error: true, message: `error serving ${req.method} ${req.path}` });
}
});
// GET /handle/:handle/timeline?page=$int - get scenes for a handle's timeline
//
// This gives the scenes published by a handle in reverse chronological order.
const page_size = 8;
state.app.get(
"/handle/:handle/timeline",
async (req: JwtRequest, res: Response) => {
try {
// Handle parameters
var page_num = 0;
try {
const qpage = parseInt(req.query.page as string, 10);
if (qpage >= 0) {
page_num = qpage;
}
} catch {
res.statusCode = 400;
res.json({ error: true, message: `invalid page number` });
}
const handle = await state.handles.findOne({ "handle": req.params.handle });
if (handle === null) {
res.statusCode = 404;
res.json({ error: true, message: "Not found" });
return;
}
// Now, the actual query
const docs = await state.scenes
.find({
"handle_id": { "$eq": handle._id },
published: true,
})
.sort({ creation_date: -1 }) // todo: publish date
.skip(page_num * page_size)
.limit(page_size)
.toArray();
const scenes = [];
for (var doc of docs) {
scenes.push(await sceneToJson(doc, state, req.session));
}
res.json({
error: false,
results: scenes,
});
} catch (err) {
console.error(`${req.method} ${req.path} exception:`, err);
res.statusCode = 500;
res.json({ error: true, message: `error serving ${req.method} ${req.path}` });
}
}
);
// GET /handle/:handle/permissions - get information about the logged-in user's
// permissions with regards to this handle.
//
// This API is only informative -- of course, direct API calls are the final
// arbiters of what is and isn't allowed. But the frontend can use this
// information to decide what UI elements to expose to a user.
state.app.get(
"/handle/:handle/permissions",
async (req: JwtRequest, res: Response) => {
try {
const handle = await state.handles.findOne({ "handle": req.params.handle });
if (handle === null) {
res.statusCode = 404;
res.json({ error: true, message: "Not found" });
return;
}
const output = {
error: false,
handle: handle.handle,
view_dashboard: isAllowed(req, handle, "viewDashboard"),
};
res.json(output);
} catch (err) {
console.error(`${req.method} ${req.path} exception:`, err);
res.statusCode = 500;
res.json({ error: true, message: `error serving ${req.method} ${req.path}` });
}
}
);
// GET /handle/:handle/stats - get some statistics about this handle
//
// This information is only accessible to dashboard-capable users.
state.app.get(
"/handle/:handle/stats",
async (req: JwtRequest, res: Response) => {
try {
// Validate input(s)
const handle = await state.handles.findOne({ "handle": req.params.handle });
if (handle === null) {
res.statusCode = 404;
res.json({ error: true, message: "Not found" });
return;
}
// Check authorization
if (!isAllowed(req, handle, "viewDashboard")) {
res.statusCode = 403;
res.json({ error: true, message: "Forbidden" });
return;
}
// OK, actually do it
const imageStats = (await state.images.aggregate([
{
"$match": { handle_id: handle._id },
},
{
"$group": {
"_id": null,
"count": { "$sum": 1 }, // Azure Cosmos doesn't support $count
}
},
]).next()) || {
count: 0,
};
const sceneStats = (await state.scenes.aggregate([
{
"$match": { handle_id: handle._id },
},
{
"$group": {
"_id": null,
"count": { "$sum": 1 }, // Azure Cosmos doesn't support $count
"impressions": { "$sum": "$impressions" },
"likes": { "$sum": "$likes" },
"clicks": { "$sum": "$clicks" },
"shares": { "$sum": "$shares" },
}
},
]).next()) || {
count: 0,
impressions: 0,
likes: 0,
clicks: 0,
shares: 0,
};
// Construct the output
const output = {
error: false,
handle: handle.handle,
images: {
count: imageStats.count,
},
scenes: {
count: sceneStats.count,
impressions: sceneStats.impressions,
likes: sceneStats.likes,
clicks: sceneStats.clicks,
shares: sceneStats.shares,
},
};
res.json(output);
} catch (err) {
console.error(`${req.method} ${req.path} exception:`, err);
res.statusCode = 500;
res.json({ error: true, message: `error serving ${req.method} ${req.path}` });
}
}
);
// PATCH /handle/:handle - update various handle properties
const HandlePatch = t.partial({
display_name: t.string,
});
type HandlePatchT = t.TypeOf<typeof HandlePatch>;
state.app.patch(
"/handle/:handle",
async (req: JwtRequest, res: Response) => {
try {
// Validate inputs
const handle = await state.handles.findOne({ "handle": req.params.handle });
if (handle === null) {
res.statusCode = 404;
res.json({ error: true, message: "Not found" });
return;
}
const maybe = HandlePatch.decode(req.body);
if (isLeft(maybe)) {
res.statusCode = 400;
res.json({ error: true, message: `Submission did not match schema: ${PathReporter.report(maybe).join("\n")}` });
return;
}
const input: HandlePatchT = maybe.right;
// For this operation, we might require different permissions depending
// on what changes are exactly being requested. Note that patch
// operations should either fully succeed or fully fail -- no partial
// applications.
let allowed = true;
// For convenience, this value should be pre-filled with whatever
// operations we might use below. We have to hack around the typing
// below, though, because TypeScript takes some elements here to be
// read-only.
let operation: UpdateFilter<MongoHandle> = { "$set": {} };
if (input.display_name) {
allowed = allowed && isAllowed(req, handle, "editSettings");
// Validate this particular input. (TODO: I think io-ts could do this?)
if (input.display_name.length > 64) {
res.statusCode = 400;
res.json({ error: true, message: "Invalid input display_name: too long" });
return;
}
(operation as any)["$set"]["display_name"] = input.display_name;
}
// How did we do?
if (!allowed) {
res.statusCode = 403;
res.json({ error: true, message: "Forbidden" });
return;
}
await state.handles.findOneAndUpdate(
{ "handle": req.params.handle },
operation
);
res.json({
error: false,
});
} catch (err) {
console.error(`${req.method} ${req.path} exception:`, err);
res.statusCode = 500;
res.json({ error: true, message: `error serving ${req.method} ${req.path}` });
}
}
);
}