-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (49 loc) · 1.54 KB
/
index.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
const OAuthServer = require('oauth2-server');
const JWTHandler = require('./src/jwthandler');
const { Request, Response } = OAuthServer;
module.exports = (dataStore, configuration) => {
const accessTokenLifetime = configuration.accessTokenExpiry || 1800;
const refreshTokenLifetime = configuration.refreshTokenExpiry || 1209600;
const model = new JWTHandler(dataStore, accessTokenLifetime, refreshTokenLifetime);
const oauth = new OAuthServer({
model,
accessTokenLifetime,
refreshTokenLifetime,
});
const handler = {};
handler.token = (req, res, next) => {
const request = new Request(req);
const response = new Response(res);
if (!request.body.client_secret) {
request.body.client_secret = 'default';
}
if (!request.body.scope) {
request.body.scope = 'default';
}
oauth.token(request, response)
.then(() => {
res.set(response.headers);
res.json(response.body);
}).catch(err => next(err));
};
handler.authenticate = (req, res, next) => {
const request = new Request(req);
const response = new Response(res);
if (req.query.scope) {
oauth.authenticate(request, response, { scope: req.query.scope })
.then((token) => {
Object.assign(req, { user: token });
next();
})
.catch(err => next(err));
} else {
oauth.authenticate(request, response)
.then((token) => {
Object.assign(req, { user: token });
next();
})
.catch(err => next(err));
}
};
return handler;
};