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
|
from forum.conf import settings as forum_settings
from time import time
from datetime import datetime
from urllib import urlopen, urlencode
try:
from json import load as load_json
except:
from pjson import fread as load_json
from models import FBAssociation
import hashlib
import logging
REST_SERVER = 'http://api.facebook.com/restserver.php'
def generate_sig(values):
keys = []
for key in sorted(values.keys()):
keys.append(key)
signature = ''.join(['%s=%s' % (key, values[key]) for key in keys]) + forum_settings.FB_SECRET
return hashlib.md5(signature).hexdigest()
def check_cookies_signature(cookies):
API_KEY = forum_settings.FB_API_KEY
values = {}
for key in cookies.keys():
if (key.startswith(API_KEY + '_')):
values[key.replace(API_KEY + '_', '')] = cookies[key]
return generate_sig(values) == cookies[API_KEY]
def get_user_data(cookies):
request_data = {
'method': 'Users.getInfo',
'api_key': forum_settings.FB_API_KEY,
'call_id': time(),
'v': '1.0',
'uids': cookies[forum_settings.FB_API_KEY + '_user'],
'fields': 'name,first_name,last_name',
'format': 'json',
}
request_data['sig'] = generate_sig(request_data)
fb_response = urlopen(REST_SERVER, urlencode(request_data))
#print(fb_response)
return load_json(fb_response)[0]
def delete_cookies(response):
API_KEY = forum_settings.FB_API_KEY
response.delete_cookie(API_KEY + '_user')
response.delete_cookie(API_KEY + '_session_key')
response.delete_cookie(API_KEY + '_expires')
response.delete_cookie(API_KEY + '_ss')
response.delete_cookie(API_KEY)
response.delete_cookie('fbsetting_' + API_KEY)
def check_session_expiry(cookies):
return datetime.fromtimestamp(float(cookies[forum_settings.FB_API_KEY+'_expires'])) > datetime.now()
STATES = {
'FIRSTTIMER': 1,
'SESSIONEXPIRED': 2,
'RETURNINGUSER': 3,
'INVALIDSTATE': 4,
}
def get_user_state(request):
API_KEY = forum_settings.FB_API_KEY
logging.debug('')
if API_KEY in request.COOKIES:
logging.debug('FB API key is in request cookies')
if check_cookies_signature(request.COOKIES):
logging.debug('FB cookie signature is fine')
if check_session_expiry(request.COOKIES):
logging.debug('FB session is not expired')
try:
uassoc = FBAssociation.objects.get(fbuid=request.COOKIES[API_KEY + '_user'])
logging.debug('found existing FB user association')
return (STATES['RETURNINGUSER'], uassoc.user)
except:
logging.debug('dont have FB association for this user')
return (STATES['FIRSTTIMER'], get_user_data(request.COOKIES))
else:
logging.debug('FB session expired')
return (STATES['SESSIONEXPIRED'], None)
logging.debug('FB state is INVALID')
return (STATES['INVALIDSTATE'], None)
|