Autentimise märkmed: facebook ja google

Allikas: Lambda

Short tutorial: logging in with Facebook and Google+

We assume you already have FB and Google+ accounts. If not, create them.

Next you have to create FB and Google "apps" which do not really do anything except

  • give you an ID to use in your code
  • give a page name shown to a user logging in

Like this (just a generic example, specific guides will follow later):

   name: itv-kontrolltoo
   url: http://dijkstra.cs.ttu.ee/~tammet/tst.html
   App ID: 	1428005727423768
   App Secret: 	28b...5f7(reset) 

On Facebook

 App ID: 	XXXXXX..
 App Secret: 	XXXXX..
 values
 
  • Now the "Facebook login" product can be added, either manually or in the "Quickstart" mode
  • The app dashboard can later be reached through "https://developers.facebook.com/apps" again.

Google

  • The relevant docs start here: https://developers.google.com/identity/sign-in/web/
  • Include the given code snippet in your html
  • Hit "Get started" and read about how to create a project and eventually get a sign-in client id
  • Note: when asked for origin URI, give the host name of your site (http://www.blah.com, not http://www.blah.com/myhomework/mylogintest.html)
  • replace the client id in the sample code

When logging in for the first time, Google will ask your permission to send details to the app you created. Accept (or don't, your choice)

Later, https://plus.google.com/apps lists apps that you have given permissions to

Code examples

Proceed at your own risk. There is a lot of code below that may or may not be useful or up to date.

Some friendlier documentation pages:

https://developers.facebook.com/docs/facebook-login/


At beginning of page


<body>
<div id="fb-root"></div>
<script>
// facebook stuff
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '${fb_id}', //'1428005727423768', // App ID
      channelUrl : '${fb_channelurl}', //'http://dijkstra.cs.ttu.ee/~tammet/channel.html', // Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });
    // Check if the current user is logged in and has authorized the app
    // FB.getLoginStatus(checkFBLoginStatus);             
  };
 
// google stuff
window.___gcfg = {
  lang: 'et', // 'en-US'
  parsetags: 'auto'
};
 
function gplus_render() {
  if (login_service=="google" || login_service=="facebook" || login_service=="password") return false;
  gapi.signin.render('google_signin', {
    'callback': 'google_signinCallback',
    'clientid': '${google_id}', //'569466798629.apps.googleusercontent.com',
    'cookiepolicy': 'single_host_origin',
    'requestvisibleactions': 'http://schemas.google.com/AddActivity',
    'scope': "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
  });
}   
//'scope': "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
</script>

Then buttons a la


<div class="btn btn-flat btn-fb" style="margin-top: 0px; 
            width: 90px; margin-left: 5px; padding-right: 0px; white-space:nowrap;" 
            onclick="authUser('facebook');" 
            title="Facebook login">            
<div style="width:18px; display: inline-block;"></div>Facebook</div>    


<div class="btn btn-flat btn-google" id="google_signin" style="margin-top: 0px; 
        width: 92px; margin-left: 5px; padding-right: 0px; white-space:nowrap;"            
        title="Google+ login">            
<div style="width:18px; display: inline-block;"></div>Google</div>  

<!--
    <span id="signinButton">
      <span
        class="g-signin"
        data-callback="google_signinCallback"
        data-clientid="569466798629.apps.googleusercontent.com"
        data-cookiepolicy="single_host_origin"
        data-requestvisibleactions="http://schemas.google.com/AddActivity"
        data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
      </span>
    </span>
-->

At end of page standard library loaders


<!-- at end scripts -->

<script>

// facebook stuff

(function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src = "//connect.facebook.net/en_US/all.js";
   ref.parentNode.insertBefore(js, ref);
 }(document));  
 
// google stuff

if (!(login_service=="google" || login_service=="facebook" || login_service=="password")) {
(function() {
   var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
   po.src = 'https://apis.google.com/js/client:plusone.js?onload=gplus_render';
   //po.src = 'https://apis.google.com/js/plusone.js?';
   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
 })();
} else {
(function() {
   var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
   //po.src = 'https://apis.google.com/js/client:plusone.js?onload=gplus_render';
   po.src = 'https://apis.google.com/js/plusone.js?';
   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
 })();
}

// google analytics

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-44783009-1', 'tlu.ee');
  ga('send', 'pageview');

</script>

Javascript functions


// ============== facebook stuff ============


// Login in the current user via Facebook and ask for email permission
function authUser(service) {
  //alert('authUser called');
  FB.login(checkFBLoginStatus, {scope:'email'});
}
  
// Check the result of the user status and display login button if necessary
function checkFBLoginStatus(response) {
  //alert('checkFBLoginStatus called');
  if(response && response.status == 'connected') {
    //console.log('User is authorized by js');  
    //console.log(response);
    //ask_fb_userinfo(response);
    //testAPI(response);
    submit_fb_access(response);
    //document.getElementById('fb_login_button').style.display = 'none';    
  } else {
    //console.log('User is not authorized');    
    //document.getElementById('loginButton').style.display = 'block';
  }
}  

function ask_fb_userinfo(response) {
  //console.log('Welcome from ask_fb_userinfo!');
  FB.api('/me', function(meresponse) {
    submit_fb_access(meresponse);  
  });
  /*
  console.log('status: ' + response.status);
  console.log('name: ' + response.name);
  console.log('userID: ' + response.authResponse.userID);    
  console.log('accessToken: ' + response.authResponse.accessToken);
  $('#loginform_op').val("fb_login")
  $('#loginform').submit()
  */
  
}

function submit_fb_access(response) {
  /*
  alert('submit_fb_access called');
  console.log('Welcome from submit_fb_access!');
  console.log('accessToken: '+response.authResponse.accessToken);
  console.log('response: ' + response);
  //console.log('name: ' + response.name);
  //console.log('id: ' + response.id);  
  console.log('userID: ' + response.authResponse.userID);    
  */
  if (response.authResponse.accessToken && response.authResponse.userID) {
    //alert('submit_fb_access called successfully'); 
    $('#loginform_op').val("fb_login")
    $('#loginform_auth_token').val(response.authResponse.accessToken);
    $('#loginform_uid').val(response.authResponse.userID);
    $('#loginform').submit();
  }
}


function testAPI(response) {
  /*
  console.log('Welcome!');
  console.log('status: ' + response.status);
  console.log('userID: ' + response.authResponse.userID);    
  console.log('accessToken: ' + response.authResponse.accessToken);
  console.log('Fetching your information.... ');
  FB.api('/me', function(meresponse) {
    console.log('Good to see you, ' + meresponse.name + '.');
    console.log(meresponse);    
  });
  */
}



// ============== google stuff ============

var my_access_token;
var my_user_id;


function google_signinCallback(authResult) {
  //console.log("in google_signinCallback with login_service"+login_service);
  if (login_service=="google" || login_service=="facebook" || login_service=="password") return false;
  if (authResult['access_token'] && !authResult['error']) {
    // Successfully authorized    
    /*
    console.log('Authorized ok! ');
    console.log('authResult[access_token]: ' + authResult['access_token']);
    console.log('authResult[id_token]: ' + authResult['id_token']);
    console.log('authResult[email]: ' + authResult['email']);
    console.log('authResult[error]: ' + authResult['error']);    
    */ 
    my_user_id=authResult['id_token'];
    my_access_token=authResult['access_token'];
    getEmail(my_access_token);    
    // makeGoogleApiCall(my_access_token); // alternative to get social data
    return false;    
  } else if (authResult['error']) {
    // Possible error codes:
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatially log in the user
    //console.log('There was an error: ' + authResult['error']);
  }
}

function getEmail(access_token){
  // email plus username plus id
  // Load the oauth2 libraries to enable the userinfo methods.
  //console.log("getEmail() called");
  gapi.client.load('oauth2', 'v2', function() {
    gapi.client.oauth2.userinfo.get().execute(function(resp) {
      /*
      console.log("resp: "+resp);
      console.log("resp.email: "+resp.email);      
      console.log("displayName: "+resp.name);
      console.log("id: "+resp.id);
      */
      $('#loginform_op').val("google_login");
      $('#loginform_auth_token').val(access_token);
      $('#loginform_uid').val(resp.id);
      if (resp.email) $('#loginform_email').val(resp.email);
      if (resp.name) $('#loginform_screenname').val(resp.name);
      $('#loginform_uid').val(resp.id);
      $('#loginform').submit();
      
      return false;
    });
  });
}

function makeGoogleApiCall(access_token) {
  // no email in this way
  gapi.client.load('plus', 'v1', function() {
    var request = gapi.client.plus.people.get({
      'userId': 'me'
    });
    request.execute(function(resp) {
      /*
      console.log("resp: "+resp);
      console.log("displayName: "+resp.displayName);
      console.log("id: "+resp.id);
      */
      $('#loginform_op').val("google_login");
      $('#loginform_auth_token').val(access_token);
      if (resp.displayName) $('#loginform_screenname').val(resp.displayName);
      $('#loginform_uid').val(resp.id);
      $('#loginform').submit();
      
      return false;
    });
  });
}



function getData(){
  //console.log("getData called");
  $.ajax({
    type: 'GET',
    url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+my_access_token,
    async: true,
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(p) {
      // Do something now that user is disconnected
      // The response is always undefined.
      /*
      console.log("success: "+p);
      console.log("success id: "+p.id);
      console.log("success data: "+p.data);
      console.log("success error: "+p.error);
      */
    },
    error: function(e) {
      // Handle the error
      //console.log("error: "+e);
      // You could point users to manually disconnect if unsuccessful
      // https://plus.google.com/apps
    }
  });
}


function toggleElement(id) {
  var el = document.getElementById(id);
  if (el.getAttribute('class') == 'hide') {
    el.setAttribute('class', 'show');
  } else {
    el.setAttribute('class', 'hide');
  }
}


function gplusShare(topflag) {
  var gurl="https://plus.google.com/share?url=";  
  link=top_link;
  gurl+=encodeURIComponent(link);
  //debug(gurl);
  window.open(gurl,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
}

Server side stuff



def handle_fb_login(req):  
  """
  """  
  import facebook   
  #print('Content-type: text/html\n\nhandle_fb_login\n\n')
  #print str(req.incookies)
  #if req.inparams.has_key('auth_token') and req.inparams['auth_token'].value:
  #  print str('auth_token: '+req.inparams['auth_token'].value)
  #print str(req.incookies)
  #sys.exit(0)
  
  #if not req.incookies:
  #  handle_home(req)
  #  return    
  #cookiedict={}
  """
  for key in req.incookies:
    cookiedict[key]=req.incookies[key].value    
  user = facebook.get_user_from_cookie(cookiedict, "1428005727423768", "28bf97eed94158b0e3cbd6d9eec545f7")
  """
  if req.inparams.has_key('uid') and req.inparams['uid'].value and \
     req.inparams.has_key('auth_token') and req.inparams['auth_token'].value: #user and user["uid"]:
    #uid=user["uid"]
    #graph = facebook.GraphAPI(user["access_token"])  
    try:    
      uid=req.inparams['uid'].value
      graph = facebook.GraphAPI(req.inparams['auth_token'].value)     
      
      profile = graph.get_object("me")
      username=profile["username"] # Tanel.Tammet
      name=profile["name"] # Tanel Tammet
      email=profile["email"] # Tanel.Tammet@gmail.com
      req.login_service="facebook"
    except:  
      req.warning="Sisselogimisel tekkis tõrge: vajadusel proovi hiljem uuesti!"       
      handle_home(req)
      return 
    #friends = graph.get_connections("me", "friends")  
    """    
    print('Content-type: text/html\n\nhandle_fb_login\n\n')
    print "uid: "+str(uid)+"<p>"
    print "username: "+str(username)+"<p>"
    print "name: "+str(name)+"<p>"
    print "email: "+str(email)+"<p>"    
    print "graph: "+str(graph)+"<p>"
    print "profile: "+str(profile)+"<p>"
    #print "friends: "+str(friends)+"<p>"
    sys.exit(0)
    """
    tmp=handle_social_login_phase(req,"facebook",uid,username,name,email,None)
    if not tmp:
      handle_home(req)
    else:
      ctrl_main_authenticated(req)      
    return
  else:          
    req.warning="Sisselogimisel tekkis tõrge: vajadusel proovi hiljem uuesti!"       
    handle_home(req)
    return 
    
  

def handle_google_login(req):  
  """
  """    
  import urllib2
  #print('Content-type: text/html\n\nhandle_google_login\n\n')
  #print str(req.incookies)
  #if req.inparams.has_key('auth_token') and req.inparams['auth_token'].value:
  #  print str('<br>login_service: '+str(req.login_service))
  #  print str('<br>auth_token: '+req.inparams['auth_token'].value)
  #print str(req.incookies)
  #sys.exit(0)
 
  if req.inparams.has_key('uid') and req.inparams['uid'].value and \
     req.inparams.has_key('auth_token') and req.inparams['auth_token'].value: #user and user["uid"]:
    #uid=user["uid"]
    #graph = facebook.GraphAPI(user["access_token"])   
    uid=req.inparams['uid'].value
    token=req.inparams['auth_token'].value
    name=None
    email=None
    user_id=None
    if req.inparams.has_key("screenname") and req.inparams["screenname"].value: 
      name=req.inparams["screenname"].value    
    if req.inparams.has_key("email") and req.inparams["email"].value: 
      email=req.inparams["email"].value
      if not name: name=email      
    gurl="https://www.googleapis.com/oauth2/v1/tokeninfo?access_token="+token
    try:
      ureq = urllib2.Request(gurl)
      uresp=urllib2.urlopen(ureq)
      jsonstr = uresp.read()    
      data=json.loads(jsonstr)
      new_user_id=data["user_id"]
      audience=data["audience"]  #"audience":"8819981768.apps.googleusercontent.com"
    except:
      req.warning="Sisselogimisel tekkis tõrge: vajadusel proovi hiljem uuesti!"       
      handle_home(req)
      return
    email=None        
    user_id=data["user_id"]
    if audience!=req.conf["google_id"] or user_id!=new_user_id: # "569466798629.apps.googleusercontent.com" 
      req.warning="Sisselogimisel tekkis tõrge: vajadusel proovi hiljem uuesti!"       
      handle_home(req)
      return      
    #print "<br>name: "+str(name)+"<br>email: "+str(email)
    #print "<br>user_id: "+str(user_id)+"<br>new_user_id: "+str(new_user_id)+"<br>audience: "+str(audience)
    req.login_service="google"
    tmp=handle_social_login_phase(req,"google",new_user_id,new_user_id,name,email,token)
    if not tmp:
      handle_home(req)
    else:
      ctrl_main_authenticated(req)      
    return
  else:
    req.warning="Sisselogimisel tekkis tõrge: vajadusel proovi hiljem uuesti!"
    handle_home(req)
    return    
  #sys.exit(0)  
  

def handle_social_login_phase(req,service,uid,username,userfullname,email,token):  
  # ----- check if user already in database and add if not ----
  try:
    data=db_get_socialuser_row(req,service,uid)
    if not data:
      id=store_socialuser(req,service,uid,service+":"+username,userfullname,email)
    elif data["status"]!='A':
      return False
    else:
      id=data["id"]
    req.username=service+":"+username
    req.userfullname=userfullname  
    req.userlevel=3  
    # -- create cookie ----
    import hashlib
    dgst = hashlib.sha1(str(time.time())+str(os.urandom(8))+str(uid)).hexdigest()
    req.outcookies = Cookie.SimpleCookie()                  
    req.outcookies["ctf_sid"] = dgst # data[3]+' '+data[4]
    #req.outcookies["ctf_sid"]["max-age"] = 3600	# Time to keep, in seconds     
    req.outcookies["ctf_sid"]["expires"] = 3*3600	# Time to keep, in seconds
    req.outcookies["ctf_sid"]["version"] = 1        
    # ----- create session -----
    create_login_session(req,dgst,req.username,token)  
    req.op='loginpassed'  
    logging.info("login ok for "+req.username)  
    return True 
  except:
    req.warning="Sisselogimisel tekkis tõrge: vajadusel proovi hiljem uuesti!"       
    return False


def handle_logout(req):  
  """  
  """
  import urllib2
  if req.sid and req.username:
    try:
      logout_sessions(req,req.sid,req.username)  
    except:
      req.warning="Väljalogimisel tekkis tõrge: vajadusel proovi hiljem uuesti või tühjenda oma brauser cookie-dest!" 
      req.op="home"
      dispatch(req)  
      return      
  if req.login_service=="google":
    if req.token:    
      gurl="https://accounts.google.com/o/oauth2/revoke?token="+req.token
      try:
        ureq = urllib2.Request(gurl)
        uresp=urllib2.urlopen(ureq)
        jsonstr = uresp.read()          
      except:
        req.warning="Google kaudu väljalogimiseks mine palun <a href='https://plus.google.com/apps'>sellele lehele</a>!" 
        req.op="home"
        dispatch(req)  
        return        
    else:    
      req.warning="Google kaudu väljalogimiseks mine palun <a href='https://plus.google.com/apps'>sellele lehele</a>!" 
      req.op="home"
      dispatch(req)  
      return
  req.username=""
  req.login_service=None
  req.op="home"
  dispatch(req)  
  return
  


facebook.py


#!/usr/bin/env python
#
# Copyright 2010 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""Python client library for the Facebook Platform.

This client library is designed to support the Graph API and the
official Facebook JavaScript SDK, which is the canonical way to
implement Facebook authentication. Read more about the Graph API at
http://developers.facebook.com/docs/api. You can download the Facebook
JavaScript SDK at http://github.com/facebook/connect-js/.

If your application is using Google AppEngine's webapp framework, your
usage of this module might look like this:

user = facebook.get_user_from_cookie(self.request.cookies, key, secret)
if user:
    graph = facebook.GraphAPI(user["access_token"])
    profile = graph.get_object("me")
    friends = graph.get_connections("me", "friends")

"""

import cgi
import time
import urllib
import urllib2
import httplib
import hashlib
import hmac
import base64
import logging
import socket

# Find a JSON parser
try:
    import simplejson as json
except ImportError:
    try:
        from django.utils import simplejson as json
    except ImportError:
        import json
_parse_json = json.loads

# Find a query string parser
try:
    from urlparse import parse_qs
except ImportError:
    from cgi import parse_qs


class GraphAPI(object):
    """A client for the Facebook Graph API.

    See http://developers.facebook.com/docs/api for complete
    documentation for the API.

    The Graph API is made up of the objects in Facebook (e.g., people,
    pages, events, photos) and the connections between them (e.g.,
    friends, photo tags, and event RSVPs). This client provides access
    to those primitive types in a generic way. For example, given an
    OAuth access token, this will fetch the profile of the active user
    and the list of the user's friends:

       graph = facebook.GraphAPI(access_token)
       user = graph.get_object("me")
       friends = graph.get_connections(user["id"], "friends")

    You can see a list of all of the objects and connections supported
    by the API at http://developers.facebook.com/docs/reference/api/.

    You can obtain an access token via OAuth or by using the Facebook
    JavaScript SDK. See
    http://developers.facebook.com/docs/authentication/ for details.

    If you are using the JavaScript SDK, you can use the
    get_user_from_cookie() method below to get the OAuth access token
    for the active user from the cookie saved by the SDK.

    """
    def __init__(self, access_token=None, timeout=None):
        self.access_token = access_token
        self.timeout = timeout

    def get_object(self, id, **args):
        """Fetchs the given object from the graph."""
        return self.request(id, args)

    def get_objects(self, ids, **args):
        """Fetchs all of the given object from the graph.

        We return a map from ID to object. If any of the IDs are
        invalid, we raise an exception.
        """
        args["ids"] = ",".join(ids)
        return self.request("", args)

    def get_connections(self, id, connection_name, **args):
        """Fetchs the connections for given object."""
        return self.request(id + "/" + connection_name, args)

    def put_object(self, parent_object, connection_name, **data):
        """Writes the given object to the graph, connected to the given parent.

        For example,

            graph.put_object("me", "feed", message="Hello, world")

        writes "Hello, world" to the active user's wall. Likewise, this
        will comment on a the first post of the active user's feed:

            feed = graph.get_connections("me", "feed")
            post = feed["data"][0]
            graph.put_object(post["id"], "comments", message="First!")

        See http://developers.facebook.com/docs/api#publishing for all
        of the supported writeable objects.

        Certain write operations require extended permissions. For
        example, publishing to a user's feed requires the
        "publish_actions" permission. See
        http://developers.facebook.com/docs/publishing/ for details
        about publishing permissions.

        """
        assert self.access_token, "Write operations require an access token"
        return self.request(parent_object + "/" + connection_name,
                            post_args=data)

    def put_wall_post(self, message, attachment={}, profile_id="me"):
        """Writes a wall post to the given profile's wall.

        We default to writing to the authenticated user's wall if no
        profile_id is specified.

        attachment adds a structured attachment to the status message
        being posted to the Wall. It should be a dictionary of the form:

            {"name": "Link name"
             "link": "http://www.example.com/",
             "caption": "{*actor*} posted a new review",
             "description": "This is a longer description of the attachment",
             "picture": "http://www.example.com/thumbnail.jpg"}

        """
        return self.put_object(profile_id, "feed", message=message,
                               **attachment)

    def put_comment(self, object_id, message):
        """Writes the given comment on the given post."""
        return self.put_object(object_id, "comments", message=message)

    def put_like(self, object_id):
        """Likes the given post."""
        return self.put_object(object_id, "likes")

    def delete_object(self, id):
        """Deletes the object with the given ID from the graph."""
        self.request(id, post_args={"method": "delete"})

    def delete_request(self, user_id, request_id):
        """Deletes the Request with the given ID for the given user."""
        conn = httplib.HTTPSConnection('graph.facebook.com')

        url = '/%s_%s?%s' % (
            request_id,
            user_id,
            urllib.urlencode({'access_token': self.access_token}),
        )
        conn.request('DELETE', url)
        response = conn.getresponse()
        data = response.read()

        response = _parse_json(data)
        # Raise an error if we got one, but don't not if Facebook just
        # gave us a Bool value
        if (response and isinstance(response, dict) and response.get("error")):
            raise GraphAPIError(response)

        conn.close()

    def put_photo(self, image, message=None, album_id=None, **kwargs):
        """Uploads an image using multipart/form-data.

        image=File like object for the image
        message=Caption for your image
        album_id=None posts to /me/photos which uses or creates and uses
        an album for your application.

        """
        object_id = album_id or "me"
        #it would have been nice to reuse self.request;
        #but multipart is messy in urllib
        post_args = {
            'access_token': self.access_token,
            'source': image,
            'message': message,
        }
        post_args.update(kwargs)
        content_type, body = self._encode_multipart_form(post_args)
        req = urllib2.Request(("https://graph.facebook.com/%s/photos" %
                               object_id),
                              data=body)
        req.add_header('Content-Type', content_type)
        try:
            data = urllib2.urlopen(req).read()
        #For Python 3 use this:
        #except urllib2.HTTPError as e:
        except urllib2.HTTPError, e:
            data = e.read()  # Facebook sends OAuth errors as 400, and urllib2
                             # throws an exception, we want a GraphAPIError
        try:
            response = _parse_json(data)
            # Raise an error if we got one, but don't not if Facebook just
            # gave us a Bool value
            if (response and isinstance(response, dict) and
                    response.get("error")):
                raise GraphAPIError(response)
        except ValueError:
            response = data

        return response

    # based on: http://code.activestate.com/recipes/146306/
    def _encode_multipart_form(self, fields):
        """Encode files as 'multipart/form-data'.

        Fields are a dict of form name-> value. For files, value should
        be a file object. Other file-like objects might work and a fake
        name will be chosen.

        Returns (content_type, body) ready for httplib.HTTP instance.

        """
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        L = []
        for (key, value) in fields.items():
            logging.debug("Encoding %s, (%s)%s" % (key, type(value), value))
            if not value:
                continue
            L.append('--' + BOUNDARY)
            if hasattr(value, 'read') and callable(value.read):
                filename = getattr(value, 'name', '%s.jpg' % key)
                L.append(('Content-Disposition: form-data;'
                          'name="%s";'
                          'filename="%s"') % (key, filename))
                L.append('Content-Type: image/jpeg')
                value = value.read()
                logging.debug(type(value))
            else:
                L.append('Content-Disposition: form-data; name="%s"' % key)
            L.append('')
            if isinstance(value, unicode):
                logging.debug("Convert to ascii")
                value = value.encode('ascii')
            L.append(value)
        L.append('--' + BOUNDARY + '--')
        L.append('')
        body = CRLF.join(L)
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        return content_type, body

    def request(self, path, args=None, post_args=None):
        """Fetches the given path in the Graph API.

        We translate args to a valid query string. If post_args is
        given, we send a POST request to the given path with the given
        arguments.

        """
        args = args or {}

        if self.access_token:
            if post_args is not None:
                post_args["access_token"] = self.access_token
            else:
                args["access_token"] = self.access_token
        post_data = None if post_args is None else urllib.urlencode(post_args)
        try:
            file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" +
                                   urllib.urlencode(args),
                                   post_data, timeout=self.timeout)
        except urllib2.HTTPError, e:
            response = _parse_json(e.read())
            raise GraphAPIError(response)
        except TypeError:
            # Timeout support for Python <2.6
            if self.timeout:
                socket.setdefaulttimeout(self.timeout)
            file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" +
                                   urllib.urlencode(args), post_data)
        try:
            fileInfo = file.info()
            if fileInfo.maintype == 'text':
                response = _parse_json(file.read())
            elif fileInfo.maintype == 'image':
                mimetype = fileInfo['content-type']
                response = {
                    "data": file.read(),
                    "mime-type": mimetype,
                    "url": file.url,
                }
            else:
                raise GraphAPIError('Maintype was not text or image')
        finally:
            file.close()
        if response and isinstance(response, dict) and response.get("error"):
            raise GraphAPIError(response["error"]["type"],
                                response["error"]["message"])
        return response

    def fql(self, query, args=None, post_args=None):
        """FQL query.

        Example query: "SELECT affiliations FROM user WHERE uid = me()"

        """
        args = args or {}
        if self.access_token:
            if post_args is not None:
                post_args["access_token"] = self.access_token
            else:
                args["access_token"] = self.access_token
        post_data = None if post_args is None else urllib.urlencode(post_args)

        args["q"] = query
        args["format"] = "json"

        try:
            file = urllib2.urlopen("https://graph.facebook.com/fql?" +
                                   urllib.urlencode(args),
                                   post_data, timeout=self.timeout)
        except TypeError:
            # Timeout support for Python <2.6
            if self.timeout:
                socket.setdefaulttimeout(self.timeout)
            file = urllib2.urlopen("https://graph.facebook.com/fql?" +
                                   urllib.urlencode(args),
                                   post_data)

        try:
            content = file.read()
            response = _parse_json(content)
            #Return a list if success, return a dictionary if failed
            if type(response) is dict and "error_code" in response:
                raise GraphAPIError(response)
        except Exception, e:
            raise e
        finally:
            file.close()

        return response

    def extend_access_token(self, app_id, app_secret):
        """
        Extends the expiration time of a valid OAuth access token. See
        <https://developers.facebook.com/roadmap/offline-access-removal/
        #extend_token>

        """
        args = {
            "client_id": app_id,
            "client_secret": app_secret,
            "grant_type": "fb_exchange_token",
            "fb_exchange_token": self.access_token,
        }
        response = urllib.urlopen("https://graph.facebook.com/oauth/"
                                  "access_token?" +
                                  urllib.urlencode(args)).read()
        query_str = parse_qs(response)
        if "access_token" in query_str:
            result = {"access_token": query_str["access_token"][0]}
            if "expires" in query_str:
                result["expires"] = query_str["expires"][0]
            return result
        else:
            response = json.loads(response)
            raise GraphAPIError(response)


class GraphAPIError(Exception):
    def __init__(self, result):
        #Exception.__init__(self, message)
        #self.type = type
        self.result = result
        try:
            self.type = result["error_code"]
        except:
            self.type = ""

        # OAuth 2.0 Draft 10
        try:
            self.message = result["error_description"]
        except:
            # OAuth 2.0 Draft 00
            try:
                self.message = result["error"]["message"]
            except:
                # REST server style
                try:
                    self.message = result["error_msg"]
                except:
                    self.message = result

        Exception.__init__(self, self.message)


def get_user_from_cookie(cookies, app_id, app_secret):
    """Parses the cookie set by the official Facebook JavaScript SDK.

    cookies should be a dictionary-like object mapping cookie names to
    cookie values.

    If the user is logged in via Facebook, we return a dictionary with
    the keys "uid" and "access_token". The former is the user's
    Facebook ID, and the latter can be used to make authenticated
    requests to the Graph API. If the user is not logged in, we
    return None.

    Download the official Facebook JavaScript SDK at
    http://github.com/facebook/connect-js/. Read more about Facebook
    authentication at
    http://developers.facebook.com/docs/authentication/.

    """
    cookie = cookies.get("fbsr_" + app_id, "")
    if not cookie:
        return None
    parsed_request = parse_signed_request(cookie, app_secret)
    if not parsed_request:
        return None
    try:
        result = get_access_token_from_code(parsed_request["code"], "",
                                            app_id, app_secret)
    except GraphAPIError:
        return None
    result["uid"] = parsed_request["user_id"]
    return result


def parse_signed_request(signed_request, app_secret):
    """ Return dictionary with signed request data.

    We return a dictionary containing the information in the
    signed_request. This includes a user_id if the user has authorised
    your application, as well as any information requested.

    If the signed_request is malformed or corrupted, False is returned.

    """
    try:
        encoded_sig, payload = map(str, signed_request.split('.', 1))

        sig = base64.urlsafe_b64decode(encoded_sig + "=" *
                                       ((4 - len(encoded_sig) % 4) % 4))
        data = base64.urlsafe_b64decode(payload + "=" *
                                        ((4 - len(payload) % 4) % 4))
    except IndexError:
        # Signed request was malformed.
        return False
    except TypeError:
        # Signed request had a corrupted payload.
        return False

    data = _parse_json(data)
    if data.get('algorithm', '').upper() != 'HMAC-SHA256':
        return False

    # HMAC can only handle ascii (byte) strings
    # http://bugs.python.org/issue5285
    app_secret = app_secret.encode('ascii')
    payload = payload.encode('ascii')

    expected_sig = hmac.new(app_secret,
                            msg=payload,
                            digestmod=hashlib.sha256).digest()
    if sig != expected_sig:
        return False

    return data


def auth_url(app_id, canvas_url, perms=None, **kwargs):
    url = "https://www.facebook.com/dialog/oauth?"
    kvps = {'client_id': app_id, 'redirect_uri': canvas_url}
    if perms:
        kvps['scope'] = ",".join(perms)
    kvps.update(kwargs)
    return url + urllib.urlencode(kvps)

def get_access_token_from_code(code, redirect_uri, app_id, app_secret):
    """Get an access token from the "code" returned from an OAuth dialog.

    Returns a dict containing the user-specific access token and its
    expiration date (if applicable).

    """
    args = {
        "code": code,
        "redirect_uri": redirect_uri,
        "client_id": app_id,
        "client_secret": app_secret,
    }
    # We would use GraphAPI.request() here, except for that the fact
    # that the response is a key-value pair, and not JSON.
    response = urllib.urlopen("https://graph.facebook.com/oauth/access_token" +
                              "?" + urllib.urlencode(args)).read()
    query_str = parse_qs(response)
    if "access_token" in query_str:
        result = {"access_token": query_str["access_token"][0]}
        if "expires" in query_str:
            result["expires"] = query_str["expires"][0]
        return result
    else:
        response = json.loads(response)
        raise GraphAPIError(response)


def get_app_access_token(app_id, app_secret):
    """Get the access_token for the app.

    This token can be used for insights and creating test users.

    app_id = retrieved from the developer page
    app_secret = retrieved from the developer page

    Returns the application access_token.

    """
    # Get an app access token
    args = {'grant_type': 'client_credentials',
            'client_id': app_id,
            'client_secret': app_secret}

    file = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" +
                           urllib.urlencode(args))

    try:
        result = file.read().split("=")[1]
    finally:
        file.close()

    return result