Пример #1
0
    def authenticate(self, cookies):
        API_KEY = FACEBOOK_API_KEY
        API_SECRET = FACEBOOK_API_SECRET
        REST_SERVER = FACEBOOK_REST_SERVER
        if API_KEY in cookies:
            signature_hash = get_facebook_signature(API_KEY, API_SECRET, cookies, True)
            if(signature_hash == cookies[API_KEY]) and (datetime.fromtimestamp(float(cookies[API_KEY+'_expires'])) > datetime.now()):
                user_info_response  = get_user_info(API_KEY, API_SECRET, cookies)
                username = user_info_response[0]['first_name']
                try:
                    profile = FacebookUserProfile.objects.get(facebook_uid = user_info_response[0]['uid'])
                    return profile.user
                except FacebookUserProfile.DoesNotExist:
                    fb_data = user_info_response[0]
                    name_count = AuthUser.objects.filter(username__istartswith = username).count()
                    if name_count:
                        username = '******' % (username, name_count + 1)
                    #user_email = '%s@facebookuser.%s.com'%(user_info_response[0]['first_name'], settings.SITE_NAME)
                    user = User.objects.create(username = username)
                    user.first_name = fb_data['first_name']
                    user.last_name = fb_data['last_name']
                    user.save()
                    location = str(fb_data['current_location'])
                    fb_profile = FacebookUserProfile(facebook_uid = fb_data['uid'], user = user, profile_image_url = fb_data['pic_small'], location=location)
                    fb_profile.save()
                    auth_meta = AuthMeta(user=user, provider='Facebook').save()
                    return user
            else:
                return None

        else:
            return None
Пример #2
0
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES,
                                               FACEBOOK_APP_ID,
                                               FACEBOOK_SECRET_KEY)
        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = '%s://%s%s' % (
                         'https' if request.is_secure() else 'http',
                         Site.objects.get_current().domain,
                         reverse("socialauth_facebook_login_done"))
            params["code"] = request.GET.get('code', '')

            url = ("https://graph.facebook.com/oauth/access_token?"
                   + urllib.urlencode(params))
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)
            # Could be a bot query
            if not res_parse_qs.has_key('access_token'):
                return None
                
            access_token = res_parse_qs['access_token'][-1]
            
            graph = facebook.GraphAPI(access_token)
            uid = graph.get_object('me')['id']
            
        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:
            
            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token) 
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            username = uid
            if not user:
                user = User.objects.create(username=username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.email = username + '@socialauth+facebook'
                user.save()
                
            fb_profile = FacebookUserProfile(facebook_uid=uid, user=user)
            fb_profile.save()
            
            auth_meta = AuthMeta(user=user, provider='Facebook').save()
                
            return user
Пример #3
0
 def authenticate(self, request):
     """
     Started at 
         http://github.com/uswaretech/Django-Socialauth/blob/master/socialauth/auth_backends.py
     
     Made massive improvements with error handling.
     """
     facebook =  Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
     check = facebook.check_session(request)
     clear_permissions(request) # for internal perms
     try:
         fb_user = facebook.users.getLoggedInUser()
         fb_data = get_fb_data(facebook, fb_user)
         
         profile = FacebookUserProfile.objects.get(facebook_uid = unicode(fb_user))            
     except FacebookUserProfile.DoesNotExist:
         username = '******' % fb_data['uid']
         fb_user,new_user = User.objects.get_or_create(username = username)
         fb_user.is_active = True
         fb_user.first_name = fb_data['first_name']
         fb_user.last_name = fb_data['last_name']
         fb_user.email = fb_data['email']
         fb_user.save()
         
         try:
             profile = FacebookUserProfile(facebook_uid= unicode(fb_data['uid']), user=fb_user)
             profile.save()
             auth_meta = AuthMeta(user=user, provider='Facebook').save()
         except:
             pass
     except Exception, e:
         return None
Пример #4
0
    def authenticate(self, request):

        if not settings.FACEBOOK_API_KEY in request.COOKIES:
            return None

        facebook =  Facebook(settings.FACEBOOK_API_KEY,
                             settings.FACEBOOK_SECRET_KEY)
                             
        check = facebook.check_session(request)
        fb_user = facebook.users.getLoggedInUser()

        try:
            profile = FacebookUserProfile.objects.get(facebook_uid = fb_user)
            return profile.user
        except FacebookUserProfile.DoesNotExist:
            fb_data = facebook.users.getInfo([fb_user], ['uid', 'first_name', 'last_name', 'pic_small', 'current_location'])
            if not fb_data:
                return None
            fb_data = fb_data[0]

            username = '******' % fb_data['uid']
            user_email = '%s@facebookuser.%s.com'%(fb_data['first_name'], settings.SITE_NAME)
            user = User.objects.create(username = username, email=user_email)
            user.first_name = fb_data['first_name']
            user.last_name = fb_data['last_name']
            user.save()
            location = str(fb_data['current_location'])
            fb_profile = FacebookUserProfile(facebook_uid = fb_data['uid'], user = user, profile_image_url = fb_data['pic_small'], location=location)
            fb_profile.save()
            auth_meta = AuthMeta(user=user, provider='Facebook').save()
            return user
        except Exception, e:
            print str(e)
Пример #5
0
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES,
                                               FACEBOOK_APP_ID,
                                               FACEBOOK_SECRET_KEY)
        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = '%s://%s%s' % (
                'https' if request.is_secure() else 'http',
                Site.objects.get_current().domain,
                reverse("socialauth_facebook_login_done"))
            params["code"] = request.GET.get('code', '')

            url = ("https://graph.facebook.com/oauth/access_token?" +
                   urllib.urlencode(params))
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)
            # Could be a bot query
            if not res_parse_qs.has_key('access_token'):
                return None

            access_token = res_parse_qs['access_token'][-1]

            graph = facebook.GraphAPI(access_token)
            uid = graph.get_object('me')['id']

        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:

            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token)
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            username = uid
            if not user:
                user = User.objects.create(username=username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.email = username + '@socialauth+facebook'
                user.save()

            fb_profile = FacebookUserProfile(facebook_uid=uid, user=user)
            fb_profile.save()

            auth_meta = AuthMeta(user=user, provider='Facebook').save()

            return user
Пример #6
0
    def authenticate(self, request, user=None):

        """
        if not settings.FACEBOOK_API_KEY in request.COOKIES:
            logging.debug("Could not find FACEBOOK_API_KEY in Cookies")
            return None
        """


        cookie = facebook.get_user_from_cookie(request.COOKIES, FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY)
        
        #print cookie

        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = reverse("socialauth_facebook_login_done")[1:] 
            params["code"] = request.GET.get('code', '')

            url = "https://graph.facebook.com/oauth/access_token?"+urllib.urlencode(params)
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            parse_data = parse_qs(userdata)['access_token']
            uid = parse_data['uid'][-1]
            access_token = parse_data['access_token'][-1]
        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:
            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token) 
            fb_data = graph.get_object("me")

        print fb_data 
        if not fb_data:
            return None

        username = '******' % uid
        if not user:
            user = User.objects.create(username=username)
            user.first_name = fb_data['first_name']
            user.last_name = fb_data['last_name']
            user.email = username + "@facebook"
            user.save()
        fb_profile = FacebookUserProfile(facebook_uid=uid, user=user)
        fb_profile.save()
        auth_meta = AuthMeta(user=user, provider='Facebook',
            provider_model='FacebookUserProfile', provider_id=fb_profile.pk).save()
        return user
Пример #7
0
    def authenticate(self, cookies):
        API_KEY = FACEBOOK_API_KEY
        API_SECRET = FACEBOOK_API_SECRET
        REST_SERVER = FACEBOOK_REST_SERVER
        if API_KEY in cookies:
            signature_hash = get_facebook_signature(API_KEY, API_SECRET,
                                                    cookies, True)
            if (signature_hash == cookies[API_KEY]) and (
                    datetime.fromtimestamp(float(
                        cookies[API_KEY + '_expires'])) > datetime.now()):
                user_info_response = get_user_info(API_KEY, API_SECRET,
                                                   cookies)
                username = user_info_response[0]['first_name']
                try:
                    user_profile = FacebookUserProfile.objects.get(
                        user__is_active=True,
                        facebook_uid=user_info_response[0]['uid'])
                    if user_profile.user.is_active:
                        return user_profile.user
                    else:
                        return
                except FacebookUserProfile.DoesNotExist:
                    fb_data = user_info_response[0]
                    name_count = AuthUser.objects.filter(
                        username__istartswith=username).count()
                    if name_count:
                        username = '******' % (username, name_count + 1)
                    #user_email = '%s@facebookuser.%s.com'%(user_info_response[0]['first_name'], settings.SITE_NAME)
                    user = User.objects.create(username=username)
                    user.first_name = fb_data['first_name']
                    user.last_name = fb_data['last_name']
                    user.save()
                    location = str(fb_data['current_location'])
                    fb_profile = FacebookUserProfile(
                        facebook_uid=fb_data['uid'],
                        user=user,
                        profile_image_url=fb_data['pic_small'],
                        location=location)
                    fb_profile.save()
                    AuthMeta(user=user, provider='Facebook').save()
                    return user
            else:
                return None

        else:
            return None
Пример #8
0
    def authenticate(self, fb_access_token):
        """ authenticates the token by requesting user information from facebook """
        try:
            api = facebook.GraphAPI(fb_access_token)
            userinfo = api.get_object("me")
        except:
            # If we cannot get the user information, user cannot be authenticated
            raise
        # variables not initialise here
        try:
            user_profile = FacebookUserProfile.objects.get(
                fb_uid=userinfo['id'])
            if user_profile.user.is_active:
                return user_profile.user
            else:
                return
        except FacebookUserProfile.DoesNotExist:
            #Create new user
            try:
                username = userinfo['username']
            except KeyError:
                # if username not set on facebook
                username = userinfo['first_name']

            user = new_user(username=username, provider='Facebook')

            user.first_name, user.last_name = userinfo['first_name'], userinfo[
                'last_name']
            #img_url = 'http://graph.facebook.com/me/picture?type=large'+'&fb_access_token='+ access_token
            user.save()
            userprofile = FacebookUserProfile(user=user,
                                              fb_uid=userinfo['id'],
                                              fb_username=username,
                                              location=userinfo['location'])
            userprofile.access_token = fb_access_token
            """if img_url:
                img = ContentFile(urlopen(img_url).read())
                name = img_url.split('/')[-1]
                user.picture.save(name, img, False)"""

        userprofile.save()
        AuthMeta(user=user, provider='Facebook').save()
        return user
    def authenticate(self, request):

        """
        if not settings.FACEBOOK_API_KEY in request.COOKIES:
            logging.debug("Could not find FACEBOOK_API_KEY in Cookies")
            return None
        """

        facebook =  Facebook(settings.FACEBOOK_API_KEY,
                             settings.FACEBOOK_SECRET_KEY)
                             
        check = facebook.check_session(request)
        fb_user = facebook.users.getLoggedInUser()

        try:
            profile = FacebookUserProfile.objects.get(facebook_uid = str(fb_user))
            return profile.user
        except FacebookUserProfile.DoesNotExist:
            fb_data = facebook.users.getInfo([fb_user], ['uid', 'about_me', 'first_name', 'last_name', 'pic_big', 'pic', 'pic_small', 'current_location', 'profile_url', 'email'])
            if not fb_data:
                return None
            fb_data = fb_data[0]

            username = '******' % fb_data['uid']
            email = fb_data['email']
            try:
                  user = User.objects.get(email=email)
            except:
                  #user_email = '*****@*****.**'%(fb_data['uid'])
                  user = User.objects.create(username = username)
                  user.first_name = fb_data['first_name']
                  user.last_name = fb_data['last_name']
                  user.save()
                  location = str(fb_data['current_location'])
                  about_me = str(fb_data['about_me'])
                  url = str(fb_data['profile_url'])
                  fb_profile = FacebookUserProfile(facebook_uid = str(fb_data['uid']), user = user, profile_image_url = fb_data['pic'], profile_image_url_big = fb_data['pic_big'], profile_image_url_small = fb_data['pic_small'], location=location, about_me=about_me, url=url)
                  fb_profile.save()
            auth_meta = AuthMeta(user=user, provider='Facebook').save()
            return user
        except Exception, e:
            print str(e)
Пример #10
0
    def authenticate(self, request):

        if not settings.FACEBOOK_API_KEY in request.COOKIES:
            return None

        facebook = Facebook(settings.FACEBOOK_API_KEY,
                            settings.FACEBOOK_SECRET_KEY)

        check = facebook.check_session(request)
        fb_user = facebook.users.getLoggedInUser()

        try:
            profile = FacebookUserProfile.objects.get(facebook_uid=fb_user)
            return profile.user
        except FacebookUserProfile.DoesNotExist:
            fb_data = facebook.users.getInfo([fb_user], [
                'uid', 'first_name', 'last_name', 'pic_small',
                'current_location'
            ])
            if not fb_data:
                return None
            fb_data = fb_data[0]

            username = '******' % fb_data['uid']
            user_email = '%s@facebookuser.%s.com' % (fb_data['first_name'],
                                                     settings.SITE_NAME)
            user = User.objects.create(username=username, email=user_email)
            user.first_name = fb_data['first_name']
            user.last_name = fb_data['last_name']
            user.save()
            location = str(fb_data['current_location'])
            fb_profile = FacebookUserProfile(
                facebook_uid=fb_data['uid'],
                user=user,
                profile_image_url=fb_data['pic_small'],
                location=location)
            fb_profile.save()
            auth_meta = AuthMeta(user=user, provider='Facebook').save()
            return user
        except Exception, e:
            print str(e)
Пример #11
0
    def authenticate(self, fb_access_token):
        """ authenticates the token by requesting user information from facebook """
        try:
            api = facebook.GraphAPI(fb_access_token)
            userinfo = api.get_object("me")
        except:
            # If we cannot get the user information, user cannot be authenticated
            raise
        # variables not initialise here
        try:
            user_profile = FacebookUserProfile.objects.get(fb_uid = userinfo['id'])
            if user_profile.user.is_active:
                return user_profile.user
            else:
                return
        except FacebookUserProfile.DoesNotExist:
            #Create new user
            try:
                username = userinfo['username']
            except KeyError:
                # if username not set on facebook
                username = userinfo['first_name']
                       
            user = new_user(username = username, provider = 'Facebook')
                       
            user.first_name, user.last_name = userinfo['first_name'], userinfo['last_name']
            #img_url = 'http://graph.facebook.com/me/picture?type=large'+'&fb_access_token='+ access_token
            user.save()
            userprofile = FacebookUserProfile(user = user, fb_uid = userinfo['id'], fb_username = username, location = userinfo['location'])
            userprofile.access_token = fb_access_token

            """if img_url:
                img = ContentFile(urlopen(img_url).read())
                name = img_url.split('/')[-1]
                user.picture.save(name, img, False)"""
       
        userprofile.save()
        AuthMeta(user=user, provider='Facebook').save()
        return user
Пример #12
0
    def authenticate(self, facebook, request):
        facebook.oauth2_check_session(request)

        facebook.uid = facebook.users.getLoggedInUser()
        user_info = facebook.users.getInfo([facebook.uid], ['first_name', 'last_name', 'pic_square'])[0]

        username = user_info['first_name']
        try:
            user_profile = FacebookUserProfile.objects.get(user__is_active=True, facebook_uid=user_info['uid'])
            if user_profile.user.is_active:
                return user_profile.user
            else:
                return None
        except FacebookUserProfile.DoesNotExist:
            name_count = AuthUser.objects.filter(username__istartswith=username).count()
            if name_count:
                username = '******' % (username, name_count + 1)

            user = User.objects.create(username=username)
            user.first_name = user_info['first_name']
            user.last_name = user_info['last_name']

            img_url = user_info.get('pic_square')
            if img_url:
                img = ContentFile(urlopen(img_url).read())
                name = img_url.split('/')[-1]
                user.picture.save(name, img, False)

            user.save()

            location = '' # TODO: Figure out how to get this from Facebook.  Maybe.

            fb_profile = FacebookUserProfile(facebook_uid=user_info['uid'], user=user,
                    profile_image_url=img_url, location=location)
            fb_profile.save()

            AuthMeta(user=user, provider='Facebook').save()
            return user
Пример #13
0
    def authenticate(self, request, user=None):

        """
        if not settings.FACEBOOK_API_KEY in request.COOKIES:
            logging.debug("Could not find FACEBOOK_API_KEY in Cookies")
            return None
        """

        facebook =  Facebook(settings.FACEBOOK_API_KEY,
                             settings.FACEBOOK_SECRET_KEY)
                             
        check = facebook.check_session(request)
        fb_user = facebook.users.getLoggedInUser()

        try:
            profile = FacebookUserProfile.objects.get(facebook_uid = str(fb_user))
            return profile.user
        except FacebookUserProfile.DoesNotExist:
            fb_data = facebook.users.getInfo([fb_user], ['uid', 'first_name', 'last_name'])
            if not fb_data:
                return None
            fb_data = fb_data[0]
            username = '******' % fb_data['uid']
            if not user:
                user = User.objects.create(username = username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.email = username + "@socialauth"
                user.save()
            fb_profile = FacebookUserProfile(facebook_uid = str(fb_data['uid']), user = user)
            fb_profile.save()
            auth_meta = AuthMeta(user=user, provider='Facebook',
                provider_model='FacebookUserProfile', provider_id=fb_profile.pk).save()
            return user
        except Exception, e:
            print str(e)
Пример #14
0
    def authenticate(self, request):

        """
        if not settings.FACEBOOK_API_KEY in request.COOKIES:
            logging.debug("Could not find FACEBOOK_API_KEY in Cookies")
            return None
        """

        facebook = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)

        check = facebook.check_session(request)
        fb_user = facebook.users.getLoggedInUser()

        try:
            profile = FacebookUserProfile.objects.get(facebook_uid=str(fb_user))
            return profile.user
        except FacebookUserProfile.DoesNotExist:
            user = None
            fb_data = facebook.users.getInfo(
                [fb_user],
                [
                    "uid",
                    "about_me",
                    "first_name",
                    "last_name",
                    "pic_big",
                    "pic",
                    "pic_small",
                    "current_location",
                    "profile_url",
                    "email",
                ],
            )
            if not fb_data:
                return None
            fb_data = fb_data[0]

            username = "******" % fb_data["uid"]
            email = fb_data["email"]
            try:
                if not email:
                    raise
                user = User.objects.get(email=email)
            except:
                # user_email = '*****@*****.**'%(fb_data['uid'])
                user = User.objects.create(username=username)
                user.first_name = fb_data["first_name"]
                user.last_name = fb_data["last_name"]
                if email:
                    user.email = email
                user.save()
                location = unicode(fb_data["current_location"])
                about_me = unicode(fb_data["about_me"])
                url = str(fb_data["profile_url"])
                fb_profile = FacebookUserProfile(
                    facebook_uid=str(fb_data["uid"]),
                    user=user,
                    profile_image_url=fb_data["pic"],
                    profile_image_url_big=fb_data["pic_big"],
                    profile_image_url_small=fb_data["pic_small"],
                    location=location,
                    about_me=about_me,
                    url=url,
                )
                fb_profile.save()
            auth_meta = AuthMeta(user=user, provider="Facebook").save()
            return user
        except Exception, e:
            print str(e)
Пример #15
0
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES, FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY)

        if cookie:
            uid = cookie["uid"]
            access_token = cookie["access_token"]
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = "%s://%s%s" % (
                "https" if request.is_secure() else "http",
                Site.objects.get_current().domain,
                reverse("socialauth_facebook_login_done"),
            )

            params["code"] = request.GET.get("code", "")

            url = "https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(params)
            from cgi import parse_qs

            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)

            # Could be a bot query
            if not res_parse_qs.has_key("access_token"):
                return None

            access_token = res_parse_qs["access_token"][-1]

            graph = facebook.GraphAPI(access_token)
            uid = graph.get_object("me")["id"]

        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:

            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token)
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            if not user:
                username = "******" % fb_data["id"]
                user = User.objects.create(username=username)
                user.first_name = fb_data["first_name"]
                user.last_name = fb_data["last_name"]
                user.email = username + "@socialauth"
                user.set_unusable_password()
                user.save()

            fb_profile = FacebookUserProfile(facebook_uid=uid, user=user)
            fb_profile.save()

            auth_meta = AuthMeta(
                user=user, provider="Facebook", provider_model="FacebookUserProfile", provider_id=fb_profile.pk
            ).save()

            return user
Пример #16
0
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES,
                                               FACEBOOK_APP_ID,
                                               FACEBOOK_SECRET_KEY)
        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = reverse(
                                              "socialauth_facebook_login_done"
                                              )[1:]
            params["code"] = request.GET.get('code', '')

            url = ("https://graph.facebook.com/oauth/access_token?"
                   +urllib.urlencode(params))
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)
            # Could be a bot query
            if not res_parse_qs.has_key('access_token'):
                return None
                
            parse_data = res_parse_qs['access_token']
            uid = parse_data['uid'][-1]
            access_token = parse_data['access_token'][-1]
            
        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:
            
            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token) 
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            username = uid
            if not user:
                user = User.objects.create(username=username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.email = fb_data.get('email')
                user.save()
                
            picture_url = 'http://graph.facebook.com/%s/picture' % uid
            fb_profile = FacebookUserProfile(
                facebook_uid=uid, 
                user=user,
                profile_image_url = picture_url,
                profile_image_url_small = picture_url + '?type=small',
                profile_image_url_big = picture_url + '?type=large',
                about_me = fb_data.get('about'),
                url = fb_data.get('website'),
            )
            if 'location' in fb_data:
                fb_profile.location = fb_data['location']['name']

            fb_profile.save()
            
            auth_meta = AuthMeta(user=user, provider='Facebook').save()
                
            return user
Пример #17
0
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES,
                                               FACEBOOK_APP_ID,
                                               FACEBOOK_SECRET_KEY)
        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = reverse(
                "socialauth_facebook_login_done")[1:]
            params["code"] = request.GET.get('code', '')

            url = ("https://graph.facebook.com/oauth/access_token?" +
                   urllib.urlencode(params))
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)
            # Could be a bot query
            if not res_parse_qs.has_key('access_token'):
                return None

            parse_data = res_parse_qs['access_token']
            uid = parse_data['uid'][-1]
            access_token = parse_data['access_token'][-1]

        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:

            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token)
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            username = uid
            if not user:
                user = User.objects.create(username=username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.email = fb_data.get('email')
                user.save()

            picture_url = 'http://graph.facebook.com/%s/picture' % uid
            fb_profile = FacebookUserProfile(
                facebook_uid=uid,
                user=user,
                profile_image_url=picture_url,
                profile_image_url_small=picture_url + '?type=small',
                profile_image_url_big=picture_url + '?type=large',
                about_me=fb_data.get('about'),
                url=fb_data.get('website'),
            )
            if 'location' in fb_data:
                fb_profile.location = fb_data['location']['name']

            fb_profile.save()

            auth_meta = AuthMeta(user=user, provider='Facebook').save()

            return user