-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathapp.js
70 lines (49 loc) · 1.44 KB
/
app.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
var express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
OAuth2Server = require('oauth2-server'),
Request = OAuth2Server.Request,
Response = OAuth2Server.Response;
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var mongoUri = 'mongodb://localhost/oauth';
mongoose.connect(mongoUri, {
useCreateIndex: true,
useNewUrlParser: true
}, function(err, res) {
if (err) {
return console.error('Error connecting to "%s":', mongoUri, err);
}
console.log('Connected successfully to "%s"', mongoUri);
});
app.oauth = new OAuth2Server({
model: require('./model.js'),
accessTokenLifetime: 60 * 60,
allowBearerTokensInQueryString: true
});
app.all('/oauth/token', obtainToken);
app.get('/', authenticateRequest, function(req, res) {
res.send('Congratulations, you are in a secret area!');
});
app.listen(3000);
function obtainToken(req, res) {
var request = new Request(req);
var response = new Response(res);
return app.oauth.token(request, response)
.then(function(token) {
res.json(token);
}).catch(function(err) {
res.status(err.code || 500).json(err);
});
}
function authenticateRequest(req, res, next) {
var request = new Request(req);
var response = new Response(res);
return app.oauth.authenticate(request, response)
.then(function(token) {
next();
}).catch(function(err) {
res.status(err.code || 500).json(err);
});
}