1 | 'use strict'
|
2 |
|
3 | const WebIdTlsCertificate = require('../models/webid-tls-certificate')
|
4 | const debug = require('./../debug').accounts
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | class AddCertificateRequest {
|
14 | |
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | constructor (options) {
|
22 | this.accountManager = options.accountManager
|
23 | this.userAccount = options.userAccount
|
24 | this.certificate = options.certificate
|
25 | this.response = options.response
|
26 | }
|
27 |
|
28 | |
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | static handle (req, res, accountManager) {
|
42 | let request
|
43 | try {
|
44 | request = AddCertificateRequest.fromParams(req, res, accountManager)
|
45 | } catch (error) {
|
46 | return Promise.reject(error)
|
47 | }
|
48 |
|
49 | return AddCertificateRequest.addCertificate(request)
|
50 | }
|
51 |
|
52 | |
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | static fromParams (req, res, accountManager) {
|
66 | let userAccount = accountManager.userAccountFrom(req.body)
|
67 | let certificate = WebIdTlsCertificate.fromSpkacPost(
|
68 | req.body.spkac,
|
69 | userAccount,
|
70 | accountManager.host)
|
71 |
|
72 | debug(`Adding a new certificate for ${userAccount.webId}`)
|
73 |
|
74 | if (req.session.userId !== userAccount.webId) {
|
75 | debug(`Cannot add new certificate: signed in user is "${req.session.userId}"`)
|
76 | let error = new Error("You are not logged in, so you can't create a certificate")
|
77 | error.status = 401
|
78 | throw error
|
79 | }
|
80 |
|
81 | let options = {
|
82 | accountManager,
|
83 | userAccount,
|
84 | certificate,
|
85 | response: res
|
86 | }
|
87 |
|
88 | return new AddCertificateRequest(options)
|
89 | }
|
90 |
|
91 | |
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 | static addCertificate (request) {
|
102 | let { certificate, userAccount, accountManager } = request
|
103 |
|
104 | return certificate.generateCertificate()
|
105 | .catch(err => {
|
106 | err.status = 400
|
107 | err.message = 'Error generating a certificate: ' + err.message
|
108 | throw err
|
109 | })
|
110 | .then(() => {
|
111 | return accountManager.addCertKeyToProfile(certificate, userAccount)
|
112 | })
|
113 | .catch(err => {
|
114 | err.status = 400
|
115 | err.message = 'Error adding certificate to profile: ' + err.message
|
116 | throw err
|
117 | })
|
118 | .then(() => {
|
119 | request.sendResponse(certificate)
|
120 | })
|
121 | }
|
122 |
|
123 | |
124 |
|
125 |
|
126 |
|
127 |
|
128 | sendResponse (certificate) {
|
129 | let { response, userAccount } = this
|
130 | response.set('User', userAccount.webId)
|
131 | response.status(200)
|
132 |
|
133 | response.set('Content-Type', 'application/x-x509-user-cert')
|
134 | response.send(certificate.toDER())
|
135 | }
|
136 | }
|
137 |
|
138 | module.exports = AddCertificateRequest
|