Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
83 lines (72 loc) · 1.98 KB
/
Copy pathapp.js
File metadata and controls
83 lines (72 loc) · 1.98 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
var crypto = require('crypto'),
express = require('express'),
request = require('request'),
url = require('url');
var app = express();
app.use(express.cookieParser());
// insert your app key and secret here
var APP_KEY = '<YOUR APP KEY>';
var APP_SECRET = '<YOUR APP SECRET>';
function generateCSRFToken() {
return crypto.randomBytes(18).toString('base64')
.replace(/\//g, '-').replace(/\+/g, '_');
}
function generateRedirectURI(req) {
return url.format({
protocol: req.protocol,
host: req.headers.host,
pathname: app.path() + '/callback'
});
}
app.get('/', function (req, res) {
var csrfToken = generateCSRFToken();
res.cookie('csrf', csrfToken);
res.redirect(url.format({
protocol: 'https',
hostname: 'www.dropbox.com',
pathname: '1/oauth2/authorize',
query: {
client_id: APP_KEY,
response_type: 'code',
state: csrfToken,
redirect_uri: generateRedirectURI(req)
}
}));
});
app.get('/callback', function (req, res) {
if (req.query.error) {
return res.send('ERROR ' + req.query.error + ': ' + req.query.error_description);
}
// check CSRF token
if (req.query.state !== req.cookies.csrf) {
return res.status(401).send(
'CSRF token mismatch, possible cross-site request forgery attempt.'
);
}
// exchange access code for bearer token
request.post('https://api.dropbox.com/1/oauth2/token', {
form: {
code: req.query.code,
grant_type: 'authorization_code',
redirect_uri: generateRedirectURI(req)
},
auth: {
user: APP_KEY,
pass: APP_SECRET
}
}, function (error, response, body) {
var data = JSON.parse(body);
if (data.error) {
return res.send('ERROR: ' + data.error);
}
// extract bearer token
var token = data.access_token;
// use the bearer token to make API calls
request.get('https://api.dropbox.com/1/account/info', {
headers: { Authorization: 'Bearer ' + token }
}, function (error, response, body) {
res.send('Logged in successfully as ' + JSON.parse(body).display_name + '.');
});
});
});
app.listen(5000);