]>
Commit | Line | Data |
---|---|---|
350e31d6 | 1 | import { NextFunction, Request, Response, RequestHandler } from 'express' |
e4f97bab | 2 | import { ActivityPubSignature } from '../../shared' |
350e31d6 | 3 | import { isSignatureVerified, logger } from '../helpers' |
60862425 | 4 | import { fetchRemoteAccountAndCreateServer } from '../helpers/activitypub' |
350e31d6 C |
5 | import { database as db, ACTIVITY_PUB_ACCEPT_HEADER } from '../initializers' |
6 | import { each, eachSeries, waterfall } from 'async' | |
e4f97bab C |
7 | |
8 | async function checkSignature (req: Request, res: Response, next: NextFunction) { | |
9 | const signatureObject: ActivityPubSignature = req.body.signature | |
10 | ||
11 | logger.debug('Checking signature of account %s...', signatureObject.creator) | |
12 | ||
13 | let account = await db.Account.loadByUrl(signatureObject.creator) | |
14 | ||
15 | // We don't have this account in our database, fetch it on remote | |
16 | if (!account) { | |
60862425 | 17 | const accountResult = await fetchRemoteAccountAndCreateServer(signatureObject.creator) |
e4f97bab | 18 | |
350e31d6 | 19 | if (!accountResult) { |
e4f97bab C |
20 | return res.sendStatus(403) |
21 | } | |
22 | ||
23 | // Save our new account in database | |
350e31d6 | 24 | account = accountResult.account |
e4f97bab C |
25 | await account.save() |
26 | } | |
27 | ||
28 | const verified = await isSignatureVerified(account, req.body) | |
29 | if (verified === false) return res.sendStatus(403) | |
30 | ||
350e31d6 C |
31 | res.locals.signature = { |
32 | account | |
33 | } | |
e4f97bab C |
34 | |
35 | return next() | |
36 | } | |
37 | ||
350e31d6 | 38 | function executeIfActivityPub (fun: RequestHandler | RequestHandler[]) { |
e4f97bab | 39 | return (req: Request, res: Response, next: NextFunction) => { |
350e31d6 | 40 | if (req.header('Accept') !== ACTIVITY_PUB_ACCEPT_HEADER) { |
e4f97bab C |
41 | return next() |
42 | } | |
43 | ||
44 | if (Array.isArray(fun) === true) { | |
350e31d6 C |
45 | return eachSeries(fun as RequestHandler[], (f, cb) => { |
46 | f(req, res, cb) | |
47 | }, next) | |
e4f97bab C |
48 | } |
49 | ||
350e31d6 | 50 | return (fun as RequestHandler)(req, res, next) |
e4f97bab C |
51 | } |
52 | } | |
53 | ||
54 | // --------------------------------------------------------------------------- | |
55 | ||
56 | export { | |
57 | checkSignature, | |
58 | executeIfActivityPub | |
59 | } |