Esempio n. 1
0
 def get(self, request, *args, **kwargs):
     backend = kwargs.pop('backend')
     try:
         return complete(request, backend, *args, **kwargs)
     except Exception as e:
         messages.error(request, "Your Google Apps domain isn't authorized for this app")
         return HttpResponseRedirect(reverse('app') + '#/?loginerror')
Esempio n. 2
0
 def get(self, request, *args, **kwargs):
     backend = kwargs.pop('backend')
     try:
         return complete(request, backend, *args, **kwargs)
     except AuthFailed:
         messages.error(request, "Your Google Apps domain isn't authorized for this app")
         return HttpResponseRedirect(reverse('home'))
 def get(self, request, *args, **kwargs):
     backend = kwargs.pop('backend')
     try:
         return complete(request, backend, *args, **kwargs)
     except (AuthCanceled, AuthFailed) as e:
         logger.error(e)
         messages.error(request, self.get_error_message())
         return HttpResponseRedirect(self.get_failure_url())
Esempio n. 4
0
 def get(self, request, *args, **kwargs):
     backend = kwargs.pop('backend')
     try:
         return complete(request, backend, *args, **kwargs)
     except AuthFailed:
         messages.error(
             request,
             "Your Google Apps domain isn't authorized for this app")
         return HttpResponseRedirect(reverse('login'))
Esempio n. 5
0
 def get(self, request, *args, **kwargs):
     result = None
     if request.GET.get('apiconnection', None):
         if request.user.is_authenticated() and 'OdnoklassnikiAppBackend' not in request.session.get(BACKEND_SESSION_KEY, ''):
             logout(request)
         result = complete(request, 'odnoklassnikiapp')
     if isinstance(result, HttpResponse):
         return result
     else:
         if not request.user.is_authenticated() or 'OdnoklassnikiAppBackend' not in request.session.get(BACKEND_SESSION_KEY, ''):
             request.user = AnonymousUser()
     
     context = self.get_context_data(params=kwargs)
     return self.render_to_response(context)
Esempio n. 6
0
def social_auth_complete(request, backend, *args, **kwargs):
    """ wrap social-auth function """
    try:
        response = complete(request, backend, *args, **kwargs)
        # if not request.user.profile.verified:  # todo change this?
        #     return redirect('signup_complete')
        # return redirect('profile')
        return redirect('home')
        # return response
    except Exception, e:
        # logging.error('social_auth_complete: ')
        logging.error(traceback.format_exc())
        messages.error(request, e.message)
        return redirect('signin')
Esempio n. 7
0
 def get(self, request, *args, **kwargs):
     backend = kwargs.pop('backend')
     try:
         response = complete(request, backend, *args, **kwargs)
         if 'picture' in response:
             avatar = urlopen(url)
             image_basename = slugify(user.username + " social")
             image_name = '%s%s.jpg' % (int(time.time()), image_basename)
             user.avatar.save(image_name, ContentFile(avatar.read()))
             user.save()
         return response
     except Exception:
         messages.error(
             request,
             "Your Google Apps domain isn't authorized for this app")
         return HttpResponseRedirect('/')
def registration_complete(request, *args, **kwargs):
    "this might be not a registration but invited user redirected from e.g. facebook"
    if request.GET:
        if 'request_ids' in request.GET:
            # this is a request from invitation from facebook
            request_ids = request.GET['request_ids'].split(',')
            request.session['invited_via'] = 'facebook'
            request.session['invitation_ids'] = request_ids
            print 'setting session'
            return redirect(reverse("acct_login")) # or maybe some invitation greetings

    # at this point user almost registered so we need to check for invitations in session
    if 'invited_via' in request.session:
        invitation_ids = request.session['invitation_ids']
        users = User.objects.filter(invitations__external_id__in=invitation_ids)
        for user in users:
            user.get_profile().invitation_succeed()
        try:
            del request.session['invitation_ids']
            del request.session['invited_via']
        except:pass
    return complete(request, *args, **kwargs)
Esempio n. 9
0
    def login(self, user, mock_urlopen, backend='facebook'):
        """
        Login or Register a facebook user.
        
        If the user has never logged in then they get registered and logged in.
        If the user has already registered, then they are logged in. 

        user: dict
        backend: 'facebook'

        example user:
        {
            'first_name': 'Django', 
            'last_name': 'Reinhardt', 
            'verified': True, 
            'name': 'Django Reinhardt', 
            'locale': 'en_US', 
            'hometown': {
                'id': '12345678', 
                'name': 'Any Town, Any State'
            }, 
            'expires': '4812', 
            'updated_time': '2012-01-29T19:27:32+0000', 
            'access_token': 'dummyToken', 
            'link': 'http://www.facebook.com/profile.php?id=1234', 
            'location': {
                'id': '108659242498155', 
                'name': 'Chicago, Illinois'
            }, 
            'gender': 'male', 
            'timezone': -6, 
            'id': '1234',
            'email': '*****@*****.**'
        }
        """

        if backend not in self.backends:
            raise NoBackendError("%s is not supported" % backend)

        access_token = "access_token=dummyToken&expires=4817"
        """
        mock out urlopen to get 
            1. access token
            2. user profile.
        """
        mock_urlopen.side_effect = [
            DumbResponse(access_token),
            DumbResponse(simplejson.dumps(user))
        ]

        factory = RequestFactory()
        request = factory.post('', {
            'code': 'dummy',
            'redirect_state': 'dummy'
        })

        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
        else:
            request.session = engine.SessionStore()

        request.user = AnonymousUser()
        request.session['facebook_state'] = 'dummy'

        # make it happen.
        redirect = complete(request, backend)

        request.session.save()

        # Set the cookie for this session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)

        return True
Esempio n. 10
0
    def login(self,
              user,
              mock_urlopen,
              mock_facebook_enabled,
              backend='facebook'):
        """
        Login or Register a facebook user.

        If the user has never logged in then they get registered and logged in.
        If the user has already registered, then they are logged in.

        user: dict
        backend: 'facebook'

        example user:
        {
            'first_name': 'Django',
            'last_name': 'Reinhardt',
            'verified': True,
            'name': 'Django Reinhardt',
            'locale': 'en_US',
            'hometown': {
                'id': '12345678',
                'name': 'Any Town, Any State'
            },
            'expires': '4812',
            'updated_time': '2012-01-29T19:27:32+0000',
            'access_token': 'dummyToken',
            'link': 'http://www.facebook.com/profile.php?id=1234',
            'location': {
                'id': '108659242498155',
                'name': 'Chicago, Illinois'
            },
            'gender': 'male',
            'timezone': -6,
            'id': '1234',
            'email': '*****@*****.**'
        }
        """

        token = 'dummyToken'
        backends = {
            'facebook': (
                urllib.parse.urlencode({
                    'access_token': token,
                    'expires': 3600,
                }),
                simplejson.dumps(user),
            ),
            'google': (
                simplejson.dumps({
                    "access_token": token,
                    "token_type": "Bearer",
                    "expires_in": 3600,
                }),
                simplejson.dumps(user),
            ),
            'linkedin': (
                urllib.parse.urlencode({
                    'oauth_token':
                    token,
                    'oauth_token_secret':
                    token,
                    'oauth_callback_confirmed':
                    'true',
                    'xoauth_request_auth_url':
                    ('https://api.linkedin.com/uas/oauth/authorize'),
                    'oauth_expires_in':
                    3600,
                }),
                urllib.parse.urlencode({
                    'oauth_token': token,
                    'oauth_token_secret': token,
                    'oauth_expires_in': 3600,
                    'oauth_authorization_expires_in': 3600,
                }),
                (('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
                  '<person>\n'
                  '  <id>{id}</id>\n'
                  '  <email-address>{email}</email-address>\n'
                  '  <first-name>{first_name}</first-name>\n'
                  '  <last-name>{last_name}</last-name>\n'
                  '</person>\n').format(**user)),
            ),
        }

        if backend not in backends:
            raise NoBackendError("%s is not supported" % backend)
        """
        mock out urlopen
        """
        mock_urlopen.side_effect = [DumbResponse(r) for r in backends[backend]]
        # make it work when no FACEBOOK_APP_ID declared
        mock_facebook_enabled.return_value = True
        factory = RequestFactory()
        request = factory.post('', {
            'code': 'dummy',
            'redirect_state': 'dummy'
        })

        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
        else:
            request.session = engine.SessionStore()

        request.user = AnonymousUser()
        request.session['facebook_state'] = 'dummy'

        # make it happen.
        redirect = complete(request, backend)

        request.session.save()

        # Set the cookie for this session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)

        return True
Esempio n. 11
0
    def login(self, user, mock_urlopen, backend='facebook'):
        """
        Login or Register a facebook user.
        
        If the user has never logged in then they get registered and logged in.
        If the user has already registered, then they are logged in. 

        user: dict
        backend: 'facebook'

        example user:
        {
            'first_name': 'Django', 
            'last_name': 'Reinhardt', 
            'verified': True, 
            'name': 'Django Reinhardt', 
            'locale': 'en_US', 
            'hometown': {
                'id': '12345678', 
                'name': 'Any Town, Any State'
            }, 
            'expires': '4812', 
            'updated_time': '2012-01-29T19:27:32+0000', 
            'access_token': 'dummyToken', 
            'link': 'http://www.facebook.com/profile.php?id=1234', 
            'location': {
                'id': '108659242498155', 
                'name': 'Chicago, Illinois'
            }, 
            'gender': 'male', 
            'timezone': -6, 
            'id': '1234',
            'email': '*****@*****.**'
        }
        """


        if backend not in self.backends:
            raise NoBackendError("%s is not supported" % backend)

        access_token = "access_token=dummyToken&expires=4817"

        """
        mock out urlopen to get 
            1. access token
            2. user profile.
        """
        mock_urlopen.side_effect = [
            DumbResponse(access_token),
            DumbResponse(json.dumps(user))
        ]

        factory = RequestFactory()
        request = factory.post('', {'code': 'dummy','redirect_state': 'dummy'})

        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
        else:
            request.session = engine.SessionStore()

        request.user = AnonymousUser()
        request.session['facebook_state'] = 'dummy'

        # make it happen.
        redirect = complete(request, backend)

        request.session.save()
   
        # Set the cookie for this session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)
    
        return True
Esempio n. 12
0
    def login(self, user, mock_urlopen, mock_facebook_enabled, backend='facebook'):
        """
        Login or Register a facebook user.

        If the user has never logged in then they get registered and logged in.
        If the user has already registered, then they are logged in.

        user: dict
        backend: 'facebook'

        example user:
        {
            'first_name': 'Django',
            'last_name': 'Reinhardt',
            'verified': True,
            'name': 'Django Reinhardt',
            'locale': 'en_US',
            'hometown': {
                'id': '12345678',
                'name': 'Any Town, Any State'
            },
            'expires': '4812',
            'updated_time': '2012-01-29T19:27:32+0000',
            'access_token': 'dummyToken',
            'link': 'http://www.facebook.com/profile.php?id=1234',
            'location': {
                'id': '108659242498155',
                'name': 'Chicago, Illinois'
            },
            'gender': 'male',
            'timezone': -6,
            'id': '1234',
            'email': '*****@*****.**'
        }
        """

        token = 'dummyToken'
        backends = {
            'facebook': (
                urllib.parse.urlencode({
                    'access_token': token,
                    'expires': 3600,
                }),
                simplejson.dumps(user),
            ),

            'google': (
                simplejson.dumps({
                    "access_token": token,
                    "token_type": "Bearer",
                    "expires_in": 3600,
                }),
                simplejson.dumps(user),
            ),

            'linkedin': (
                urllib.parse.urlencode({
                    'oauth_token': token,
                    'oauth_token_secret': token,
                    'oauth_callback_confirmed': 'true',
                    'xoauth_request_auth_url': (
                        'https://api.linkedin.com/uas/oauth/authorize'),
                    'oauth_expires_in': 3600,
                }),
                urllib.parse.urlencode({
                    'oauth_token': token,
                    'oauth_token_secret': token,
                    'oauth_expires_in': 3600,
                    'oauth_authorization_expires_in': 3600,
                }),
                (('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
                  '<person>\n'
                  '  <id>{id}</id>\n'
                  '  <email-address>{email}</email-address>\n'
                  '  <first-name>{first_name}</first-name>\n'
                  '  <last-name>{last_name}</last-name>\n'
                  '</person>\n').format(**user)),
            ),
        }

        if backend not in backends:
            raise NoBackendError("%s is not supported" % backend)

        """
        mock out urlopen
        """
        mock_urlopen.side_effect = [
            DumbResponse(r) for r in backends[backend]
        ]
        # make it work when no FACEBOOK_APP_ID declared
        mock_facebook_enabled.return_value = True
        factory = RequestFactory()
        request = factory.post('', {'code': 'dummy',
            'redirect_state': 'dummy'})

        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
        else:
            request.session = engine.SessionStore()

        request.user = AnonymousUser()
        request.session['facebook_state'] = 'dummy'

        # make it happen.
        redirect = complete(request, backend)

        request.session.save()

        # Set the cookie for this session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)

        return True