-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathfacebook-hack.py
More file actions
288 lines (209 loc) · 8.65 KB
/
facebook-hack.py
File metadata and controls
288 lines (209 loc) · 8.65 KB
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# -*- coding: utf-8 -*-
import base64
import os
import os.path
import urllib
import hmac
import json
import hashlib
import random
from base64 import urlsafe_b64decode, urlsafe_b64encode
import requests
from flask import Flask, request, redirect, render_template, url_for, json, jsonify
FB_APP_ID = os.environ.get('FACEBOOK_APP_ID')
requests = requests.session()
app_url = 'https://graph.facebook.com/{0}'.format(FB_APP_ID)
FB_APP_NAME = json.loads(requests.get(app_url, verify=False).content).get('name')
FB_APP_SECRET = os.environ.get('FACEBOOK_SECRET')
def oauth_login_url(preserve_path=True, next_url=None):
fb_login_uri = ("https://www.facebook.com/dialog/oauth"
"?client_id=%s&redirect_uri=%s" %
(app.config['FB_APP_ID'], get_home()))
if app.config['FBAPI_SCOPE']:
fb_login_uri += "&scope=%s" % ",".join(app.config['FBAPI_SCOPE'])
print fb_login_uri
return fb_login_uri
def simple_dict_serialisation(params):
return "&".join(map(lambda k: "%s=%s" % (k, params[k]), params.keys()))
def base64_url_encode(data):
return base64.urlsafe_b64encode(data).rstrip('=')
def fbapi_get_string(path,
domain=u'graph', params=None, access_token=None,
encode_func=urllib.urlencode):
"""Make an API call"""
if not params:
params = {}
params[u'method'] = u'GET'
if access_token:
params[u'access_token'] = access_token
for k, v in params.iteritems():
if hasattr(v, 'encode'):
params[k] = v.encode('utf-8')
url = u'https://' + domain + u'.facebook.com' + path
params_encoded = encode_func(params)
url = url + params_encoded
result = requests.get(url, verify=False).content
return result
def fbapi_auth(code):
params = {'client_id': app.config['FB_APP_ID'],
'redirect_uri': get_home(),
'client_secret': app.config['FB_APP_SECRET'],
'code': code}
result = fbapi_get_string(path=u"/oauth/access_token?", params=params,
encode_func=simple_dict_serialisation)
pairs = result.split("&", 1)
result_dict = {}
for pair in pairs:
(key, value) = pair.split("=")
result_dict[key] = value
return (result_dict["access_token"], result_dict["expires"])
def fbapi_get_application_access_token(id):
token = fbapi_get_string(
path=u"/oauth/access_token",
params=dict(grant_type=u'client_credentials', client_id=id,
client_secret=app.config['FB_APP_SECRET']),
domain=u'graph')
token = token.split('=')[-1]
if not str(id) in token:
print 'Token mismatch: %s not in %s' % (id, token)
return token
def fql(fql, token, args=None):
if not args:
args = {}
args["query"], args["format"], args["access_token"] = fql, "json", token
url = "https://api.facebook.com/method/fql.query"
r = requests.get(url, verify=False, params=args)
return json.loads(r.content)
def fb_call(call, args=None):
url = "https://graph.facebook.com/{0}".format(call)
r = requests.get(url, verify=False, params=args)
return json.loads(r.content)
def get_user_posts():
access_token = get_token()
if access_token:
args = {'access_token': access_token}
my_posts = fb_call('/me/posts/', args=args)
children = []
if my_posts:
for data in my_posts['data']:
likes_count = 0
if 'likes' in data:
likes_count = data['likes'].get('count')
comments_count = 0
if 'comments' in data:
likes_count = data['comments'].get('count')
if likes_count != 0 or comments_count != 0:
children.append({
'id': data['id'],
#'description': data['description'],
'display_name': data['type'],
'likes': likes_count,
'comments': comments_count,
})
return children
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_object('conf.Config')
def get_home():
return 'https://' + request.host + '/'
def get_token():
if request.args.get('code', None):
return fbapi_auth(request.args.get('code'))[0]
cookie_key = 'fbsr_{0}'.format(FB_APP_ID)
if cookie_key in request.cookies:
c = request.cookies.get(cookie_key)
encoded_data = c.split('.', 2)
sig = encoded_data[0]
data = json.loads(urlsafe_b64decode(str(encoded_data[1])))
if not data['algorithm'].upper() == 'HMAC-SHA256':
raise ValueError('unknown algorithm {0}'.format(data['algorithm']))
h = hmac.new(FB_APP_SECRET, digestmod=hashlib.sha256)
h.update(encoded_data[1])
expected_sig = urlsafe_b64encode(h.digest()).replace('=', '')
if sig != expected_sig:
raise ValueError('bad signature')
code = data['code']
params = {
'client_id': FB_APP_ID,
'client_secret': FB_APP_SECRET,
'redirect_uri': '',
'code': data['code']
}
from urlparse import parse_qs
r = requests.get('https://graph.facebook.com/oauth/access_token', verify=False, params=params)
token = parse_qs(r.content).get('access_token')
return token
@app.route('/', methods=['GET', 'POST'])
def index():
# print get_home()
access_token = get_token()
channel_url = url_for('get_channel', _external=True)
channel_url = channel_url.replace('http:', '').replace('https:', '')
if access_token:
me = fb_call('me', args={'access_token': access_token})
fb_app = fb_call(FB_APP_ID, args={'access_token': access_token})
likes = fb_call('me/likes',
args={'access_token': access_token, 'limit': 4})
friends = fb_call('me/friends',
args={'access_token': access_token, 'limit': 4})
photos = fb_call('me/photos',
args={'access_token': access_token, 'limit': 16})
redir = get_home() + 'close/'
POST_TO_WALL = ("https://www.facebook.com/dialog/feed?redirect_uri=%s&"
"display=popup&app_id=%s" % (redir, FB_APP_ID))
app_friends = fql(
"SELECT uid, name, is_app_user, pic_square "
"FROM user "
"WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND "
" is_app_user = 1", access_token)
SEND_TO = ('https://www.facebook.com/dialog/send?'
'redirect_uri=%s&display=popup&app_id=%s&link=%s'
% (redir, FB_APP_ID, get_home()))
url = request.url
return render_template(
'index.html', app_id=FB_APP_ID, token=access_token, likes=likes,
friends=friends, photos=photos, app_friends=app_friends, app=fb_app,
me=me, POST_TO_WALL=POST_TO_WALL, SEND_TO=SEND_TO, url=url,
channel_url=channel_url, name=FB_APP_NAME)
else:
return render_template('login.html', app_id=FB_APP_ID, token=access_token, url=request.url, channel_url=channel_url, name=FB_APP_NAME)
@app.route('/channel.html', methods=['GET', 'POST'])
def get_channel():
return render_template('channel.html')
@app.route('/close/', methods=['GET', 'POST'])
def close():
return render_template('close.html')
@app.route('/about/', methods=['GET'])
def about():
return render_template('core/about.html')
@app.route('/graph/', methods=['GET'])
def graph():
return render_template('core/graph.html')
@app.route('/graph/details/', methods=['GET'])
def graph_details():
return render_template('core/details.html')
@app.route('/_get_user_posts/', methods=['GET'])
def user_posts():
data = get_user_posts()
return jsonify(children=data)
@app.route('/data/', methods=['GET'])
def test_data():
data = []
categories = ['photos', 'likes', 'checkins', 'posts', 'videos']
for c in categories:
customer = {"display_name": c, "likes": random.randint(10, 25), "comments": random.randint(5, 25)}
data.append(customer)
return jsonify(children=data)
@app.route('/data-details/', methods=['GET'])
def test_detail_data():
data = []
for i in xrange(5):
category = {"category_name": "category_{0}".format(i), "value": random.randint(0, 100)}
data.append(category)
return jsonify(children=data)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
if app.config.get('FB_APP_ID') and app.config.get('FB_APP_SECRET'):
app.run(host='0.0.0.0', port=port)
else:
print 'Cannot start application without Facebook App Id and Secret set'