I want to write a script that logs an user into Facebook and initialize oauth dialog to get the access_token(I don't want to log in into a website using facebook account!). I don't want to use facebook-sdk,pyfb etc.
This is what I've tried:
import sys, urllib2,json,urlparse,webbrowser, os, cookielib, re
class Facebook():
def __init__(self, email, password):
self.email = email
self.password = password
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('Referer', 'http://login.facebook.com/login.php'),
('Content-Type', 'application/x-www-form-urlencoded'),
('User-Agent', 'Mozilla/8.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) \
Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)')]
self.opener = opener
def login(self):
url = 'https://login.facebook.com/login.php?login_attempt=1'
data ="locale=en_US&non_com_login=&email="+self.email+"&pass="+self.password+"&lsd=20TOl"
usock = self.opener.open('http://www.facebook.com')
usock = self.opener.open(url, data)
if "Logout" in usock.read():
print "Logged in."
else:
print "failed login"
f = Facebook("email", "pass")
f.login()
#############
#oauth dialog
APP_ID="583086091722833"
APP_SECRET='e781b9f386c2d1767cc2aad0486bd51e'
REDIRECT_URL='http://127.0.0.1'
SCOPE='user_photos,email,user_birthday,user_online_presence,offline_access'
url = "http://www.facebook.com/dialog/oauth/?client_id="+APP_ID+"&redirect_uri="+REDIRECT_URL+"&scope="+SCOPE+"&response_type=code"
#get code parameter from oauth dialog
#it will work only if the user had already granted the required permissions
req = urllib2.Request(url)
response = urllib2.urlopen(req)
print response.geturl()
This script prints out:
Logged in
and the last line prints:
https://www.facebook.com/login.php?skip_api_login=1&api_key=583086091722833&signed_next=1&next=http://www.facebook.com/dialog/oauth?redirect_uri=http%3A%2F%2F127.0.0.1&scope=user_photos%2Cemail%2Cuser_birthday%2Cuser_online_presence%2Coffline_access&response_type=code&client_id=583086091722833&ret=login&cancel_uri=http://127.0.0.1/?error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied#_=_&display=page
but what I expect is something like this: http://127.0.0.1?code= some alphanumerical code.
If I access the URL stored in "url" variable from the browser, it will redirect me to what I'm expecting. The same thing happens if I access from browser the output from last line of code. So, why I don't have in the "response" variable the final redirect URL (that with http://127.0.0.1?code=) from "url" page?