-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
108 lines (96 loc) · 2.83 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
import { app, errorHandler } from 'mu';
import {
getImpersonatedSession,
setImpersonatedSession,
deleteImpersonatedSession,
} from './lib/session';
import { getRole } from './lib/role';
app.get('/', function(_req, res) {
res.send({ message: '👋 Hi, this is the impersonation-service 🕵' });
});
app.get('/impersonations/current', async function(req, res) {
const muSessionId = req.get('mu-session-id');
const {
id: sessionId,
roleId,
} = await getImpersonatedSession(muSessionId);
const data = {
type: 'impersonations',
id: sessionId,
}
if (roleId) {
data.relationships ??= {};
data.relationships['impersonated-role'] = {
links: `/roles/${roleId}`,
data: { type: 'roles', id: roleId },
}
}
res.send({
links: {
self: '/impersonations/current',
},
data,
});
});
app.post('/impersonations', async function(req, res, next) {
let roleId;
try {
({
data: {
relationships: {
'impersonated-role': {
data: {
id: roleId
}
}
}
}
} = req.body);
if (!roleId) {
return next({ message: `You need to pass a role ID in the request body` });
}
} catch (e) {
return next({ message: `Failed to parse the request body` });
}
const muSessionId = req.get('mu-session-id');
try {
const { uri: role } = await getRole(roleId);
if (role) {
await setImpersonatedSession(muSessionId, role);
} else {
return next({ message: `Could not find a role with id ${roleId}`, status: 404 });
}
} catch (e) {
if (e.httpStatus === 403) {
console.warn(`Session <${muSessionId}> could not write data to impersonate role <${role}>`);
return next({ message: `You don't have the necessary rights to impersonate other roles`, status: 403 });
} else {
console.warn(`Something went wrong while session <${muSessionId}> tried to impersonate role <${role}>`);
console.error(e);
return next({ message: 'Something went wrong' });
}
}
res
.header('mu-auth-allowed-groups', 'CLEAR')
.status(204)
.send();
});
app.delete('/impersonations/current', async function(req, res) {
const muSessionId = req.get('mu-session-id');
try {
await deleteImpersonatedSession(muSessionId);
} catch (e) {
if (e.httpStatus === 403) {
console.warn(`Session <${muSessionId}> could not remove impersonation data`);
return next({ message: `You don't have the necessary rights to stop impersonating other accounts`, status: 403 });
} else {
console.warn(`Something went wrong while session <${muSessionId}> tried to stop impersonating another account`);
return next({ message: 'Something went wrong' });
}
}
res
.header('mu-auth-allowed-groups', 'CLEAR')
.status(204)
.send();
});
app.use(errorHandler);