]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/activitypub.ts
Send server announce when users upload a video
[github/Chocobozzz/PeerTube.git] / server / middlewares / activitypub.ts
1 import { NextFunction, Request, Response, RequestHandler } from 'express'
2 import { ActivityPubSignature } from '../../shared'
3 import { isSignatureVerified, logger } from '../helpers'
4 import { fetchRemoteAccountAndCreateServer } from '../helpers/activitypub'
5 import { database as db, ACTIVITY_PUB_ACCEPT_HEADER } from '../initializers'
6 import { each, eachSeries, waterfall } from 'async'
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) {
17 const accountResult = await fetchRemoteAccountAndCreateServer(signatureObject.creator)
18
19 if (!accountResult) {
20 return res.sendStatus(403)
21 }
22
23 // Save our new account in database
24 account = accountResult.account
25 await account.save()
26 }
27
28 const verified = await isSignatureVerified(account, req.body)
29 if (verified === false) return res.sendStatus(403)
30
31 res.locals.signature = {
32 account
33 }
34
35 return next()
36 }
37
38 function executeIfActivityPub (fun: RequestHandler | RequestHandler[]) {
39 return (req: Request, res: Response, next: NextFunction) => {
40 if (req.header('Accept') !== ACTIVITY_PUB_ACCEPT_HEADER) {
41 return next()
42 }
43
44 if (Array.isArray(fun) === true) {
45 return eachSeries(fun as RequestHandler[], (f, cb) => {
46 f(req, res, cb)
47 }, next)
48 }
49
50 return (fun as RequestHandler)(req, res, next)
51 }
52 }
53
54 // ---------------------------------------------------------------------------
55
56 export {
57 checkSignature,
58 executeIfActivityPub
59 }