aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/remote/pods.ts
blob: 326eb61ac183c712176c0517bc28c178e9973a50 (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
import * as express from 'express'

import { database as db } from '../../../initializers/database'
import {
  checkSignature,
  signatureValidator,
  setBodyHostPort,
  remotePodsAddValidator,
  asyncMiddleware
} from '../../../middlewares'
import { sendOwnedDataToPod } from '../../../lib'
import { getMyPublicCert, getFormattedObjects } from '../../../helpers'
import { CONFIG } from '../../../initializers'
import { PodInstance } from '../../../models'
import { PodSignature, Pod as FormattedPod } from '../../../../shared'

const remotePodsRouter = express.Router()

remotePodsRouter.post('/remove',
  signatureValidator,
  checkSignature,
  asyncMiddleware(removePods)
)

remotePodsRouter.post('/list',
  asyncMiddleware(remotePodsList)
)

remotePodsRouter.post('/add',
  setBodyHostPort, // We need to modify the host before running the validator!
  remotePodsAddValidator,
  asyncMiddleware(addPods)
)

// ---------------------------------------------------------------------------

export {
  remotePodsRouter
}

// ---------------------------------------------------------------------------

async function addPods (req: express.Request, res: express.Response, next: express.NextFunction) {
  const information = req.body

  const pod = db.Pod.build(information)
  const podCreated = await pod.save()

  await sendOwnedDataToPod(podCreated.id)

  const cert = await getMyPublicCert()
  return res.json({ cert, email: CONFIG.ADMIN.EMAIL })
}

async function remotePodsList (req: express.Request, res: express.Response, next: express.NextFunction) {
  const pods = await db.Pod.list()

  return res.json(getFormattedObjects<FormattedPod, PodInstance>(pods, pods.length))
}

async function removePods (req: express.Request, res: express.Response, next: express.NextFunction) {
  const signature: PodSignature = req.body.signature
  const host = signature.host

  const pod = await db.Pod.loadByHost(host)
  await pod.destroy()

  return res.type('json').status(204).end()
}