-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
84 lines (66 loc) · 2.34 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const querystring = require('querystring');
const url = require('url');
const rp = require('request-promise');
const redirect = require('micro-redirect');
const uuid = require('uuid');
const provider = 'facebook';
const microAuthFacebook = ({ appId, appSecret, fields = 'name,email,cover', callbackUrl, path = '/auth/facebook', scope = 'public_profile,email', apiVersion = '2.11' }) => {
const getRedirectUrl = state => {
return `https://www.facebook.com/dialog/oauth?client_id=${appId}&redirect_uri=${callbackUrl}&response_type=code&state=${state}&scope=${scope}`;
};
const getAccessTokenUrl = code => {
return `https://graph.facebook.com/v${apiVersion}/oauth/access_token?client_id=${appId}&redirect_uri=${callbackUrl}&client_secret=${appSecret}&code=${code}`;
};
const getUserInfoUrl = accessToken => {
return `https://graph.facebook.com/v${apiVersion}/me?access_token=${accessToken}&fields=${fields}`;
};
const states = [];
return fn => async (req, res, ...args) => {
const { pathname, query } = url.parse(req.url);
if (pathname === path) {
try {
const state = uuid.v4();
const redirectUrl = getRedirectUrl(state);
states.push(state);
return redirect(res, 302, redirectUrl);
} catch (err) {
args.push({ err, provider });
return fn(req, res, ...args);
}
}
const callbackPath = url.parse(callbackUrl).pathname;
if (pathname === callbackPath) {
try {
const { state, code } = querystring.parse(query);
if (!states.includes(state)) {
const err = new Error('Invalid state');
args.push({ err, provider });
return fn(req, res, ...args);
}
const response = await rp({
method: 'GET',
url: getAccessTokenUrl(code),
json: true
});
const accessToken = response.access_token;
const info = await rp({
method: 'GET',
url: getUserInfoUrl(accessToken),
json: true
});
const result = {
provider,
accessToken,
info
};
args.push({ result });
return fn(req, res, ...args);
} catch (err) {
args.push({ err, provider });
return fn(req, res, ...args);
}
}
return fn(req, res, ...args);
};
};
module.exports = microAuthFacebook;