-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathicann_server.js
103 lines (87 loc) · 2.33 KB
/
icann_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
Icann = {};
Icann.retrieveCredential = (credentialToken, credentialSecret) =>
OAuth.retrieveCredential(credentialToken, credentialSecret);
OAuth.registerService('icann', 2, null, query => {
const config = Icann.getConfiguration({ tenantId: query.tenantId });
const { access_token: accessToken, id_token: idToken } = query;
const userInfo = handleUserInfo(idToken, accessToken, config);
const userInfoAccessToken = userDataFromToken(accessToken);
console.log(`user info from icann`, userInfo);
const {
sub: id,
email,
given_name: firstName,
family_name: lastName,
name,
} = userInfo;
const {
given_name: firstNameAccessToken,
family_name: lastNameAccessToken,
} = userInfoAccessToken;
const emailsFormatted = email ? [email] : [];
const _names = {
firstName: firstNameAccessToken || firstName || name,
lastName: lastNameAccessToken || lastName,
};
const serviceData = {
..._names,
id,
email,
accessToken,
};
const options = {
profile: { ..._names },
tenantId: query.tenantId,
email: email,
emails: emailsFormatted,
};
return {
serviceName: 'icann',
serviceData,
options,
};
});
const handleUserInfo = (idToken, accessToken, { userInfoUrl }) => {
if (!userInfoUrl) {
if (!idToken) {
throw new Error(`Authorization failed. Token ID not present.`);
}
return userDataFromToken(idToken);
}
if (!userInfoUrl) {
throw new Error(`Authorization failed. User Info URL not present.`);
}
try {
const { data } = HTTP.get(userInfoUrl, {
headers: {
Authorization: 'Bearer ' + accessToken,
},
});
return data;
} catch (error) {
console.error(`[icann-server] Error to retrieve user info`, {
error,
userInfoUrl,
});
throw Object.assign(
new Error(`Authorization failed. Failed to fetch user data.`),
{ response: error.response }
)
}
};
const userDataFromToken = idToken => {
if (idToken) {
try {
const tokenParts = idToken.split('.');
return JSON.parse(
new Buffer.from(tokenParts[1], 'base64').toString()
);
} catch (error) {
console.error(`[icann-server] Error to retrieve user info`, {
error,
idToken,
});
throw new Error(`Authorization failed. Failed to parse user data.`);
}
}
};