-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
executable file
·65 lines (57 loc) · 1.82 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
56
57
58
59
60
61
62
63
64
65
const FastifyOAuthServer = require('./oauthServer');
const fp = require('fastify-plugin');
function plugin (fastify, options, next) {
const opts = Object.assign({}, options || {});
const oauthServer = new FastifyOAuthServer(opts);
fastify.decorateRequest('oauth', null)
fastify.addHook('onRequest', (req, reply, done) => {
req.oauth = {
authenticate: authenticate,
authorize: authorize,
token: token,
}
done()
})
function authenticate(req, reply){
return new Promise((resolve, reject) => {
oauthServer.authenticate({skipResponse: true})(req.raw, reply.res, function (err, authenticated) {
if(err){
reject(err);
}else{
resolve(authenticated);
}
});
});
}
function authorize(req, reply){
return new Promise((resolve, reject) => {
req.raw.query = req.query;
req.raw.body = req.body;
oauthServer.authorize({skipResponse: true})(req.raw, reply.res, function (err, authenticated) {
if(err){
reject(err);
}else{
resolve(authenticated);
}
});
});
}
function token(req, reply){
return new Promise((resolve, reject) => {
req.raw.query = req.query;
req.raw.body = req.body;
oauthServer.token({skipResponse: true})(req.raw, reply.res, function (err, authenticated) {
if(err){
reject(err);
}else{
resolve(authenticated);
}
});
});
}
next();
}
module.exports = fp(plugin, {
fastify: '>= 0.39.0',
name: 'fastify-oauth-server'
});