-
Notifications
You must be signed in to change notification settings - Fork 0
/
clever.js
98 lines (77 loc) · 2.46 KB
/
clever.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
const req = require('request-promise');
const async = require('async');
CLIENT_ID = 'f72cdb5b20623d71325a';
CLIENT_SECRET = '34fe3bf977c4dcd9fc2f05941d260fbb0d9db1fd';
REDIRECT_URL = 'https://testing-clever.herokuapp.com/oauth';
async function runOAuthFlow(code) {
console.log("getting token");
const token = await getToken(code);
console.log("getting me");
const response = await request('/me', token);
const data = response["data"];
console.log("me data", data);
console.log("user data", data);
return {
id: data.id,
type: data.type,
token: token
};
}
async function getToken(code) {
var auth = new Buffer(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');
var token_options = {
url: 'https://clever.com/oauth/tokens',
headers: { 'Authorization': 'Basic ' + auth },
form: {
'code': code,
'grant_type': 'authorization_code',
'redirect_uri': REDIRECT_URL
},
method: 'POST',
json: true,
};
data = await req(token_options);
return data["access_token"];
}
async function request(route, token) {
var url = `https://api.clever.com/v2.0${route}`;
const data = req({
url: url,
headers: { 'Authorization': `Bearer ${token}` },
json: true,
});
return data;
}
async function getMyInfo(user_id, user_type, token) {
var route = `/${user_type}s/${user_id}`;
const response = await request(route, token);
return response["data"];
}
async function getMySections(user_id, user_type, token) {
var route = `/${user_type}s/${user_id}/sections`;
const response = await request(route, token);
return response["data"];
}
async function getMySectionsWithStudents(user_id, user_type, token) {
var route = `/${user_type}s/${user_id}/sections`;
const response = await request(route, token);
const sections = response["data"];
// for every section, go fetch the data for each of its students
await Promise.all(sections.map(async (section) => {
section.data.students = await getStudentsForSection(section.data.id, token);
}));
return sections;
}
async function getStudentsForSection(section_id, token) {
var route = `/sections/${section_id}/students`;
const response = await request(route, token);
return response["data"];
}
module.exports = {
request: request,
runOAuthFlow: runOAuthFlow,
getMyInfo: getMyInfo,
getMySections: getMySections,
getMySectionsWithStudents: getMySectionsWithStudents,
getStudentsForSection: getStudentsForSection,
};