-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoauth.js
73 lines (66 loc) · 3 KB
/
oauth.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
'use strict';
const querystring = require('querystring'),
configs = require('../configurations'),
helpers = require('../helpers'),
request = require('superagent'),
express = require('express'),
router = express.Router();
module.exports = function () {
/* GET /oauth
* This endpoint is used to redirect the user to the authentication route
* on the learning environment side so that the user can confirm
* that they want allow this application to make API requests on
* their behalf.
*/
router.get('/oauth', function(req, res) {
// The state value is hardcoded for the sample but normally should change with each request to the
// authentication endpoint and then stored securely. Please read the configuration.md readme for
// more information.
const authCodeParams = querystring.stringify({
response_type: 'code',
redirect_uri: helpers.getRedirectUri(req),
client_id: configs.clientId,
scope: configs.authCodeScope,
state: configs.state
});
res.redirect(configs.authEndpoint + '?' + authCodeParams);
});
/* GET /oauthcallback
* This endpoint is the callback provided when setting up an oauth
* client in the learning environment and is called after the user has
* granted permission for this application to make API requests. This
* method takes the authorization code and exchanges it for
* the token(stores it in a cookie) that can then be used to make API requests.
*/
router.get('/oauthcallback', function(req, res) {
const authorizationCode = req.query.code;
const state = req.query.state;
if (state !== configs.state) {
console.log('The state value from the authorization request was incorrect.');
res.status(500).send({ error: 'STATE mistmatch - authorization request could not be completed.'});
return;
}
const payload = querystring.stringify({
grant_type: 'authorization_code',
redirect_uri: helpers.getRedirectUri(req),
code: authorizationCode
});
request
.post(configs.tokenEndpoint)
.auth(configs.clientId, configs.clientSecret)
.send(payload)
.end(function(err, response) {
if (err) {
console.log('Access Token Error', err.response || err);
res.redirect('/auth');
} else if(response.statusCode !== 200) {
res.status(response.statusCode).send(response.error);
} else {
const accessToken = response.body.access_token;
res.cookie(configs.cookieName, { accessToken: accessToken }, configs.cookieOptions);
res.redirect('/?authenticationType=oauth');
}
});
});
return router;
};