This repository has been archived by the owner on Nov 13, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathopenbadger.js
489 lines (403 loc) · 12 KB
/
openbadger.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
const Api = require('./api');
const errors = require('./lib/errors');
const logger = require('./logger');
const _ = require('underscore');
const jwt = require('jwt-simple');
const async = require('async');
const s3 = require('./s3');
const iremix = require('./iremix');
const ENDPOINT = process.env['CSOL_OPENBADGER_URL'];
const JWT_SECRET = process.env['CSOL_OPENBADGER_SECRET'];
const TOKEN_LIFETIME = process.env['CSOL_OPENBADGER_TOKEN_LIFETIME'] || 10000;
if (!ENDPOINT)
throw new Error('Must specify CSOL_OPENBADGER_URL in the environment');
if (!JWT_SECRET)
throw new Error('Must specify CSOL_OPENBADGER_SECRET in the environment');
function normalizeBadge (badge, id) {
if (badge.shortname)
badge.id = badge.shortname;
if (!id)
id = badge.shortname;
if (!badge.id)
badge.id = id;
if (!badge.url)
badge.url = '/earn/' + badge.id;
return badge;
}
function normalizeBadgeInstance (badge, id) {
/* This is dumb, but let's us reuse current templates to
build out a single-level object. */
_.extend(badge, badge.badgeClass);
if (!badge.id)
badge.id = id;
if (!badge.url)
badge.url = '/mybadges/' + id;
badge.id = id;
return badge;
}
function normalizeProgram(program, id) {
if (!id)
id = program.shortname;
if (!program.id)
program.id = id;
program.localUrl = '/explore/' + program.shortname;
return program;
}
var categories = [
{label: 'Science', value: 'science'},
{label: 'Technology', value: 'technology'},
{label: 'Engineering', value: 'engineering'},
{label: 'Art', value: 'art'},
{label: 'Math', value: 'math'}
];
var ageRanges = [
{label: 'Under 13', value: '0-13'},
{label: '13-18', value: '13-18'},
{label: '19-24', value: '19-24'}
];
var activityTypes = [
{label: 'Online', value: 'online'},
{label: 'Offline', value: 'offline'}
];
var badgeTypes = [
{label: 'Participation', value: 'participation'},
{label: 'Skill', value: 'skill'},
{label: 'Achievement', value: 'achievement'}
];
var orgs = [];
function updateOrgs (callback) {
if (typeof callback !== 'function')
callback = function () {};
openbadger.getOrgs(function (err, data) {
if (err)
return callback(err);
orgs = [];
(data.orgs || data.issuers).forEach(function (org) {
orgs.push({
label: org.name,
value: org.shortname
});
});
orgs.sort(function(a, b) {
var aVal = (a && a.label || '').toLowerCase().replace(/^\s*the\s+/, ''),
bVal = (b && b.label || '').toLowerCase().replace(/^\s*the\s+/, '');
return aVal.localeCompare(bVal);
});
callback(null, orgs);
});
}
function confirmFilterValue (value, list) {
if (!value && value !== 0)
return null;
for (var i = 0, l = list.length; i < l; ++i)
if (list[i].value === value)
return value;
return null;
}
function applyFilter (data, query) {
return _.filter(data, function(item) {
return _.reduce(query, function(memo, value, field) {
if (!memo) // We've already failed a test - no point in continuing
return memo;
if (!value && value !== 0)
return memo;
var data = item;
if (field.indexOf('.') > -1) {
var fieldParts = field.split('.').reverse();
while (data && fieldParts.length > 1) {
data = data[fieldParts.pop()];
}
field = fieldParts.reverse().join('.');
}
var itemValue = data ? data[field] : null;
if (_.isArray(itemValue))
return memo && _.contains(itemValue, value);
return memo && (itemValue === value);
}, true);
})
}
function getJWTToken(email) {
var claims = {
prn: email,
exp: Date.now() + TOKEN_LIFETIME
};
return jwt.encode(claims, JWT_SECRET);
}
function handleAutoAwards(email, learner, autoAwardedBadges) {
if (autoAwardedBadges && autoAwardedBadges.length > 0) {
async.map(autoAwardedBadges, function(shortname, cb) {
openbadger.getUserBadge({ id: shortname, email: email }, cb);
}, function(err, results) {
if (err) {
logger.log('info', 'Failed to get user badges from openbadger for email %s', email);
return;
}
iremix.invite({ learner: learner, badges: results });
});
}
}
var openbadger = new Api(ENDPOINT, {
getBadges: {
func: function getBadges (query, callback) {
this.getAllBadges(query, callback);
},
paginate: true,
key: 'badges'
},
getAllBadges: function getAllBadges (query, callback) {
var category = confirmFilterValue(query.category, categories),
ageGroup = confirmFilterValue(query.age, ageRanges),
badgeType = confirmFilterValue(query.type, badgeTypes),
activityType = confirmFilterValue(query.activity, activityTypes);
this.get('/badges', {qs: {search: query.search, category: category, ageGroup: ageGroup, badgeType: badgeType, activityType: activityType }}, function(err, data) {
if (err)
return callback(err, data);
return callback(null, {
badges: _.map(data.badges, normalizeBadge)
});
})
},
getBadge: function getBadge (query, callback) {
var id = query.id;
if (!id)
return callback(new errors.BadRequest('Invalid badge key'));
this.get('/badge/' + id, function(err, data) {
if (err)
return callback(err, data);
return callback(null, {
badge: normalizeBadge(data.badge, id)
});
});
},
getPrograms: {
func: function getPrograms (query, callback) {
var qs = {
category: query.category,
org: query.org,
age: query.age,
activity: query.activity,
search: query.search,
};
this.get('/programs', {qs: qs}, function(err, data) {
if (err)
return callback(err, data);
return callback(null, {
programs: _.map(data.programs, normalizeProgram)
});
});
},
paginate: true,
key: 'programs'
},
getProgram: function getProgram (query, callback) {
var id = query.id;
if (!id)
return callback(new errors.BadRequest('Invalid program key'));
this.get('/program/' + id, function(err, data) {
if (err)
return callback(err, data);
return callback(null, {
program: normalizeProgram(data.program, id)
});
});
},
getOrgs: function getOrgs (query, callback) {
this.get('/issuers/', function(err, data) {
if (err)
return callback(err, data);
return callback(null, {
orgs: _.values(data.issuers)
});
});
},
getUserBadges: {
func: function getUserBadges (query, callback) {
var email = query.email || query.session.user.email;
var params = {
auth: getJWTToken(email),
email: email
};
this.get('/user', { qs: params }, function(err, data) {
if (err)
return callback(err, data);
badges = _.map(data.badges, normalizeBadgeInstance)
return callback(null, {
badges: badges.sort(function(a, b) {
return b.issuedOn - a.issuedOn;
})
});
});
},
paginate: true,
key: 'badges'
},
getUserBadge: function getUserBadge (query, callback) {
var id = query.id;
var email = query.email || query.session.user.email;
var params = {
auth: getJWTToken(email),
email: email
};
this.get('/user/badge/' + id, { qs: params }, function(err, data) {
if (err)
return callback(err, data);
return callback(null, {
badge: normalizeBadgeInstance(data.badge, id)
});
});
},
awardBadge: function awardBadge (query, callback) {
var email = query.learner ? query.learner.email : query.session.user.email;
var shortname = query.badge;
var params = {
auth: getJWTToken(email),
email: email
}
this.post('/user/badge/' + shortname, { form: params }, function(err, data) {
if (err)
return callback(err, data);
handleAutoAwards(email, query.learner, data.autoAwardedBadges);
return callback(null, {
assertionUrl: data.url
});
});
},
getBadgeFromCode: function getBadgeFromCode (query, callback) {
var email = query.email;
var code = query.code;
var params = {
auth: getJWTToken(email),
email: email,
code: code,
};
this.get('/unclaimed', { qs: params }, function(err, data) {
return callback(err, data);
});
},
claim: function claim (query, callback) {
var email = query.learner ? query.learner.email : null;
var code = query.code;
var params = {
auth: getJWTToken(email),
email: email,
code: code,
};
this.post('/claim', { json: params }, function(err, data) {
if (err)
return callback(err);
handleAutoAwards(email, query.learner, data.autoAwardedBadges);
return callback(null, data);
});
},
getBadgeRecommendations: function getBadgeRecommendations (query, callback) {
var badgename = query.badgeName;
var id = query.id;
var limit = query.limit;
var params = {
limit: limit
};
if (badgename)
id = badgename
if (!id)
return callback(new errors.BadRequest('Invalid badge key'));
this.get('/badge/' + id + '/recommendations', { qs: params }, function(err, data) {
if (err)
return callback(err, data);
return callback(null, {
badges: _.map(data.badges, normalizeBadge)
});
});
},
getUserRecommendations: function getUserRecommendations (query, callback) {
var user = query.session.user;
var email = user.email;
var params = {
auth: getJWTToken(email),
email: email
};
this.get('/user/recommendations', {qs: params}, function(err, data) {
if (err)
return callback(err, null);
return callback(null, {
recommendations: _.map(data.badges, normalizeBadge)
});
});
}
});
updateOrgs();
module.exports = openbadger;
module.exports.getFilters = function getFilters () {
return {
categories: {
name: 'category',
label: 'Category',
options: categories
},
ageRanges: {
name: 'age',
label: 'Age',
options: ageRanges
},
orgs: {
name: 'org',
label: 'Organization',
options: orgs
},
activityTypes: {
name: 'activity',
label: 'Activity',
options: activityTypes
},
badgeTypes: {
name: 'type',
label: 'Type',
options: badgeTypes
},
search: {
name: 'search',
label: 'Search'
}
};
}
module.exports.updateOrgs = updateOrgs;
module.exports.healthCheck = function(meta, cb) {
// Use a privileged API call to ensure we're testing the JWT secret.
// A random email should guarantee we bust through any caches.
var random = Math.floor(Math.random() * 100000).toString();
var fakeClaimCode = 'healthCheck_test_' + random;
var email = fakeClaimCode + '@mozilla.org';
meta.notes = ENDPOINT;
meta.apiTest = meta.webhookTest = "FAILED";
async.waterfall([
openbadger.getUserBadges.bind(openbadger, {
session: {user: {email: email}}
}),
function(data, done) { meta.apiTest = "OK"; done(); },
openbadger.post.bind(openbadger, '/test/webhook', {
json: {
auth: getJWTToken(email),
email: email,
claimCode: fakeClaimCode
}
}),
function(data, done) {
if (!(data &&
data.status == "ok" &&
data.body == "S3_ITEM_CREATED"))
return done(new Error("unexpected webhook response: " +
JSON.stringify(data)));
s3.get('/' + fakeClaimCode).on('response', function(stream) {
var chunks = [];
stream.on('data', function(chunk) { chunks.push(chunk); });
stream.on('end', function() {
var result = Buffer.concat(chunks).toString('ascii');
if (result !== fakeClaimCode)
return done(new Error("unexpected s3 item content: " + result));
done();
});
}).end();
},
s3.deleteFile.bind(s3, '/' + fakeClaimCode),
function(_, done) { meta.webhookTest = "OK"; done(); }
], cb);
};