-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
171 lines (145 loc) · 4.84 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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
var rem = require('rem')
, express = require('express')
, path = require('path');
/**
* Create Application
*/
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000); // sets up the port
app.set('host', process.env.HOST || ('localhost:' + app.get('port')));
app.use(express.cookieParser());
app.use(express.session({
secret: "some arbitrary secret"
}));
app.use(express.favicon()); // default favicon
app.use(express.logger('dev')); // error logging
app.use(express.bodyParser()); //
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public'))); // sets the path for public files (css & js)
})
/**
* Facebook API
*/
console.log(process.env);
var fb = rem.connect('facebook.com', '1.0').configure({
key: process.env.FB_KEY,
secret: process.env.FB_SECRET
});
// Crudely store user access tokens in a global hash for the duration of
// the Heroku app's life.
//
// In production, you would probably replace these with database-backed
// functions. As a convenience, these are written as asynchronous functions,
// though that's totally superfluous here.
var keys = {}
, keyskey = 'im not actually a beggar, im actually a... magic man';
function hashUserId (id) {
return require('crypto').createHmac('sha1', keyskey).update(id).digest('hex');
}
function storeCredentials (id, state, next) {
keys[hashUserId(id)] = state;
next(null);
}
function restoreCredentials (hash, next) {
next(null, keys[hash]);
}
function clearStoredCredentials (id, next) {
next(!(delete keys[hashUserId(id)]));
}
// The oauth middleware intercepts the callback url that we set when we
// created the oauth middleware.
var oauth = rem.oauth(fb, 'http://' + app.get('host') + '/oauth/callback/');
app.use(oauth.middleware(function (req, res, next) {
console.log("User is now authenticated.");
var user = oauth.session(req);
user('me').get(function (err, json) {
user.saveState(function (state) {
if (err || !json.id) {
res.redirect('/error');
}
storeCredentials(json.id, state, function () {
res.redirect('/');
});
})
});
}));
// Login route calls oauth.startSession, which redirects to an oauth URL.
app.get('/login/', oauth.login({
scope: ['publish_actions']
}));
// Logout route clears the user's session.
// Use middleware to clear the tokens from our tokens store as well.
app.get('/logout/', function (req, res, next) {
var user = oauth.session(req);
if (!user) {
return next();
}
user('me').get(function (err, json) {
if (json && json.id) {
clearStoredCredentials(json.id, next);
} else {
next();
}
})
}, oauth.logout(function (req, res) {
res.redirect('/');
}));
/**
* Routes
*/
app.get('/error', function (req, res) {
res.send('There was an error logging into Facebook. Please retry.');
});
app.get('/', function (req, res) {
var user = oauth.session(req);
if (!user) {
res.setHeader('Content-Type', 'text/html');
return res.send('<a href="/login/">Log in to GraphButton.</a>', 400);
}
user('me').get(function (err, json) {
var path = '/action/' + hashUserId(json.id);
res.setHeader('Content-Type', 'text/html');
res.write('<p>GraphButton Demo! The current acting Facebook user is <a href="https:/facebook.com/' + json.id + '">' + json.id + '</a>.</p>');
res.write('<p>POST to <a href="http://' + app.get('host') + path + '">http://' + app.get('host') + path + '</a> to submit your action:</p>');
res.write('<form action="' + path + '" method="post"><button>Post to Open Graph</button></form>')
res.write('<p><a href="/logout/">Logout from GraphButton.</a></p>');
res.end();
})
});
app.post('/action/:user', function (req, res) {
restoreCredentials(req.params.user, function (err, tokens) {
if (!tokens) {
return res.json({message: 'Invalid or expired id.'}, 400);
}
// Attempt to restore the tokens. Validate whether the session remains valid.
var user = oauth.restore(tokens);
user.validate(function (valid) {
if (!valid) {
clearStoredCredentials(req.param.user, function () {
oauth.clearSession(req);
return res.json({message: 'Expired Facebook credentials. Please log in again.'}, 400);
});
}
user('me/' + process.env.FB_ACTION).post({
button: process.env.FB_SAMPLE
}, function (err, json) {
res.setHeader('Content-Type', 'text/html');
res.write('Response: <pre>');
res.write(JSON.stringify(json, null, '\t'));
res.write('</pre>');
if (json.id) {
var url = 'https://facebook.com/' + json.id;
res.write('See action: <a href="' + url + '">' + url + '</a>');
}
res.end();
});
});
});
})
/**
* Launch
*/
app.listen(app.get('port'), function () {
console.log('Running on http://' + app.get('host'));
})