-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.js
101 lines (81 loc) · 2.52 KB
/
auth.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
var open = require('open'),
sdk = require('facebook-node-sdk'),
nconf = require('nconf'),
http = require('http'),
request = require('request'),
querystring = require('querystring');
// Config file
var configFile = __dirname + '/config.json';
/**
* Configuration file settings
*/
nconf.file({ file: configFile });
module.exports = function(params,callback){
var getAccessToken = function() {
var redirect_uri = 'http://localhost:3000/';
var server = http.createServer(function (req, res) {
// haha
var code = querystring.parse(req.url)['/?code'];
if (code) {
var url = "https://graph.facebook.com/oauth/access_token?"
+ "client_id=" + params.appId
+ "&client_secret=" + params.secret
+ "&redirect_uri=" + redirect_uri
+ "&code=" + code;
request(url, function(err,response,body) {
var token = querystring.parse(body).access_token;
if(token) {
params.fb.setAccessToken(token);
nconf.set('token', token);
// Save the configuration object
nconf.save();
callback(params.fb);
// TODO close server doesn't work?
server.close();
} else {
console.log('Something went wrong.');
}
})
}
else {
console.log('Something went wrong.');
}
res.end('Now you are logged in. Go to the terminal!');
}).listen(3000);
var codeUrl = 'https://www.facebook.com/dialog/oauth?client_id=' + params.appId + '&redirect_uri=' + redirect_uri;
// Get additional permissions
if (params.permissions) {
codeUrl += '&scope=' + params.permissions.join(",");
}
open(codeUrl);
};
// Get access token from memory
var token = nconf.get('token');
if (token) {
// Set access token to facebook object
params.fb.setAccessToken(token);
// Try with our access token
params.fb.api('/me/permissions',function(err, response){
if (err) {
getAccessToken();
return;
}
else {
if (params.permissions) {
var permissions = response.data[0];
// Check required permissions. if something is missing, get another access token.
for(var i = 0; i < params.permissions.length; i++){
if(!permissions[params.permissions[i]]) {
getAccessToken();
return;
}
}
}
}
callback(params.fb);
});
}
else {
getAccessToken();
}
};