forked from VirgilSecurity/ionic-demo-healthcare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
180 lines (157 loc) · 5.4 KB
/
server.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
const path = require('path');
const dotenv = require('dotenv');
const express = require('express');
const morgan = require('morgan');
const { readFileSync } = require('fs');
const { body: checkBody, validationResult, oneOf } = require('express-validator/check');
const { buildSamlResponse, IonicApiClient } = require('ionic-admin-sdk');
const debug = require('./server/debug');
const UserService = require('./server/ionic/user-service');
const PREDEFINED_GROUPS = require('./server/data/groups.json');
const StateStorage = require('./server/db/state-storage');
dotenv.config();
// check required environment variables
function validateConfig() {
const requiredVars = [
'IONIC_IDP_ENTITY_ID',
'IONIC_ASSERTION_CONSUMER_SERVICE',
'IONIC_ENROLLMENT_ENDPOINT',
'IONIC_IDP_PRIVATE_KEY_PATH',
'IONIC_API_BASE_URL',
'IONIC_TENANT_ID',
'IONIC_API_AUTH_TOKEN',
// 'AWS_ACCESS_KEY_ID', // required only when using DynamoDB hosted in AWS
// 'AWS_SECRET_ACCESS_KEY', // required only when using DynamoDB hosted in AWS
'AWS_DYNAMODB_ENDPOINT',
'AWS_DYNAMODB_TABLE_NAME'
];
const missingVars = requiredVars.filter(name => !(name in process.env));
if (missingVars.length > 0) {
console.error(`The following environment variables must be set to run the server: ${missingVars.join(', ')}`);
process.exit(1);
}
}
validateConfig();
const app = express();
app.disable('x-powered-by');
app.use(morgan('dev'));
app.use(express.json());
const storage = new StateStorage();
app.post(
'/register',
[
checkBody('email').isEmail(),
checkBody('groupName').isIn(Object.keys(PREDEFINED_GROUPS)),
checkBody('firstName').isAlpha().isLength({ max: 256 }),
checkBody('lastName').isAlpha().isLength({ max: 256 })
],
async (req, res) => {
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.status(400).json({
error: 'Invalid request body',
errors: validationErrors.array().map(({ msg: message, param }) => ({ param, message }))
});
}
const { firstName, lastName, email, groupName } = req.body;
const userService = new UserService(
new IonicApiClient({
baseUrl: process.env.IONIC_API_BASE_URL,
tenantId: process.env.IONIC_TENANT_ID,
auth: {
type: 'bearer',
secretToken: process.env.IONIC_API_AUTH_TOKEN
}
})
);
debug('fetching user');
let user;
try {
user = await userService.getOrCreateUser({ email, groupName, firstName, lastName });
debug('user fetched');
} catch (err) {
debug('error fetching user %o', err);
const message = typeof err.body === 'object' && 'message' in err.body ? err.body.message : err.message;
res.status(500).json({ error: message });
return;
}
debug('generating SAML assertion');
let samlResponse;
try {
samlResponse = buildSamlResponse({
privateKey: readFileSync(process.env.IONIC_IDP_PRIVATE_KEY_PATH, 'utf8'),
userEmail: email,
recipientUrl: process.env.IONIC_ENROLLMENT_ENDPOINT,
recipientName: process.env.IONIC_ASSERTION_CONSUMER_SERVICE,
issuer: process.env.IONIC_IDP_ENTITY_ID
});
debug('assertion generated');
} catch (err) {
debug('error sending SAML assertion: %o', err);
res.status(500).json({ error: err.message });
return;
}
res.status(200).json({ assertion: samlResponse, user });
}
);
app.get('/state', async (req, res) => {
let state;
try {
state = await storage.getState();
} catch (err) {
debug('error getting state: %o');
res.status(500).json({ error: 'Internal server error '});
return;
}
res.json(state);
});
app.put(
'/state',
[
oneOf([
checkBody('medical_history').not().isEmpty(),
checkBody('office_visit_notes').not().isEmpty(),
checkBody('prescription').not().isEmpty(),
checkBody('insurer_reply').not().isEmpty(),
], 'At least one property to update must be specified')
],
async (req, res) => {
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.status(400).json({
error: 'Invalid request body',
errors: validationErrors.array().map(({ msg: message, param }) => ({ param, message }))
});
}
const { medical_history, office_visit_notes, prescription, insurer_reply } = req.body;
let updatedState;
try {
updatedState = await storage.updateState({ medical_history, office_visit_notes, prescription, insurer_reply });
} catch (err) {
debug('error updating state: %o', err);
res.status(500).json({ error: 'Internal server error' });
return;
}
res.json(updatedState);
}
);
app.delete('/state', async (req, res) => {
let updatedState;
try {
updatedState = await storage.resetState();
} catch (err) {
debug('error reseting state: %o', err);
res.status(500).json({ error: 'Internal server error' });
return;
}
res.json(updatedState);
});
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.listen(8080, () => {
console.log(`The server is listening on port 8080`);
});