-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathobo_express_dev.js
More file actions
499 lines (463 loc) · 15.7 KB
/
Copy pathobo_express_dev.js
File metadata and controls
499 lines (463 loc) · 15.7 KB
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
490
491
492
493
494
495
496
497
498
499
const path = require('path')
global.oboRequire = name => require(path.resolve(__dirname, '..', name))
const db = require('obojobo-express/server/db')
const sig = require('oauth-signature')
const config = require('./config')
const oauthKey = Object.keys(config.lti.keys)[0]
const oauthSecret = config.lti.keys[oauthKey]
const User = require('obojobo-express/server/models/user')
const DraftSummary = require('obojobo-repository/server/models/draft_summary')
const POSSIBLE_PERMS = [
'canViewEditor',
'canCreateDrafts',
'canDeleteDrafts',
'canPreviewDrafts',
'canViewStatsPage',
'canViewSystemStats',
'canViewAdminPage'
]
// Normally the query running in User.saveOrCreate would auto-fill the new user's id,
// but since we're using the user's ID as part of their name and e-mail, we need to know what
// it is going to be ahead of time
const getNewUserId = () => {
return db
.oneOrNone('SELECT MAX(id) AS max_id FROM users')
.then(result => parseInt(result.max_id, 10) + 1)
}
const createNewUser = (id, first, last, type) => {
// If the database is freshly reset, there won't be any users - assume the first id is 1
if (!id) id = 1
const capType = type.charAt(0).toUpperCase() + type.slice(1)
const newUser = new User({
username: `sis:tst${type}${id}`,
email: `test_${type}_${id}@obojobo.com`,
firstName: first || 'Test',
lastName: last || `${capType} ${id}`,
roles: [capType]
})
return newUser.saveOrCreate()
}
const spoofLTIUser = user => ({
lis_person_contact_email_primary: user.email,
lis_person_name_family: user.lastName,
lis_person_name_full: `${user.firstName} ${user.lastName}`,
lis_person_name_given: user.firstName,
lis_person_sourcedid: user.username,
roles: user.roles[0],
user_id: parseInt(user.id, 10) + 10000,
user_image: 'https://s.gravatar.com/avatar/17f34572459fa620071cae55d7f1eacb?s=80'
})
const ltiToolConsumer = {
tool_consumer_info_product_family_code: 'obojobo-next',
tool_consumer_instance_guid: 'obojobo.ucf.edu',
tool_consumer_instance_name: 'University of Central Florida',
tool_consumer_instance_url: 'https://obojobo.ucf.edu/'
}
const ltiContext = {
context_id: 'S3294476',
context_label: 'OBO4321',
context_title: 'Obojobo Local Dev 101',
context_type: 'CourseSection'
}
const defaultResourceLinkId = 'obojobo-dev-resource-id'
// constructs a signed lti request and sends it.
const renderLtiLaunch = (paramsIn, method, endpoint, res) => {
// add the required oauth params to the given prams
const oauthParams = {
oauth_nonce: Math.round(new Date().getTime()),
oauth_timestamp: Math.round(new Date().getTime() / 1000.0),
oauth_callback: 'about:blank',
oauth_consumer_key: oauthKey,
oauth_signature_method: 'HMAC-SHA1',
oauth_version: '1.0'
}
const params = { ...paramsIn, ...oauthParams }
const hmac_sha1 = sig.generate(method, endpoint, params, oauthSecret, '', {
encodeSignature: false
})
params['oauth_signature'] = hmac_sha1
const keys = Object.keys(params)
const htmlInput = keys
.map(key => `<input type="hidden" name="${key}" value="${params[key]}"/><br/>`)
.join('')
res.set('Content-Type', 'text/html')
res.send(`<html>
<body>
<form id="form"
method="${method}"
action="${endpoint}">
${htmlInput}
</form>
<script>
document.getElementById('form').submit()
</script>
</body>
</html>`)
}
// util to get a baseUrl for inernal requests
const baseUrl = req => `${req.protocol}://${req.get('host')}`
module.exports = app => {
const bodyParser = require('body-parser')
app.use(bodyParser.json(config.general.bodyParser.jsonOptions))
app.use(bodyParser.urlencoded(config.general.bodyParser.urlencodedOptions))
// index page with links to all the launch types
app.get('/dev/', (req, res) => {
const usersPromise = db.manyOrNone(
'SELECT id, first_name, last_name FROM users ORDER BY id ASC'
)
const draftsPromise = DraftSummary.fetchAll()
Promise.all([usersPromise, draftsPromise]).then(results => {
const users = results[0]
const drafts = results[1]
const userOptions = users
.map(user => `<option value=${user.id}>${user.first_name} ${user.last_name}</option>`)
.join('')
const draftOptions = drafts
.map(draft => `<option value="${draft.draftId}">${draft.title}</option>`)
.join('')
let userSelectRender =
'<p>No users found. Create a student or instructor with the buttons above.</p>'
if (userOptions && userOptions.length) {
userSelectRender = `
<label for='user_id'>Select user:</label>
<select name='user_id'>
${userOptions}
</select>`
}
const permOptions = POSSIBLE_PERMS.map(perm => `<option value="${perm}">${perm}</option>`)
res.set('Content-Type', 'text/html')
res.send(`<html>
<head>
<title>Obojobo Next Express Dev Utils</title>
<script>
const launchInIframe = url => {
const iframeEl = document.getElementById('the-iframe')
iframeEl.src = url
iframeEl.scrollIntoView()
}
const scrollToIframe = () => {
const iframeEl = document.getElementById('the-iframe')
iframeEl.scrollIntoView()
}
</script>
<style>
iframe{
width: 620px;
height: 475px;
resize: both;
overflow: auto;
}
</style>
</head>
<body>
<h1>Obojobo Next Express Dev Utils</h1>
<h2>User Management Tools</h2>
<ul>
<li><b>Create new test users:</b>
<form id='new-user-form'
method='post'
action='/dev/util/new_user'>
<label for='first'>First name:</label>
<input type='text' name='first' placeholder='Test (Optional)'/>
<br/>
<label for='last'>Last name:</label>
<input type='text' name='last' placeholder='User (Optional)'/>
<br/>
<button type='submit' name='type' value='instructor'>Create new test instructor</button>
Note: The <b>canViewEditor</b>, <b>canCreateDrafts</b>, <b>canDeleteDrafts</b>, and <b>canPreviewDrafts</b> permissions are implicit for instructors.
<br/>
<button type='submit' name='type' value='learner'>Create new test learner</button>
</form>
</li>
<li><b>Add permission to user:</b>
<form id='resource-select-form'
method='post'
action='/dev/util/permission'>
${userSelectRender}
${
userOptions.length
? `<br/>
<label for='permission'>Select permission:</label>
<select name='permission'>
${permOptions}
</select>
<br/>
<input type='hidden' name='add_remove' value='add'/>
<button type='submit' value='submit'>Add</button>`
: ''
}
</form>
</li>
<li><b>Remove permission from user:</b>
<form id='resource-select-form'
method='post'
action='/dev/util/permission'>
${userSelectRender}
${
userOptions.length
? `<br/>
<label for='permission'>Select permission:</label>
<select name='permission'>
${permOptions}
</select>
<br/>
<input type='hidden' name='add_remove' value='remove'/>
<button type='submit' value='submit'>Remove</button>`
: ''
}
</form>
</li>
</ul>
<h2>LTI Tools</h2>
<ul>
<li><a href="/lti">LTI Instructions</a></li>
<li><b>LTI Course Nav:</b> (simulate LTI launch from clicking on LMS nav menu link)
<form id='course-nav-form'
method='post'
target='_blank'
action='/lti/dev/launch/course_navigation'>
<input type='hidden' name='resource_link_id' value='course_1' />
${userSelectRender}
${userOptions.length ? "<button type='submit' value='submit'>Go</button>" : ''}
</form>
</li>
<li><b>LTI Resource Selection:</b> (simulate LTI launch for resource/assignment selection)
<form id='resource-select-form'
method='get'
action='/lti/dev/launch/resource_selection'
target='the-iframe'>
${userSelectRender}
${
userOptions.length
? `<button onClick="scrollToIframe()" type='submit' value='submit'>Go</button>`
: ''
}
</form>
</li>
<li><b>LTI Assignment:</b> (simulate LTI launch for an assignment)
<form id='resource-select-form'
method='get'
action='/lti/dev/launch/view'
target='_blank'>
${userSelectRender}
${
userOptions.length
? `<br/>
<label for='draft_id'>Select module:</label>
<select name='draft_id'>
${draftOptions}
</select>
<br/>
<label for='score_import'>Score import enabled:</label>
<input type='checkbox' name='score_import' />
<br/>
<label for='resource_link_id'>LMS course ID:</label>
<input type='text' name='resource_link_id' placeholder="course_1"/>
<br/>
<label>LMS context ID:</label>
<input type='text' name='context_id' placeholder='S3294476'/>
<br/>
<label>LMS context label:</label>
<input type='text' name='context_label' placeholder='OBO4321'/>
<br/>
<label>LMS context title:</label>
<input type='text' name='context_title' placeholder='Obojobo Local Dev 101'/>
<br/>
<label>LMS resource link title:</label>
<input type='text' name='resource_link_title' placeholder='Embedded Assignment'/>
<br/>
<button type='submit' value='submit'>Go</button>`
: ''
}
</form>
</li>
</ul>
<h2>Build Tools</h2>
<ul>
<li><a href="/routes">Express Routes</a></li>
<li><a href="/webpack-dev-server">Webpack Dev Server Assets</a></li>
</ul>
<h2>Iframe for simulating assignment selection overlay</h2>
<iframe id="the-iframe" name="the-iframe"></iframe>
</body>
</html>`)
})
})
// json list of every express.js route
app.get('/routes', (req, res) => {
const listEndpoints = require('express-list-endpoints')
const foundPaths = new Set()
const simplifiedEndpoints = listEndpoints(app)
// remove express's * path
.filter(i => i.path !== '*')
// filter any duplicat paths
.filter(i => {
if (foundPaths.has(i.path)) return false
foundPaths.add(i.path)
return true
})
// sort the remaining paths
.sort((a, b) => a.path.localeCompare(b.path))
res.json(simplifiedEndpoints)
})
app.post('/lti/dev/launch/course_navigation', (req, res) => {
// const resource_link_id = req.query.resource_link_id || defaultResourceLinkId
// const instructorOneOrTwo = req.query.instructor === '2' ? ltiInstructor2 : ltiInstructor
User.fetchById(req.body.user_id).then(user => {
const resource_link_id = req.body.resource_link_id || defaultResourceLinkId
const person = spoofLTIUser(user)
const params = {
launch_presentation_css_url: 'https://example.fake/nope.css',
launch_presentation_document_target: 'frame',
launch_presentation_locale: 'en-US',
launch_presentation_return_url: 'https://example.fake/fake-return.html',
lis_course_offering_sourcedid: 'DD-ST101',
lis_course_section_sourcedid: 'DD-ST101:C1',
lis_outcome_service_url: 'https://example.fake/outcomes/fake',
lis_result_sourcedid: 'UzMyOTQ0NzY6Ojo0Mjk3ODUyMjY6OjoyOTEyMw==',
lti_message_type: 'basic-lti-launch-request',
lti_version: 'LTI-1p0',
resource_link_id,
resource_link_title: 'Phone home'
}
renderLtiLaunch(
{ ...ltiContext, ...person, ...ltiToolConsumer, ...params },
'POST',
`${baseUrl(req)}/lti/canvas/course_navigation`,
res
)
})
})
// builds a valid document view lti launch and submits it
app.get('/lti/dev/launch/view', (req, res) => {
User.fetchById(req.query.user_id).then(user => {
const resource_link_id = req.query.resource_link_id || defaultResourceLinkId
const draftId = req.query.draft_id || '00000000-0000-0000-0000-000000000000'
const person = spoofLTIUser(user)
const params = {
lis_outcome_service_url: 'https://example.fake/outcomes/fake',
lti_message_type: 'basic-lti-launch-request',
lti_version: 'LTI-1p0',
resource_link_id,
score_import: req.query.score_import === 'on' ? 'true' : 'false'
}
const launchContext = { ...ltiContext }
if (req.query.context_id) launchContext.context_id = req.query.context_id
if (req.query.context_label) launchContext.context_label = req.query.context_label
if (req.query.context_title) launchContext.context_title = req.query.context_title
if (req.query.resource_link_title) {
launchContext.resource_link_title = req.query.resource_link_title
}
renderLtiLaunch(
{ ...launchContext, ...person, ...params },
'POST',
`${baseUrl(req)}/view/${draftId}`,
res
)
})
})
// builds a valid resourse selection lti launch and submits it
app.get('/lti/dev/launch/resource_selection', (req, res) => {
User.fetchById(req.query.user_id).then(user => {
const person = spoofLTIUser(user)
const params = {
accept_copy_advice: 'false',
accept_media_types: '*/*',
accept_multiple: 'false',
accept_presentation_document_targets: 'embed,frame,iframe,window,popup,overlay,none',
accept_unsigned: 'false',
auto_create: 'true',
can_confirm: 'false',
content_item_return_url: `${baseUrl(
req
)}/lti/dev/return/resource_selection?test=this%20is%20a%20test`,
launch_presentation_css_url: 'https://example.fake/nope.css',
launch_presentation_locale: 'en-US',
lti_message_type: 'ContentItemSelectionRequest',
lti_version: 'LTI-1p0',
data: "this opaque 'data' should be sent back to the LMS!"
}
renderLtiLaunch(
{ ...ltiContext, ...person, ...ltiToolConsumer, ...params },
'POST',
`${baseUrl(req)}/lti/canvas/resource_selection`,
res
)
})
})
// route that resource selections will return to
app.post('/lti/dev/return/resource_selection', (req, res) => {
const data = JSON.parse(req.body.content_items)
res.set('Content-Type', 'text/html')
res.send(`<html>
<body>
<h1>Resource selected!</h1>
<ul>
<li>URL: ${req.originalUrl}</li>
<li>lti_message_type: ${req.body.lti_message_type}</li>
<li>Type: ${data['@graph'][0]['@type']}</li>
<li>URL: ${data['@graph'][0].url}</li>
<li>Title: ${data['@graph'][0].title}</li>
<li>Data: ${req.body.data}</li>
</ul>
<code>${req.body.content_items}</code>
</body>
</html>`)
})
app.post('/dev/util/new_user', (req, res) => {
getNewUserId().then(newId => {
const { first, last, type } = req.body
createNewUser(newId, first, last, type).then(() => {
res.redirect('/dev')
})
})
})
app.post('/dev/util/permission', (req, res) => {
const userId = req.body.user_id
const op = req.body.add_remove
db.oneOrNone('SELECT perms FROM user_perms WHERE user_id = $[userId]', { userId })
.then(existing => {
// selected user has no explicitly set permissions
if (!existing) {
existing = { perms: [] }
}
const perms = [...existing.perms]
const existingPermIndex = perms.indexOf(req.body.permission)
// either trying to add a permissions the user has already, or remove one it doesn't have yet
if (
(op === 'add' && existingPermIndex >= 0) ||
(op === 'remove' && existingPermIndex < 0)
) {
// do nothing
return false
}
switch (req.body.add_remove) {
case 'add':
perms.push(req.body.permission)
break
case 'remove':
default:
perms.splice(existingPermIndex, 1)
break
}
return perms
})
.then(perms => {
if (!perms) return
return db.none(
`
INSERT INTO user_perms
VALUES ($[userId], $[perms])
ON CONFLICT (user_id)
DO UPDATE
SET perms = $[perms]
WHERE user_perms.user_id = $[userId]
`,
{ userId, perms }
)
})
.then(() => {
res.redirect('/dev')
})
})
}