-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
38 lines (34 loc) · 1.69 KB
/
index.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
const fetch = require('node-fetch');
const encode = require('./encode.js');
exports.formAuthorizationUri = async function (config) {
if (config.client.id === undefined || config.client.secret === undefined || config.uri.authorization === undefined || config.uri.redirect === undefined || config.scope === undefined) {
return 'Not enough information to form authorization URL';
} else {
if (config.responseType !== undefined) {
return `${config.uri.authorization}?client_id=${encodeURI(config.client.id)}&response_type=${encodeURI(config.responseType)}&scope=${encodeURI(config.scope)}&redirect_uri=${encodeURIComponent(config.uri.redirect)}`;
} else if (config.responseType === undefined) {
return `${config.uri.authorization}?client_id=${encodeURI(config.client.id)}&scope=${encodeURI(config.scope)}&redirect_uri=${encodeURIComponent(config.uri.redirect)}`;
}
}
}
exports.getAccessToken = async function (config) {
let accessToken;
try {
accessToken = await fetch(config.uri.token, {
method: 'POST',
headers: {
'Authorization': `Basic ${encodedClientCredentials}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `code=${encodeURI(config.code)}&grant_type=authorization_code&redirect_uri=${encodeURI(config.uri.redirect)}`
}).then((response) => {
return response.json().catch((parseError) => {
console.log(`Error parsing token response: ${parseError}`);
});
});
} catch (error) {
console.log(`Error fetching token: ${error}`);
return error;
}
return accessToken;
}