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

import { database as db } from '../../../initializers/database'
import {
  checkSignature,
  signatureValidator,
  setBodyHostPort,
  remotePodsAddValidator
} 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,
  removePods
)

remotePodsRouter.post('/list', remotePodsList)

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

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

export {
  remotePodsRouter
}

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

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

  const pod = db.Pod.build(information)
  pod.save()
     .then(podCreated => {
       return sendOwnedDataToPod(podCreated.id)
     })
     .then(() => {
       return getMyPublicCert()
     })
     .then(cert => {
       return res.json({ cert: cert, email: CONFIG.ADMIN.EMAIL })
     })
     .catch(err => next(err))
}

function remotePodsList (req: express.Request, res: express.Response, next: express.NextFunction) {
  db.Pod.list()
    .then(podsList => res.json(getFormattedObjects<FormattedPod, PodInstance>(podsList, podsList.length)))
    .catch(err => next(err))
}

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

  db.Pod.loadByHost(host)
    .then(pod => pod.destroy())
    .then(() => res.type('json').status(204).end())
    .catch(err => next(err))
}