Esempio n. 1
0
 def setUp(self):
     self.signup_url = reverse("socialaccount_signup", locale=settings.WIKI_DEFAULT_LANGUAGE)
     self.provider = registry.by_id(KumaGitHubProvider.id)
     app = SocialApp.objects.create(
         provider=self.provider.id, name=self.provider.id, client_id="app123id", key=self.provider.id, secret="dummy"
     )
     app.sites.add(Site.objects.get_current())
Esempio n. 2
0
 def update_user_fields(self, request, sociallogin=None, user=None):
     changed = False
     if user is None:
         user = sociallogin.account.user
     adfs_provider = registry.by_id(ADFSOAuth2Provider.id, request)
     
     false_keys = ["is_staff", "is_superuser"]
     boolean_keys = false_keys + ["is_active"]
     copy_keys = boolean_keys + ["first_name", "last_name", "email"]
     
     if sociallogin is not None and sociallogin.account.provider == ADFSOAuth2Provider.id:
         data = sociallogin.account.extra_data
         values = adfs_provider.extract_common_fields(data)
         for key in copy_keys:
             # it is assumed that values are cleaned and set for all
             # fields and if any of the boolean_keys are not provided
             # in the raw data they should be set to False by
             # the extract_common_fields method
             if getattr(user, key) != values[key]:
                 setattr(user, key, values[key])
                 changed = True
     else:
         for key in false_keys:
             if getattr(user, key):
                 msg = "Staff users must authenticate via the %s provider!" % adfs_provider.name
                 response = HttpResponseForbidden(msg)
                 raise ImmediateHttpResponse(response)
     
     return changed, user
Esempio n. 3
0
    def complete_login(self, request, app, token, **kwargs):
        provider = registry.by_id(app.provider)
        resp = requests.get(self.profile_url,
                            params={'access_token': token.token})

        extra_data = resp.json()
        return self.get_provider().sociallogin_from_response(
            request, extra_data)
Esempio n. 4
0
def attach_webhook(project_pk, user_pk):
    """
    Add post-commit hook on project import.

    This is a brute force approach to add a webhook to a repository. We try
    all accounts until we set up a webhook. This should remain around for legacy
    connections -- that is, projects that do not have a remote repository them
    and were not set up with a VCS provider.
    """
    project = Project.objects.get(pk=project_pk)
    user = User.objects.get(pk=user_pk)
    project_notification = InvalidProjectWebhookNotification(
        context_object=project,
        user=user,
        success=False,
    )

    for service_cls in registry:
        if service_cls.is_project_service(project):
            service = service_cls
            break
    else:
        log.warning('There are no registered services in the application.')
        project_notification.send()
        return None

    provider = allauth_registry.by_id(service.adapter.provider_id)
    notification = AttachWebhookNotification(
        context_object=provider,
        extra_context={'project': project},
        user=user,
        success=None,
    )

    user_accounts = service.for_user(user)
    for account in user_accounts:
        success, __ = account.setup_webhook(project)
        if success:
            notification.success = True
            notification.send()

            project.has_valid_webhook = True
            project.save()
            return True

    # No valid account found
    if user_accounts:
        notification.success = False
        notification.reason = AttachWebhookNotification.NO_PERMISSIONS
    else:
        notification.success = False
        notification.reason = AttachWebhookNotification.NO_ACCOUNTS

    project_notification.send()
    notification.send()
    return False
Esempio n. 5
0
 def complete_login(self, request, app, token, **kwargs):
     provider = registry.by_id(app.provider)
     site = provider.get_site()
     resp = requests.get(self.profile_url,
                         params={'access_token': token.token,
                                 'key': app.key,
                                 'site': site})
     extra_data = resp.json()['items'][0]
     return self.get_provider().sociallogin_from_response(request,
                                                          extra_data)
Esempio n. 6
0
 def complete_login(self, request, app, token):
     provider = registry.by_id(app.provider)
     site = provider.get_site()
     resp = requests.get(self.profile_url,
         params={ 'access_token': token.token,
                  'key': app.key,
                  'site': site })
     extra_data = resp.json()
     # extra_data is something of the form:
     #
     # {
     #   "items": [
     #     {
     #       "user_id": 654321,
     #       "user_type": "registered",
     #       "creation_date": 1234567890,
     #       "display_name": "Alice",
     #       "profile_image": "http://www.my-site.com/my-handsome-face.jpg",
     #       "reputation": 44,
     #       "reputation_change_day": 0,
     #       "reputation_change_week": 0,
     #       "reputation_change_month": 0,
     #       "reputation_change_quarter": 15,
     #       "reputation_change_year": 31,
     #       "age": 30,
     #       "last_access_date": 1355724123,
     #       "last_modified_date": 1332302654,
     #       "is_employee": false,
     #       "link": "http://stackoverflow.com/users/654321/alice",
     #       "website_url": "http://twitter.com/alice",
     #       "location": "Japan",
     #       "account_id": 123456,
     #       "badge_counts": {
     #         "gold": 0,
     #         "silver": 0,
     #         "bronze": 6
     #       },
     #       "accept_rate": 100
     #     }
     #   ],
     #   "quota_remaining": 9997,
     #   "quota_max": 10000,
     #   "has_more": false
     # }
     if len(extra_data['items']) > 0:
         uid = str(extra_data['items'][0]['user_id'])
         user = User(username=extra_data['items'][0]['display_name'])
         account = SocialAccount(extra_data=extra_data['items'][0],
                                 uid=uid,
                                 provider=self.provider_id,
                                 user=user)
         return SocialLogin(account)
     else:
         raise OAuth2Error("stackexchange/no_site_profile_error.html",
                           { 'se_site': site })
Esempio n. 7
0
def ensure_staff_login_via_adfs(**kwargs):
    adapter = get_adapter()
    if isinstance(adapter, SocialAccountAdapter):
        sociallogin = kwargs.get("sociallogin")
        via_adfs = sociallogin and sociallogin.account.provider == ADFSOAuth2Provider.id
        if not via_adfs:
            changed, user = adapter.update_user_fields(kwargs["request"], user=kwargs["user"])
            if changed:
                user.save()
                provider = registry.by_id(ADFSOAuth2Provider.id)
                messages.warning(kwargs["request"], 'User account modified due to log in provider. Log in with the %s provider to restore functionality when needed.' % provider.name)
Esempio n. 8
0
 def ensure_github_app(self):
     """Ensure a GitHub SocialApp is installed, configured."""
     provider = registry.by_id(KumaGitHubProvider.id)
     app, created = SocialApp.objects.get_or_create(
         provider=provider.id,
         defaults={
             'name': provider.id,
             'client_id': 'app123id',
             'key': provider.id,
             'secret': 'dummy'})
     if created:
         app.sites.add(Site.objects.get_current())
     return app
Esempio n. 9
0
 def complete_login(self, request, app, token):
     provider = registry.by_id(app.provider)
     site = provider.get_site()
     resp = requests.get(self.profile_url,
                         params={ 'access_token': token.token,
                                  'key': app.key,
                                  'site': site })
     extra_data = resp.json()['items'][0]
     # `user_id` varies if you use the same account for
     # e.g. StackOverflow and ServerFault. Therefore, we pick
     # `account_id`.
     uid = str(extra_data['account_id'])
     user = User(username=extra_data.get('display_name', ''))
     account = SocialAccount(user=user,
                             uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     return SocialLogin(account)
Esempio n. 10
0
def test_battlenet_auth_loaded():
    assert registry.loaded
    provider = registry.by_id("battlenet")
    assert provider.id == "battlenet"
Esempio n. 11
0
 def provider_name(self):
     return registry.by_id(self.provider_id).name
Esempio n. 12
0
class BaiduTests(create_oauth2_tests(registry.by_id(BaiduProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(200, """{"portrait": "78c0e9839de59bbde7859ccf43", "uname": "\u90dd\u56fd\u715c", "uid": "3225892368"}""")
Esempio n. 13
0
def test_battlenet_auth_loaded():
	assert registry.loaded
	provider = registry.by_id("battlenet")
	assert provider.id == "battlenet"
Esempio n. 14
0
 def ensure_github_app(self):
     """Ensure a GitHub SocialApp is installed, configured."""
     provider = registry.by_id(KumaGitHubProvider.id)
     app = SocialApp.objects.get(provider=provider.id)
     return app
Esempio n. 15
0
def attach_webhook(project_pk, user_pk, integration=None):
    """
    Add post-commit hook on project import.

    This is a brute force approach to add a webhook to a repository. We try
    all accounts until we set up a webhook. This should remain around for legacy
    connections -- that is, projects that do not have a remote repository them
    and were not set up with a VCS provider.
    """
    project = Project.objects.get(pk=project_pk)
    user = User.objects.get(pk=user_pk)
    project_notification = InvalidProjectWebhookNotification(
        context_object=project,
        user=user,
        success=False,
    )
    if integration:
        service = SERVICE_MAP.get(integration.integration_type)

        if not service:
            log.warning('There are no registered services in the application.')
            project_notification.send()
            return None
    else:
        for service_cls in registry:
            if service_cls.is_project_service(project):
                service = service_cls
                break
        else:
            log.warning('There are no registered services in the application.')
            project_notification.send()
            return None

    provider = allauth_registry.by_id(service.adapter.provider_id)
    notification = AttachWebhookNotification(
        context_object=provider,
        extra_context={'project': project},
        user=user,
        success=None,
    )

    user_accounts = service.for_user(user)
    for account in user_accounts:
        success, __ = account.setup_webhook(project, integration=integration)
        if success:
            notification.success = True
            notification.send()

            project.has_valid_webhook = True
            project.save()
            return True

    # No valid account found
    if user_accounts:
        notification.success = False
        notification.reason = AttachWebhookNotification.NO_PERMISSIONS
    else:
        notification.success = False
        notification.reason = AttachWebhookNotification.NO_ACCOUNTS

    project_notification.send()
    notification.send()
    return False
Esempio n. 16
0
class VimeoTests(create_oauth_tests(registry.by_id(VimeoProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
{"generated_in":"0.0137","stat":"ok","person":{"created_on":"2013-04-08 14:24:47","id":"17574504","is_contact":"0","is_plus":"0","is_pro":"0","is_staff":"0","is_subscribed_to":"0","username":"******","display_name":"Raymond Penners","location":"","url":[""],"bio":"","number_of_contacts":"0","number_of_uploads":"0","number_of_likes":"0","number_of_videos":"0","number_of_videos_appears_in":"0","number_of_albums":"0","number_of_channels":"0","number_of_groups":"0","profileurl":"http:\\/\\/vimeo.com\\/user17574504","videosurl":"http:\\/\\/vimeo.com\\/user17574504\\/videos","portraits":{"portrait":[{"height":"30","width":"30","_content":"http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_30_yellow.png"},{"height":"75","width":"75","_content":"http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_75_yellow.png"},{"height":"100","width":"100","_content":"http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_100_yellow.png"},{"height":"300","width":"300","_content":"http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_300_yellow.png"}]}}}
""")
Esempio n. 17
0
class SalesforceTests(
        create_oauth2_tests(registry.by_id(SalesforceProvider.id))):
    def get_mocked_response(self,
                            family_name='Penners',
                            given_name='Raymond',
                            name='Raymond Penners',
                            email='*****@*****.**',
                            verified_email=True):
        return MockedResponse(
            200, """
              {"family_name": "%s", "name": "%s",
               "picture": "https://lh5.googleusercontent.com/photo.jpg",
               "locale": "nl", "gender": "male",
               "email": "%s",
               "link": "https://plus.google.com/108204268033311374519",
               "given_name": "%s", "user_id": "108204268033311374519",
               "verified_email": %s }
        """ % (family_name, name, email, given_name,
               (repr(verified_email).lower())))

    def test_salesforce_compelete_login_401(self):
        from allauth.socialaccount.providers.salesforce.views import \
            SalesforceOAuth2Adapter

        class LessMockedResponse(MockedResponse):
            def raise_for_status(self):
                if self.status_code != 200:
                    raise HTTPError(None)

        request = RequestFactory().get(reverse(self.provider.id + '_login'),
                                       dict(process='login'))

        adapter = SalesforceOAuth2Adapter()
        app = adapter.get_provider().get_app(request)
        token = SocialToken(token='some_token')
        response_with_401 = LessMockedResponse(
            401, """
            {"error": {
              "errors": [{
                "domain": "global",
                "reason": "authError",
                "message": "Invalid Credentials",
                "locationType": "header",
                "location": "Authorization" } ],
              "code": 401,
              "message": "Invalid Credentials" }
            }""")
        with patch('allauth.socialaccount.providers.salesforce.views'
                   '.requests') as patched_requests:
            patched_requests.get.return_value = response_with_401
            with self.assertRaises(HTTPError):
                adapter.complete_login(request, app, token)

    def test_username_based_on_email(self):
        first_name = '明'
        last_name = '小'
        email = '*****@*****.**'
        self.login(
            self.get_mocked_response(name=first_name + ' ' + last_name,
                                     email=email,
                                     given_name=first_name,
                                     family_name=last_name,
                                     verified_email=True))
        user = User.objects.get(email=email)
        self.assertEqual(user.username, 'raymond.penners')

    def test_email_verified(self):
        test_email = '*****@*****.**'
        self.login(self.get_mocked_response(verified_email=True))
        email_address = EmailAddress.objects \
            .get(email=test_email,
                 verified=True)
        self.assertFalse(
            EmailConfirmation.objects.filter(
                email_address__email=test_email).exists())
        account = email_address.user.socialaccount_set.all()[0]
        self.assertEqual(account.extra_data['given_name'], 'Raymond')

    def test_user_signed_up_signal(self):
        sent_signals = []

        def on_signed_up(sender, request, user, **kwargs):
            sociallogin = kwargs['sociallogin']
            self.assertEqual(sociallogin.account.provider,
                             SalesforceProvider.id)
            self.assertEqual(sociallogin.account.user, user)
            sent_signals.append(sender)

        user_signed_up.connect(on_signed_up)
        self.login(self.get_mocked_response(verified_email=True))
        self.assertTrue(len(sent_signals) > 0)

    def test_email_unverified(self):
        test_email = '*****@*****.**'
        resp = self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects \
            .get(email=test_email)
        self.assertFalse(email_address.verified)
        self.assertTrue(
            EmailConfirmation.objects.filter(
                email_address__email=test_email).exists())
        self.assertTemplateUsed(
            resp, 'account/email/email_confirmation_signup_subject.txt')

    def test_email_verified_stashed(self):
        # http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
        request = RequestFactory().get('/')
        request.session = self.client.session
        adapter = get_adapter()
        test_email = '*****@*****.**'
        adapter.stash_verified_email(request, test_email)
        request.session.save()

        self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects \
            .get(email=test_email)
        self.assertTrue(email_address.verified)
        self.assertFalse(
            EmailConfirmation.objects.filter(
                email_address__email=test_email).exists())

    def test_account_connect(self):
        email = '*****@*****.**'
        user = User.objects.create(username='******',
                                   is_active=True,
                                   email=email)
        user.set_password('test')
        user.save()
        EmailAddress.objects.create(user=user,
                                    email=email,
                                    primary=True,
                                    verified=True)
        self.client.login(username=user.username, password='******')
        self.login(self.get_mocked_response(verified_email=True),
                   process='connect')
        # Check if we connected...
        self.assertTrue(
            SocialAccount.objects.filter(
                user=user, provider=SalesforceProvider.id).exists())
        # For now, we do not pick up any new e-mail addresses on connect
        self.assertEqual(EmailAddress.objects.filter(user=user).count(), 1)
        self.assertEqual(
            EmailAddress.objects.filter(user=user, email=email).count(), 1)

    @override_settings(ACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.MANDATORY,
                       SOCIALACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.NONE)
    def test_social_email_verification_skipped(self):
        test_email = '*****@*****.**'
        self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects.get(email=test_email)
        self.assertFalse(email_address.verified)
        self.assertFalse(
            EmailConfirmation.objects.filter(
                email_address__email=test_email).exists())

    @override_settings(ACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.OPTIONAL,
                       SOCIALACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.OPTIONAL)
    def test_social_email_verification_optional(self):
        self.login(self.get_mocked_response(verified_email=False))
        self.assertEqual(len(mail.outbox), 1)
        self.login(self.get_mocked_response(verified_email=False))
        self.assertEqual(len(mail.outbox), 1)
Esempio n. 18
0
Uses the testing infrastructure from django-allauth.
"""

from allauth.socialaccount.tests import create_oauth2_tests
from allauth.tests import MockedResponse
from allauth.socialaccount.providers import registry
from django.core.urlresolvers import reverse


from .provider import FirefoxAccountsProvider

# Setup base class but omit from nose tests
create_oauth2_tests.__test__ = False
base_class = create_oauth2_tests(
    registry.by_id(FirefoxAccountsProvider.id))
base_class.__test__ = False


class FirefoxAccountsTest(base_class):
    __test__ = True  # Include in nose tests

    def get_mocked_response(self):
        return MockedResponse(200, """
        {
            "uid":"6d940dd41e636cc156074109b8092f96",
            "email":"*****@*****.**"
        }""")

    def test_authentication_error(self):
        """Test authentication errors.
Esempio n. 19
0
 def ensure_github_app(self):
     """Ensure a GitHub SocialApp is installed, configured."""
     provider = registry.by_id(KumaGitHubProvider.id)
     app = SocialApp.objects.get(provider=provider.id)
     return app
Esempio n. 20
0
class GoogleTests(create_oauth2_tests(registry.by_id(GoogleProvider.id))):

    def get_mocked_response(self, verified_email=True):
        return MockedResponse(200, """
{"family_name": "Penners", "name": "Raymond Penners", 
               "picture": "https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg", 
               "locale": "nl", "gender": "male", 
               "email": "*****@*****.**", 
               "link": "https://plus.google.com/108204268033311374519", 
               "given_name": "Raymond", "id": "108204268033311374519", 
                "verified_email": %s }
""" % (repr(verified_email).lower()))

    @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=True,
                       ACCOUNT_SIGNUP_FORM_CLASS=None,
                       ACCOUNT_EMAIL_VERIFICATION
                       =account_settings.EmailVerificationMethod.MANDATORY)
    def test_email_verified(self):
        test_email = '*****@*****.**'
        self.login(self.get_mocked_response(verified_email=True))
        EmailAddress.objects \
            .get(email=test_email,
                 verified=True)
        self.assertFalse(EmailConfirmation.objects \
                             .filter(email_address__email=test_email) \
                             .exists())

    @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=True,
                       ACCOUNT_SIGNUP_FORM_CLASS=None,
                       ACCOUNT_EMAIL_VERIFICATION
                       =account_settings.EmailVerificationMethod.MANDATORY)
    def test_user_signed_up_signal(self):
        sent_signals = []

        def on_signed_up(sender, request, user, **kwargs):
            sociallogin = kwargs['sociallogin']
            self.assertEquals(sociallogin.account.provider,
                              GoogleProvider.id)
            self.assertEquals(sociallogin.account.user,
                              user)
            sent_signals.append(sender)

        user_signed_up.connect(on_signed_up)
        self.login(self.get_mocked_response(verified_email=True))
        self.assertTrue(len(sent_signals) > 0)

    @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=True,
                       ACCOUNT_SIGNUP_FORM_CLASS=None,
                       ACCOUNT_EMAIL_VERIFICATION
                       =account_settings.EmailVerificationMethod.MANDATORY)
    def test_email_unverified(self):
        test_email = '*****@*****.**'
        self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects \
            .get(email=test_email)
        self.assertFalse(email_address.verified)
        self.assertTrue(EmailConfirmation.objects \
                            .filter(email_address__email=test_email) \
                            .exists())


    @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=True,
                       ACCOUNT_SIGNUP_FORM_CLASS=None,
                       ACCOUNT_EMAIL_VERIFICATION
                       =account_settings.EmailVerificationMethod.MANDATORY)
    def test_email_verified_stashed(self):
        # http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
        request = RequestFactory().get('/')
        request.session = self.client.session
        adapter = get_adapter()
        test_email = '*****@*****.**'
        adapter.stash_email_verified(request, test_email)
        request.session.save()

        self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects \
            .get(email=test_email)
        self.assertTrue(email_address.verified)
        self.assertFalse(EmailConfirmation.objects \
                             .filter(email_address__email=test_email) \
                             .exists())
Esempio n. 21
0
class FacebookTests(create_oauth2_tests(registry.by_id(FacebookProvider.id))):
    facebook_data = """
        {
           "id": "630595557",
           "name": "Raymond Penners",
           "first_name": "Raymond",
           "last_name": "Penners",
           "email": "*****@*****.**",
           "link": "https://www.facebook.com/raymond.penners",
           "username": "******",
           "birthday": "07/17/1973",
           "work": [
              {
                 "employer": {
                    "id": "204953799537777",
                    "name": "IntenCT"
                 }
              }
           ],
           "timezone": 1,
           "locale": "nl_NL",
           "verified": true,
           "updated_time": "2012-11-30T20:40:33+0000"
        }"""

    def get_mocked_response(self, data=None):
        if data is None:
            data = self.facebook_data
        return MockedResponse(200, data)

    def test_username_conflict(self):
        User = get_user_model()
        User.objects.create(username='******')
        self.login(self.get_mocked_response())
        socialaccount = SocialAccount.objects.get(uid='630595557')
        self.assertEqual(socialaccount.user.username, 'raymond')

    def test_username_based_on_provider(self):
        self.login(self.get_mocked_response())
        socialaccount = SocialAccount.objects.get(uid='630595557')
        self.assertEqual(socialaccount.user.username, 'raymond.penners')

    def test_username_based_on_provider_with_simple_name(self):
        data = '{"id": "1234567", "name": "Harvey McGillicuddy"}'
        self.login(self.get_mocked_response(data=data))
        socialaccount = SocialAccount.objects.get(uid='1234567')
        self.assertEqual(socialaccount.user.username, 'harvey')

    def test_media_js(self):
        provider = providers.registry.by_id(FacebookProvider.id)
        request = RequestFactory().get(reverse('account_login'))
        request.session = {}
        script = provider.media_js(request)
        self.assertTrue('"appId": "app123id"' in script)

    def test_login_by_token(self):
        resp = self.client.get(reverse('account_login'))
        with patch('allauth.socialaccount.providers.facebook.views'
                   '.requests') as requests_mock:
            mocks = [self.get_mocked_response().json()]
            requests_mock.get.return_value.json \
                = lambda: mocks.pop()
            resp = self.client.post(reverse('facebook_login_by_token'),
                                    data={'access_token': 'dummy'})
            self.assertEqual('http://testserver/accounts/profile/',
                             resp['location'])

    @override_settings(
        SOCIALACCOUNT_PROVIDERS={
            'facebook': {
                'AUTH_PARAMS': {
                    'auth_type': 'reauthenticate'
                },
                'VERIFIED_EMAIL': False
            }
        })
    def test_login_by_token_reauthenticate(self):
        resp = self.client.get(reverse('account_login'))
        nonce = json.loads(
            resp.context['fb_data'])['loginOptions']['auth_nonce']
        with patch('allauth.socialaccount.providers.facebook.views'
                   '.requests') as requests_mock:
            mocks = [self.get_mocked_response().json(), {'auth_nonce': nonce}]
            requests_mock.get.return_value.json \
                = lambda: mocks.pop()
            resp = self.client.post(reverse('facebook_login_by_token'),
                                    data={'access_token': 'dummy'})
            self.assertEqual('http://testserver/accounts/profile/',
                             resp['location'])

    @override_settings(
        SOCIALACCOUNT_PROVIDERS={'facebook': {
            'VERIFIED_EMAIL': True
        }})
    def test_login_verified(self):
        emailaddress = self._login_verified()
        self.assertTrue(emailaddress.verified)

    def test_login_unverified(self):
        emailaddress = self._login_verified()
        self.assertFalse(emailaddress.verified)

    def _login_verified(self):
        resp = self.login(self.get_mocked_response())
        return EmailAddress.objects.get(email='*****@*****.**')
Esempio n. 22
0
class BitbucketOAuth2Tests(
        create_oauth2_tests(registry.by_id(BitbucketOAuth2Provider.id))):

    response_data = """
        {
            "created_on": "2011-12-20T16:34:07.132459+00:00",
            "display_name": "tutorials account",
            "links": {
                "avatar": {
                    "href": "https://bitbucket-assetroot.s3.amazonaws.com/c/photos/2013/Nov/25/tutorials-avatar-1563784409-6_avatar.png"
                },
                "followers": {
                    "href": "https://api.bitbucket.org/2.0/users/tutorials/followers"
                },
                "following": {
                    "href": "https://api.bitbucket.org/2.0/users/tutorials/following"
                },
                "html": {
                    "href": "https://bitbucket.org/tutorials"
                },
                "repositories": {
                    "href": "https://api.bitbucket.org/2.0/repositories/tutorials"
                },
                "self": {
                    "href": "https://api.bitbucket.org/2.0/users/tutorials"
                }
            },
            "location": "Santa Monica, CA",
            "type": "user",
            "username": "******",
            "uuid": "{c788b2da-b7a2-404c-9e26-d3f077557007}",
            "website": "https://tutorials.bitbucket.org/"
        }
    """

    email_response_data = """
        {
            "page": 1,
            "pagelen": 10,
            "size": 1,
            "values": [
                {
                    "email": "*****@*****.**",
                    "is_confirmed": true,
                    "is_primary": true,
                    "links": {
                        "self": {
                            "href": "https://api.bitbucket.org/2.0/user/emails/[email protected]"
                        }
                    },
                    "type": "email"
                },
                {
                    "email": "*****@*****.**",
                    "is_confirmed": true,
                    "is_primary": true,
                    "links": {
                        "self": {
                            "href": "https://api.bitbucket.org/2.0/user/emails/[email protected]"
                        }
                    },
                    "type": "email"
                }
            ]
        }
    """

    def setUp(self):
        super(BitbucketOAuth2Tests, self).setUp()
        self.mocks = {
            'requests':
            patch('allauth.socialaccount.providers'
                  '.bitbucket_oauth2.views.requests')
        }
        self.patches = dict(
            (name, mocked.start()) for (name, mocked) in self.mocks.items())
        self.patches['requests'].get.side_effect = [
            MockedResponse(200, self.response_data),
            MockedResponse(200, self.email_response_data),
        ]

    def tearDown(self):
        for (_, mocked) in self.mocks.items():
            mocked.stop()

    def get_mocked_response(self):
        return [MockedResponse(200, self.response_data)]

    def test_account_tokens(self, multiple_login=False):
        if multiple_login:
            self.patches['requests'].get.side_effect = [
                MockedResponse(200, self.response_data),
                MockedResponse(200, self.email_response_data),
                MockedResponse(200, self.response_data),
                MockedResponse(200, self.email_response_data),
            ]
        super(BitbucketOAuth2Tests, self).test_account_tokens(multiple_login)
        calls = [
            mock.call('https://api.bitbucket.org/2.0/user', params=mock.ANY),
            mock.call('https://api.bitbucket.org/2.0/user/emails',
                      params=mock.ANY),
        ]
        if multiple_login:
            calls.extend([
                mock.call('https://api.bitbucket.org/2.0/user',
                          params=mock.ANY),
                mock.call('https://api.bitbucket.org/2.0/user/emails',
                          params=mock.ANY),
            ])
        self.patches['requests'].get.assert_has_calls(calls)

    def test_provider_account(self):
        self.login(self.get_mocked_response())
        socialaccount = SocialAccount.objects.get(uid='tutorials')
        self.assertEqual(socialaccount.user.username, 'tutorials')
        self.assertEqual(socialaccount.user.email, '*****@*****.**')
        account = socialaccount.get_provider_account()
        self.assertEqual(account.to_str(), 'tutorials account')
        self.assertEqual(account.get_profile_url(),
                         'https://bitbucket.org/tutorials')
        self.assertEqual(
            account.get_avatar_url(),
            'https://bitbucket-assetroot.s3.amazonaws.com/c/photos/2013/Nov/25/tutorials-avatar-1563784409-6_avatar.png'
        )
        self.patches['requests'].get.assert_has_calls([
            mock.call('https://api.bitbucket.org/2.0/user', params=mock.ANY),
            mock.call('https://api.bitbucket.org/2.0/user/emails',
                      params=mock.ANY),
        ])
Esempio n. 23
0
 def provider_name(self):
     return registry.by_id(self.provider_id).name