-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
198 lines (173 loc) · 6.18 KB
/
app.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import { app } from 'mu';
import { getSessionIdHeader, error } from './utils';
import { saveLog } from './logs';
import { getAccessToken } from './lib/openid';
import { roleClaim, groupIdClaim, removeOldSessions, removeCurrentSession,
ensureUserAndAccount, insertNewSessionForAccount,
selectAccountBySession, selectCurrentSession,
selectBestuurseenheidByNumber } from './lib/session';
import request from 'request';
const logsGraph = process.env.LOGS_GRAPH || 'http://mu.semte.ch/graphs/public';
/**
* Configuration validation on startup
*/
const requiredEnvironmentVariables = [
'MU_APPLICATION_AUTH_DISCOVERY_URL',
'MU_APPLICATION_AUTH_CLIENT_ID',
'MU_APPLICATION_AUTH_REDIRECT_URI'
];
requiredEnvironmentVariables.forEach(key => {
if (!process.env[key]) {
console.log(`Environment variable ${key} must be configured`);
process.exit(1);
}
});
/**
* Log the user in by creating a new session, i.e. attaching the user's account to a session.
*
* Before creating a new session, the given authorization code gets exchanged for an access token
* with an OpenID Provider (ACM/IDM) using the configured discovery URL. The returned JWT access token
* is decoded to retrieve information to attach to the user, account and the session.
* If the OpenID Provider returns a valid access token, a new user and account are created if they
* don't exist yet and a the account is attached to the session.
*
* Body: { authorizationCode: "secret" }
*
* @return [201] On successful login containing the newly created session
* @return [400] If the session header or authorization code is missing
* @return [401] On login failure (unable to retrieve a valid access token)
* @return [403] If no bestuurseenheid can be linked to the session
*/
app.post('/sessions', async function(req, res, next) {
const sessionUri = getSessionIdHeader(req);
if (!sessionUri)
return error(res, 'Session header is missing');
const authorizationCode = req.body['authorizationCode'];
if (!authorizationCode)
return error(res, 'Authorization code is missing');
try {
let tokenSet;
try {
tokenSet = await getAccessToken(authorizationCode);
} catch(e) {
console.log(`Failed to retrieve access token for authorization code: ${e.message || e}`);
return res.status(401).end();
}
await removeOldSessions(sessionUri);
const claims = tokenSet.claims();
if (process.env['DEBUG_LOG_TOKENSETS']) {
console.log(`Received tokenSet ${JSON.stringify(tokenSet)} including claims ${JSON.stringify(claims)}`);
}
if (process.env['LOG_SINK_URL'])
request.post({ url: process.env['LOG_SINK_URL'], body: tokenSet, json: true });
const { groupUri, groupId } = await selectBestuurseenheidByNumber(claims);
if (!groupUri || !groupId) {
console.log(`User is not allowed to login. No bestuurseenheid found for roles ${JSON.stringify(claims[roleClaim])}`);
saveLog(
logsGraph,
`http://data.lblod.info/class-names/no-bestuurseenheid-for-role`,
`User is not allowed to login. No bestuurseenheid found for roles ${JSON.stringify(claims[roleClaim])}`,
sessionUri,
claims[groupIdClaim]);
return res.header('mu-auth-allowed-groups', 'CLEAR').status(403).end();
}
const { accountUri, accountId } = await ensureUserAndAccount(claims, groupId);
const roles = (claims[roleClaim] || []).map(r => r.split(':')[0]);
const { sessionId } = await insertNewSessionForAccount(accountUri, sessionUri, groupUri, roles);
return res.header('mu-auth-allowed-groups', 'CLEAR').status(201).send({
links: {
self: '/sessions/current'
},
data: {
type: 'sessions',
id: sessionId,
attributes: {
roles: roles
}
},
relationships: {
account: {
links: { related: `/accounts/${accountId}` },
data: { type: 'accounts', id: accountId }
},
group: {
links: { related: `/bestuurseenheden/${groupId}` },
data: { type: 'bestuurseenheden', id: groupId }
}
}
});
} catch(e) {
return next(new Error(e.message));
}
});
/**
* Log out from the current session, i.e. detaching the session from the user's account.
*
* @return [204] On successful logout
* @return [400] If the session header is missing or invalid
*/
app.delete('/sessions/current', async function(req, res, next) {
const sessionUri = getSessionIdHeader(req);
if (!sessionUri)
return error(res, 'Session header is missing');
try {
const { accountUri } = await selectAccountBySession(sessionUri);
if (!accountUri)
return error(res, 'Invalid session');
await removeCurrentSession(sessionUri);
return res.header('mu-auth-allowed-groups', 'CLEAR').status(204).end();
} catch(e) {
return next(new Error(e.message));
}
});
/**
* Get the current session
*
* @return [200] The current session
* @return [400] If the session header is missing or invalid
*/
app.get('/sessions/current', async function(req, res, next) {
const sessionUri = getSessionIdHeader(req);
if (!sessionUri)
return next(new Error('Session header is missing'));
try {
const { accountUri, accountId } = await selectAccountBySession(sessionUri);
if (!accountUri)
return error(res, 'Invalid session');
const { sessionId, groupId, roles } = await selectCurrentSession(accountUri);
return res.status(200).send({
links: {
self: '/sessions/current'
},
data: {
type: 'sessions',
id: sessionId,
attributes: {
roles: roles
}
},
relationships: {
account: {
links: { related: `/accounts/${accountId}` },
data: { type: 'accounts', id: accountId }
},
group: {
links: { related: `/bestuurseenheden/${groupId}` },
data: { type: 'bestuurseenheden', id: groupId }
}
}
});
} catch(e) {
return next(new Error(e.message));
}
});
/**
* Error handler translating thrown Errors to 500 HTTP responses
*/
app.use(function(err, req, res, next) {
console.log(`Error: ${err.message}`);
res.status(500);
res.json({
errors: [ {title: err.message} ]
});
});