예제 #1
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     self.backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.user = None
예제 #2
0
class BaseLegacyTest(BaseBackendTest):
    form = ''
    response_body = ''

    def setUp(self):
        HTTPretty.enable()
        self.backend = module_member(self.backend_path)
        name = self.backend.name.upper().replace('-', '_')
        self.strategy = TestStrategy(self.backend, TestStorage)
        self.complete_url = self.strategy.build_absolute_uri(
            '/complete/{0}'.format(name)
        )
        self.strategy.set_settings({
            'SOCIAL_AUTH_{0}_FORM_URL'.format(name): '/login/{0}'.format(name),
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
                self.backend_path,
                'social.tests.backends.broken_test.BrokenBackendAuth'
            )
        })
        # Force backends loading to trash PSA cache
        load_backends(
            self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
            force_load=True
        )

    def tearDown(self):
        self.strategy = None
        self.backend = None
        self.complete_url = None
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        HTTPretty.disable()

    def do_start(self):
        start_url = self.strategy.build_absolute_uri(self.strategy.start().url)
        HTTPretty.register_uri(
            HTTPretty.GET,
            start_url,
            status=200,
            body=self.form.format(self.complete_url)
        )
        HTTPretty.register_uri(
            HTTPretty.POST,
            self.complete_url,
            status=200,
            body=self.response_body,
            content_type='application/x-www-form-urlencoded'
        )
        response = requests.get(start_url)
        expect(response.text).to.equal(self.form.format(self.complete_url))
        response = requests.post(
            self.complete_url,
            data=parse_qs(self.response_body)
        )
        self.strategy.set_request_data(parse_qs(response.text))
        return self.strategy.complete()
예제 #3
0
 def setUp(self):
     HTTPretty.enable()
     Backend = module_member(self.backend_path)
     self.strategy = TestStrategy(TestStorage)
     self.complete_url = self.raw_complete_url.format(Backend.name)
     self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
     self.strategy.set_settings({
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
         (self.backend_path,
          'social.tests.backends.test_broken.BrokenBackendAuth')
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True)
예제 #4
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     self.backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.user = None
예제 #5
0
class OpenIdTest(BaseBackendTest):
    backend_path = None
    backend = None
    access_token_body = None
    user_data_body = None
    user_data_url = ""
    expected_username = ""
    settings = None
    partial_login_settings = None
    raw_complete_url = "/complete/{0}/"

    def setUp(self):
        HTTPretty.enable()
        self.backend = module_member(self.backend_path)
        name = self.backend.name
        self.complete_url = self.raw_complete_url.format(name)
        self.strategy = TestStrategy(self.backend, TestStorage, redirect_uri=self.complete_url)
        self.strategy.set_settings(
            {
                "SOCIAL_AUTH_AUTHENTICATION_BACKENDS": (
                    self.backend_path,
                    "social.tests.backends.test_broken.BrokenBackendAuth",
                )
            }
        )
        # Force backends loading to trash PSA cache
        load_backends(self.strategy.get_setting("SOCIAL_AUTH_AUTHENTICATION_BACKENDS"), force_load=True)

    def tearDown(self):
        self.strategy = None
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        HTTPretty.disable()

    def get_form_data(self, html):
        parser = FormHTMLParser()
        parser.feed(html)
        return parser.form, parser.inputs

    def openid_url(self):
        return self.strategy.backend.openid_url()

    def post_start(self):
        pass

    def do_start(self):
        HTTPretty.register_uri(
            HTTPretty.GET, self.openid_url(), status=200, body=self.discovery_body, content_type="application/xrds+xml"
        )
        start = self.strategy.start()
        self.post_start()
        form, inputs = self.get_form_data(start)
        HTTPretty.register_uri(HTTPretty.POST, form.get("action"), status=200, body=self.server_response)
        response = requests.post(form.get("action"), data=inputs)
        self.strategy.set_request_data(parse_qs(response.content))
        HTTPretty.register_uri(HTTPretty.POST, form.get("action"), status=200, body="is_valid:true\n")
        return self.strategy.complete()
예제 #6
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     Backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = self.strategy or TestStrategy(TestStorage)
     self.backend = Backend(self.strategy, redirect_uri='/complete/github')
     self.user = None
예제 #7
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.name = self.backend.name.upper().replace('-', '_')
     self.complete_url = self.strategy.build_absolute_uri(
         self.raw_complete_url.format(self.backend.name))
     backends = (self.backend_path,
                 'social.tests.backends.test_broken.BrokenBackendAuth')
     self.strategy.set_settings(
         {'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': backends})
     self.strategy.set_settings(self.extra_settings())
     # Force backends loading to trash PSA cache
     load_backends(backends, force_load=True)
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     TestCode.reset_cache()
예제 #8
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.name = self.backend.name.upper().replace("-", "_")
     self.complete_url = self.strategy.build_absolute_uri(self.raw_complete_url.format(self.backend.name))
     backends = (self.backend_path, "social.tests.backends.test_broken.BrokenBackendAuth")
     self.strategy.set_settings({"SOCIAL_AUTH_AUTHENTICATION_BACKENDS": backends})
     self.strategy.set_settings(self.extra_settings())
     # Force backends loading to trash PSA cache
     load_backends(backends, force_load=True)
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     TestCode.reset_cache()
예제 #9
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     name = self.backend.name
     self.complete_url = self.raw_complete_url.format(name)
     self.strategy = TestStrategy(self.backend, TestStorage, redirect_uri=self.complete_url)
     self.strategy.set_settings(
         {
             "SOCIAL_AUTH_AUTHENTICATION_BACKENDS": (
                 self.backend_path,
                 "social.tests.backends.test_broken.BrokenBackendAuth",
             )
         }
     )
     # Force backends loading to trash PSA cache
     load_backends(self.strategy.get_setting("SOCIAL_AUTH_AUTHENTICATION_BACKENDS"), force_load=True)
예제 #10
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     name = self.backend.name
     self.complete_url = self.raw_complete_url.format(name)
     self.strategy = TestStrategy(self.backend, TestStorage)
     name = name.upper().replace('-', '_')
     self.strategy.set_settings({
         'SOCIAL_AUTH_' + name + '_KEY': 'a-key',
         'SOCIAL_AUTH_' + name + '_SECRET': 'a-secret-key',
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
             self.backend_path,
             'social.tests.backends.broken_test.BrokenBackendAuth'
         )
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True
     )
예제 #11
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     name = self.backend.name.upper().replace('-', '_')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.complete_url = self.strategy.build_absolute_uri(
         '/complete/{0}'.format(name)
     )
     self.strategy.set_settings({
         'SOCIAL_AUTH_{0}_FORM_URL'.format(name): '/login/{0}'.format(name),
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
             self.backend_path,
             'social.tests.backends.broken_test.BrokenBackendAuth'
         )
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True
     )
 def setUp(self):
     self.strategy = TestStrategy(storage=TestStorage)
예제 #13
0
class BaseOAuthTest(BaseBackendTest):
    backend = None
    backend_path = None
    user_data_body = None
    user_data_url = ''
    user_data_content_type = 'application/json'
    access_token_body = None
    access_token_status = 200
    expected_username = ''
    raw_complete_url = ''

    def setUp(self):
        HTTPretty.enable()
        self.backend = module_member(self.backend_path)
        name = self.backend.name
        self.complete_url = self.raw_complete_url.format(name)
        self.strategy = TestStrategy(self.backend, TestStorage)
        name = name.upper().replace('-', '_')
        self.strategy.set_settings({
            'SOCIAL_AUTH_' + name + '_KEY': 'a-key',
            'SOCIAL_AUTH_' + name + '_SECRET': 'a-secret-key',
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
                self.backend_path,
                'social.tests.backends.broken_test.BrokenBackendAuth'
            )
        })
        # Force backends loading to trash PSA cache
        load_backends(
            self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
            force_load=True
        )

    def tearDown(self):
        self.strategy = None
        self.complete_url = None
        self.backend = None
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        HTTPretty.disable()

    def _method(self, method):
        return {'GET': HTTPretty.GET,
                'POST': HTTPretty.POST}[method]

    def handle_state(self, start_url, target_url):
        try:
            if self.backend.STATE_PARAMETER or self.backend.REDIRECT_STATE:
                query = parse_qs(urlparse(start_url).query)
                target_url = target_url + ('?' in target_url and '&' or '?')
                if 'state' in query or 'redirect_state' in query:
                    name = 'state' in query and 'state' or 'redirect_state'
                    target_url += '{0}={1}'.format(name, query[name])
        except AttributeError:
            pass
        return target_url

    def auth_handlers(self, start_url):
        target_url = self.handle_state(start_url,
                                       self.strategy.build_absolute_uri(
                                           self.complete_url
                                       ))
        HTTPretty.register_uri(HTTPretty.GET,
                               start_url,
                               status=301,
                               location=target_url)
        HTTPretty.register_uri(HTTPretty.GET,
                               target_url,
                               status=200,
                               body='foobar')
        HTTPretty.register_uri(self._method(self.backend.ACCESS_TOKEN_METHOD),
                               uri=self.backend.ACCESS_TOKEN_URL,
                               status=self.access_token_status,
                               body=self.access_token_body or '',
                               content_type='text/json')
        if self.user_data_url:
            HTTPretty.register_uri(HTTPretty.GET,
                                   self.user_data_url,
                                   body=self.user_data_body or '',
                                   content_type=self.user_data_content_type)
        return target_url

    def do_start(self):
        start_url = self.strategy.start().url
        target_url = self.auth_handlers(start_url)
        response = requests.get(start_url)
        expect(response.url).to.equal(target_url)
        expect(response.text).to.equal('foobar')
        self.strategy.set_request_data(parse_qs(urlparse(target_url).query))
        return self.strategy.complete()
예제 #14
0
class BaseActionTest(unittest.TestCase):
    user_data_url = 'https://api.github.com/user'
    login_redirect_url = '/success'
    expected_username = '******'
    access_token_body = json.dumps({
        'access_token': 'foobar',
        'token_type': 'bearer'
    })
    user_data_body = json.dumps({
        'login': '******',
        'id': 1,
        'avatar_url': 'https://github.com/images/error/foobar_happy.gif',
        'gravatar_id': 'somehexcode',
        'url': 'https://api.github.com/users/foobar',
        'name': 'monalisa foobar',
        'company': 'GitHub',
        'blog': 'https://github.com/blog',
        'location': 'San Francisco',
        'email': '*****@*****.**',
        'hireable': False,
        'bio': 'There once was...',
        'public_repos': 2,
        'public_gists': 1,
        'followers': 20,
        'following': 0,
        'html_url': 'https://github.com/foobar',
        'created_at': '2008-01-14T04:33:35Z',
        'type': 'User',
        'total_private_repos': 100,
        'owned_private_repos': 100,
        'private_gists': 81,
        'disk_usage': 10000,
        'collaborators': 8,
        'plan': {
            'name': 'Medium',
            'space': 400,
            'collaborators': 10,
            'private_repos': 20
        }
    })

    def setUp(self):
        HTTPretty.enable()
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        self.backend = module_member('social.backends.github.GithubOAuth2')
        self.strategy = TestStrategy(self.backend, TestStorage)
        self.user = None

    def tearDown(self):
        self.backend = None
        self.strategy = None
        self.user = None
        User.reset_cache()
        User.set_active(True)
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        HTTPretty.disable()

    def do_login(self, after_complete_checks=True, user_data_body=None,
                 expected_username=None):
        self.strategy.set_settings({
            'SOCIAL_AUTH_GITHUB_KEY': 'a-key',
            'SOCIAL_AUTH_GITHUB_SECRET': 'a-secret-key',
            'SOCIAL_AUTH_LOGIN_REDIRECT_URL': self.login_redirect_url,
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
                'social.backends.github.GithubOAuth2',
            )
        })
        start_url = do_auth(self.strategy).url
        target_url = self.strategy.build_absolute_uri(
            '/complete/github/?code=foobar'
        )

        start_query = parse_qs(urlparse(start_url).query)
        location_url = target_url + ('?' in target_url and '&' or '?') + \
                       'state=' + start_query['state']
        location_query = parse_qs(urlparse(location_url).query)

        HTTPretty.register_uri(HTTPretty.GET, start_url, status=301,
                               location=location_url)
        HTTPretty.register_uri(HTTPretty.GET, location_url, status=200,
                               body='foobar')

        response = requests.get(start_url)
        expect(response.url).to.equal(location_url)
        expect(response.text).to.equal('foobar')

        HTTPretty.register_uri(HTTPretty.GET,
                               uri=self.backend.ACCESS_TOKEN_URL,
                               status=200,
                               body=self.access_token_body or '',
                               content_type='text/json')

        if self.user_data_url:
            user_data_body = user_data_body or self.user_data_body or ''
            HTTPretty.register_uri(HTTPretty.GET, self.user_data_url,
                                   body=user_data_body,
                                   content_type='text/json')
        self.strategy.set_request_data(location_query)
        redirect = do_complete(
            self.strategy,
            user=self.user,
            login=lambda strategy, user, social_user:
                    strategy.session_set('username', user.username)
        )
        if after_complete_checks:
            expect(self.strategy.session_get('username')).to.equal(
                expected_username or self.expected_username
            )
            expect(redirect.url).to.equal(self.login_redirect_url)
        return redirect

    def do_login_with_partial_pipeline(self, before_complete=None):
        self.strategy.set_settings({
            'SOCIAL_AUTH_GITHUB_KEY': 'a-key',
            'SOCIAL_AUTH_GITHUB_SECRET': 'a-secret-key',
            'SOCIAL_AUTH_LOGIN_REDIRECT_URL': self.login_redirect_url,
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
                'social.backends.github.GithubOAuth2',
            ),
            'SOCIAL_AUTH_PIPELINE': (
                'social.pipeline.social_auth.social_details',
                'social.pipeline.social_auth.social_uid',
                'social.pipeline.social_auth.auth_allowed',
                'social.pipeline.partial.save_status_to_session',
                'social.tests.pipeline.ask_for_password',
                'social.pipeline.social_auth.social_user',
                'social.pipeline.user.get_username',
                'social.pipeline.user.create_user',
                'social.pipeline.social_auth.associate_user',
                'social.pipeline.social_auth.load_extra_data',
                'social.tests.pipeline.set_password',
                'social.pipeline.user.user_details'
            )
        })
        start_url = do_auth(self.strategy).url
        target_url = self.strategy.build_absolute_uri(
            '/complete/github/?code=foobar'
        )

        start_query = parse_qs(urlparse(start_url).query)
        location_url = target_url + ('?' in target_url and '&' or '?') + \
                       'state=' + start_query['state']
        location_query = parse_qs(urlparse(location_url).query)

        HTTPretty.register_uri(HTTPretty.GET, start_url, status=301,
                               location=location_url)
        HTTPretty.register_uri(HTTPretty.GET, location_url, status=200,
                               body='foobar')

        response = requests.get(start_url)
        expect(response.url).to.equal(location_url)
        expect(response.text).to.equal('foobar')

        HTTPretty.register_uri(HTTPretty.GET,
                               uri=self.backend.ACCESS_TOKEN_URL,
                               status=200,
                               body=self.access_token_body or '',
                               content_type='text/json')

        if self.user_data_url:
            HTTPretty.register_uri(HTTPretty.GET, self.user_data_url,
                                   body=self.user_data_body or '',
                                   content_type='text/json')
        self.strategy.set_request_data(location_query)

        def _login(strategy, user, social_user):
            strategy.session_set('username', user.username)

        redirect = do_complete(self.strategy, user=self.user, login=_login)
        url = self.strategy.build_absolute_uri('/password')
        expect(redirect.url).to.equal(url)
        HTTPretty.register_uri(HTTPretty.GET, redirect.url, status=200,
                               body='foobar')
        HTTPretty.register_uri(HTTPretty.POST, redirect.url, status=200)

        password = '******'
        requests.get(url)
        requests.post(url, data={'password': password})
        data = parse_qs(HTTPretty.last_request.body)
        expect(data['password']).to.equal(password)
        self.strategy.session_set('password', data['password'])

        if before_complete:
            before_complete()
        redirect = do_complete(self.strategy, user=self.user, login=_login)
        expect(self.strategy.session_get('username')).to.equal(
            self.expected_username
        )
        expect(redirect.url).to.equal(self.login_redirect_url)
예제 #15
0
파일: base.py 프로젝트: 2070616d/TP3
class BaseBackendTest(unittest.TestCase):
    backend = None
    backend_path = None
    name = None
    complete_url = ''
    raw_complete_url = '/complete/{0}'

    def setUp(self):
        HTTPretty.enable()
        Backend = module_member(self.backend_path)
        self.strategy = TestStrategy(TestStorage)
        self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
        self.name = self.backend.name.upper().replace('-', '_')
        self.complete_url = self.strategy.build_absolute_uri(
            self.raw_complete_url.format(self.backend.name)
        )
        backends = (self.backend_path,
                    'social.tests.backends.test_broken.BrokenBackendAuth')
        self.strategy.set_settings({
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': backends
        })
        self.strategy.set_settings(self.extra_settings())
        # Force backends loading to trash PSA cache
        load_backends(backends, force_load=True)
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        TestCode.reset_cache()

    def tearDown(self):
        HTTPretty.disable()
        self.backend = None
        self.strategy = None
        self.name = None
        self.complete_url = None
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        TestCode.reset_cache()

    def extra_settings(self):
        return {}

    def do_start(self):
        raise NotImplementedError('Implement in subclass')

    def do_login(self):
        user = self.do_start()
        username = self.expected_username
        self.assertEqual(user.username, username)
        self.assertEqual(self.strategy.session_get('username'), username)
        self.assertEqual(self.strategy.get_user(user.id), user)
        self.assertEqual(self.backend.get_user(user.id), user)
        user_backends = user_backends_data(
            user,
            self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
            self.strategy.storage
        )
        self.assertEqual(len(list(user_backends.keys())), 3)
        self.assertEqual('associated' in user_backends, True)
        self.assertEqual('not_associated' in user_backends, True)
        self.assertEqual('backends' in user_backends, True)
        self.assertEqual(len(user_backends['associated']), 1)
        self.assertEqual(len(user_backends['not_associated']), 1)
        self.assertEqual(len(user_backends['backends']), 2)
        return user

    def pipeline_settings(self):
        self.strategy.set_settings({
            'SOCIAL_AUTH_PIPELINE': (
                'social.pipeline.social_auth.social_details',
                'social.pipeline.social_auth.social_uid',
                'social.pipeline.social_auth.auth_allowed',
                'social.pipeline.partial.save_status_to_session',
                'social.tests.pipeline.ask_for_password',
                'social.tests.pipeline.ask_for_slug',
                'social.pipeline.social_auth.social_user',
                'social.pipeline.user.get_username',
                'social.pipeline.social_auth.associate_by_email',
                'social.pipeline.user.create_user',
                'social.pipeline.social_auth.associate_user',
                'social.pipeline.social_auth.load_extra_data',
                'social.tests.pipeline.set_password',
                'social.tests.pipeline.set_slug',
                'social.pipeline.user.user_details'
            )
        })

    def pipeline_handlers(self, url):
        HTTPretty.register_uri(HTTPretty.GET, url, status=200, body='foobar')
        HTTPretty.register_uri(HTTPretty.POST, url, status=200)

    def pipeline_password_handling(self, url):
        password = '******'
        requests.get(url)
        requests.post(url, data={'password': password})

        data = parse_qs(HTTPretty.last_request.body)
        self.assertEqual(data['password'], password)
        self.strategy.session_set('password', data['password'])
        return password

    def pipeline_slug_handling(self, url):
        slug = 'foo-bar'
        requests.get(url)
        requests.post(url, data={'slug': slug})

        data = parse_qs(HTTPretty.last_request.body)
        self.assertEqual(data['slug'], slug)
        self.strategy.session_set('slug', data['slug'])
        return slug

    def do_partial_pipeline(self):
        url = self.strategy.build_absolute_uri('/password')
        self.pipeline_settings()
        redirect = self.do_start()
        self.assertEqual(redirect.url, url)
        self.pipeline_handlers(url)

        password = self.pipeline_password_handling(url)
        data = self.strategy.session_pop('partial_pipeline')
        idx, backend, xargs, xkwargs = self.strategy.partial_from_session(data)
        self.assertEqual(backend, self.backend.name)
        redirect = self.backend.continue_pipeline(pipeline_index=idx,
                                                  *xargs, **xkwargs)

        url = self.strategy.build_absolute_uri('/slug')
        self.assertEqual(redirect.url, url)
        self.pipeline_handlers(url)
        slug = self.pipeline_slug_handling(url)

        data = self.strategy.session_pop('partial_pipeline')
        idx, backend, xargs, xkwargs = self.strategy.partial_from_session(data)
        self.assertEqual(backend, self.backend.name)
        user = self.backend.continue_pipeline(pipeline_index=idx,
                                              *xargs, **xkwargs)

        self.assertEqual(user.username, self.expected_username)
        self.assertEqual(user.slug, slug)
        self.assertEqual(user.password, password)
        return user
예제 #16
0
 def setUp(self):
     self.strategy = TestStrategy(UnknownErrorStorage)
     super(UnknownErrorOnLoginTest, self).setUp()
예제 #17
0
 def setUp(self):
     self.strategy = TestStrategy(IntegrityErrorStorage)
     super(IntegrityErrorOnLoginTest, self).setUp()
예제 #18
0
class OpenIdTest(BaseBackendTest):
    backend_path = None
    backend = None
    access_token_body = None
    user_data_body = None
    user_data_url = ''
    expected_username = ''
    settings = None
    partial_login_settings = None
    raw_complete_url = '/complete/{0}/'

    def setUp(self):
        HTTPretty.enable()
        self.backend = module_member(self.backend_path)
        name = self.backend.name
        self.complete_url = self.raw_complete_url.format(name)
        self.strategy = TestStrategy(self.backend,
                                     TestStorage,
                                     redirect_uri=self.complete_url)
        self.strategy.set_settings({
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
            (self.backend_path,
             'social.tests.backends.test_broken.BrokenBackendAuth')
        })
        # Force backends loading to trash PSA cache
        load_backends(
            self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
            force_load=True)

    def tearDown(self):
        self.strategy = None
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        HTTPretty.disable()

    def get_form_data(self, html):
        parser = FormHTMLParser()
        parser.feed(html)
        return parser.form, parser.inputs

    def openid_url(self):
        return self.strategy.backend.openid_url()

    def post_start(self):
        pass

    def do_start(self):
        HTTPretty.register_uri(HTTPretty.GET,
                               self.openid_url(),
                               status=200,
                               body=self.discovery_body,
                               content_type='application/xrds+xml')
        start = self.strategy.start()
        self.post_start()
        form, inputs = self.get_form_data(start)
        HTTPretty.register_uri(HTTPretty.POST,
                               form.get('action'),
                               status=200,
                               body=self.server_response)
        response = requests.post(form.get('action'), data=inputs)
        self.strategy.set_request_data(parse_qs(response.content))
        HTTPretty.register_uri(HTTPretty.POST,
                               form.get('action'),
                               status=200,
                               body='is_valid:true\n')
        return self.strategy.complete()
예제 #19
0
class BaseActionTest(unittest.TestCase):
    user_data_url = 'https://api.github.com/user'
    login_redirect_url = '/success'
    expected_username = '******'
    access_token_body = json.dumps({
        'access_token': 'foobar',
        'token_type': 'bearer'
    })
    user_data_body = json.dumps({
        'login': '******',
        'id': 1,
        'avatar_url': 'https://github.com/images/error/foobar_happy.gif',
        'gravatar_id': 'somehexcode',
        'url': 'https://api.github.com/users/foobar',
        'name': 'monalisa foobar',
        'company': 'GitHub',
        'blog': 'https://github.com/blog',
        'location': 'San Francisco',
        'email': '*****@*****.**',
        'hireable': False,
        'bio': 'There once was...',
        'public_repos': 2,
        'public_gists': 1,
        'followers': 20,
        'following': 0,
        'html_url': 'https://github.com/foobar',
        'created_at': '2008-01-14T04:33:35Z',
        'type': 'User',
        'total_private_repos': 100,
        'owned_private_repos': 100,
        'private_gists': 81,
        'disk_usage': 10000,
        'collaborators': 8,
        'plan': {
            'name': 'Medium',
            'space': 400,
            'collaborators': 10,
            'private_repos': 20
        }
    })

    def setUp(self):
        HTTPretty.enable()
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        self.backend = module_member('social.backends.github.GithubOAuth2')
        self.strategy = TestStrategy(self.backend, TestStorage)
        self.user = None

    def tearDown(self):
        self.backend = None
        self.strategy = None
        self.user = None
        User.reset_cache()
        User.set_active(True)
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        HTTPretty.disable()

    def do_login(self,
                 after_complete_checks=True,
                 user_data_body=None,
                 expected_username=None):
        self.strategy.set_settings({
            'SOCIAL_AUTH_GITHUB_KEY':
            'a-key',
            'SOCIAL_AUTH_GITHUB_SECRET':
            'a-secret-key',
            'SOCIAL_AUTH_LOGIN_REDIRECT_URL':
            self.login_redirect_url,
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
            ('social.backends.github.GithubOAuth2', )
        })
        start_url = do_auth(self.strategy).url
        target_url = self.strategy.build_absolute_uri(
            '/complete/github/?code=foobar')

        start_query = parse_qs(urlparse(start_url).query)
        location_url = target_url + ('?' in target_url and '&' or '?') + \
                       'state=' + start_query['state']
        location_query = parse_qs(urlparse(location_url).query)

        HTTPretty.register_uri(HTTPretty.GET,
                               start_url,
                               status=301,
                               location=location_url)
        HTTPretty.register_uri(HTTPretty.GET,
                               location_url,
                               status=200,
                               body='foobar')

        response = requests.get(start_url)
        expect(response.url).to.equal(location_url)
        expect(response.text).to.equal('foobar')

        HTTPretty.register_uri(HTTPretty.GET,
                               uri=self.backend.ACCESS_TOKEN_URL,
                               status=200,
                               body=self.access_token_body or '',
                               content_type='text/json')

        if self.user_data_url:
            user_data_body = user_data_body or self.user_data_body or ''
            HTTPretty.register_uri(HTTPretty.GET,
                                   self.user_data_url,
                                   body=user_data_body,
                                   content_type='text/json')
        self.strategy.set_request_data(location_query)
        redirect = do_complete(self.strategy,
                               user=self.user,
                               login=lambda strategy, user, social_user:
                               strategy.session_set('username', user.username))
        if after_complete_checks:
            expect(self.strategy.session_get('username')).to.equal(
                expected_username or self.expected_username)
            expect(redirect.url).to.equal(self.login_redirect_url)
        return redirect

    def do_login_with_partial_pipeline(self, before_complete=None):
        self.strategy.set_settings({
            'SOCIAL_AUTH_GITHUB_KEY':
            'a-key',
            'SOCIAL_AUTH_GITHUB_SECRET':
            'a-secret-key',
            'SOCIAL_AUTH_LOGIN_REDIRECT_URL':
            self.login_redirect_url,
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
            ('social.backends.github.GithubOAuth2', ),
            'SOCIAL_AUTH_PIPELINE':
            ('social.pipeline.social_auth.social_details',
             'social.pipeline.social_auth.social_uid',
             'social.pipeline.social_auth.auth_allowed',
             'social.pipeline.partial.save_status_to_session',
             'social.tests.pipeline.ask_for_password',
             'social.pipeline.social_auth.social_user',
             'social.pipeline.user.get_username',
             'social.pipeline.user.create_user',
             'social.pipeline.social_auth.associate_user',
             'social.pipeline.social_auth.load_extra_data',
             'social.tests.pipeline.set_password',
             'social.pipeline.user.user_details')
        })
        start_url = do_auth(self.strategy).url
        target_url = self.strategy.build_absolute_uri(
            '/complete/github/?code=foobar')

        start_query = parse_qs(urlparse(start_url).query)
        location_url = target_url + ('?' in target_url and '&' or '?') + \
                       'state=' + start_query['state']
        location_query = parse_qs(urlparse(location_url).query)

        HTTPretty.register_uri(HTTPretty.GET,
                               start_url,
                               status=301,
                               location=location_url)
        HTTPretty.register_uri(HTTPretty.GET,
                               location_url,
                               status=200,
                               body='foobar')

        response = requests.get(start_url)
        expect(response.url).to.equal(location_url)
        expect(response.text).to.equal('foobar')

        HTTPretty.register_uri(HTTPretty.GET,
                               uri=self.backend.ACCESS_TOKEN_URL,
                               status=200,
                               body=self.access_token_body or '',
                               content_type='text/json')

        if self.user_data_url:
            HTTPretty.register_uri(HTTPretty.GET,
                                   self.user_data_url,
                                   body=self.user_data_body or '',
                                   content_type='text/json')
        self.strategy.set_request_data(location_query)

        def _login(strategy, user, social_user):
            strategy.session_set('username', user.username)

        redirect = do_complete(self.strategy, user=self.user, login=_login)
        url = self.strategy.build_absolute_uri('/password')
        expect(redirect.url).to.equal(url)
        HTTPretty.register_uri(HTTPretty.GET,
                               redirect.url,
                               status=200,
                               body='foobar')
        HTTPretty.register_uri(HTTPretty.POST, redirect.url, status=200)

        password = '******'
        requests.get(url)
        requests.post(url, data={'password': password})
        data = parse_qs(HTTPretty.last_request.body)
        expect(data['password']).to.equal(password)
        self.strategy.session_set('password', data['password'])

        if before_complete:
            before_complete()
        redirect = do_complete(self.strategy, user=self.user, login=_login)
        expect(self.strategy.session_get('username')).to.equal(
            self.expected_username)
        expect(redirect.url).to.equal(self.login_redirect_url)
예제 #20
0
class BaseBackendTest(unittest.TestCase):
    backend = None
    backend_path = None
    name = None
    complete_url = ""
    raw_complete_url = "/complete/{0}"

    def setUp(self):
        HTTPretty.enable()
        self.backend = module_member(self.backend_path)
        self.strategy = TestStrategy(self.backend, TestStorage)
        self.name = self.backend.name.upper().replace("-", "_")
        self.complete_url = self.strategy.build_absolute_uri(self.raw_complete_url.format(self.backend.name))
        backends = (self.backend_path, "social.tests.backends.test_broken.BrokenBackendAuth")
        self.strategy.set_settings({"SOCIAL_AUTH_AUTHENTICATION_BACKENDS": backends})
        self.strategy.set_settings(self.extra_settings())
        # Force backends loading to trash PSA cache
        load_backends(backends, force_load=True)
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        TestCode.reset_cache()

    def tearDown(self):
        HTTPretty.disable()
        self.backend = None
        self.strategy = None
        self.name = None
        self.complete_url = None
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        TestCode.reset_cache()

    def extra_settings(self):
        return {}

    def do_start(self):
        raise NotImplementedError("Implement in subclass")

    def do_login(self):
        user = self.do_start()
        username = self.expected_username
        expect(user.username).to.equal(username)
        expect(self.strategy.session_get("username")).to.equal(username)
        expect(self.strategy.get_user(user.id)).to.equal(user)
        expect(self.strategy.backend.get_user(user.id)).to.equal(user)
        user_backends = user_backends_data(
            user, self.strategy.get_setting("SOCIAL_AUTH_AUTHENTICATION_BACKENDS"), self.strategy.storage
        )
        expect(len(list(user_backends.keys()))).to.equal(3)
        expect("associated" in user_backends).to.equal(True)
        expect("not_associated" in user_backends).to.equal(True)
        expect("backends" in user_backends).to.equal(True)
        expect(len(user_backends["associated"])).to.equal(1)
        expect(len(user_backends["not_associated"])).to.equal(1)
        expect(len(user_backends["backends"])).to.equal(2)
        return user

    def pipeline_settings(self):
        self.strategy.set_settings(
            {
                "SOCIAL_AUTH_PIPELINE": (
                    "social.pipeline.social_auth.social_details",
                    "social.pipeline.social_auth.social_uid",
                    "social.pipeline.social_auth.auth_allowed",
                    "social.pipeline.partial.save_status_to_session",
                    "social.tests.pipeline.ask_for_password",
                    "social.tests.pipeline.ask_for_slug",
                    "social.pipeline.social_auth.social_user",
                    "social.pipeline.user.get_username",
                    "social.pipeline.social_auth.associate_by_email",
                    "social.pipeline.user.create_user",
                    "social.pipeline.social_auth.associate_user",
                    "social.pipeline.social_auth.load_extra_data",
                    "social.tests.pipeline.set_password",
                    "social.tests.pipeline.set_slug",
                    "social.pipeline.user.user_details",
                )
            }
        )

    def pipeline_handlers(self, url):
        HTTPretty.register_uri(HTTPretty.GET, url, status=200, body="foobar")
        HTTPretty.register_uri(HTTPretty.POST, url, status=200)

    def pipeline_password_handling(self, url):
        password = "******"
        requests.get(url)
        requests.post(url, data={"password": password})

        data = parse_qs(HTTPretty.last_request.body)
        expect(data["password"]).to.equal(password)
        self.strategy.session_set("password", data["password"])
        return password

    def pipeline_slug_handling(self, url):
        slug = "foo-bar"
        requests.get(url)
        requests.post(url, data={"slug": slug})

        data = parse_qs(HTTPretty.last_request.body)
        expect(data["slug"]).to.equal(slug)
        self.strategy.session_set("slug", data["slug"])
        return slug

    def do_partial_pipeline(self):
        url = self.strategy.build_absolute_uri("/password")
        self.pipeline_settings()
        redirect = self.do_start()
        expect(redirect.url).to.equal(url)
        self.pipeline_handlers(url)

        password = self.pipeline_password_handling(url)
        data = self.strategy.session_pop("partial_pipeline")
        idx, backend, xargs, xkwargs = self.strategy.partial_from_session(data)
        expect(backend).to.equal(self.backend.name)
        redirect = self.strategy.continue_pipeline(pipeline_index=idx, *xargs, **xkwargs)

        url = self.strategy.build_absolute_uri("/slug")
        expect(redirect.url).to.equal(url)
        self.pipeline_handlers(url)
        slug = self.pipeline_slug_handling(url)

        data = self.strategy.session_pop("partial_pipeline")
        idx, backend, xargs, xkwargs = self.strategy.partial_from_session(data)
        expect(backend).to.equal(self.backend.name)
        user = self.strategy.continue_pipeline(pipeline_index=idx, *xargs, **xkwargs)

        expect(user.username).to.equal(self.expected_username)
        expect(user.slug).to.equal(slug)
        expect(user.password).to.equal(password)
        return user
예제 #21
0
class BaseBackendTest(unittest.TestCase):
    backend = None
    backend_path = None
    name = None
    complete_url = ''
    raw_complete_url = '/complete/{0}'

    def setUp(self):
        HTTPretty.enable()
        Backend = module_member(self.backend_path)
        self.strategy = TestStrategy(TestStorage)
        self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
        self.name = self.backend.name.upper().replace('-', '_')
        self.complete_url = self.strategy.build_absolute_uri(
            self.raw_complete_url.format(self.backend.name))
        backends = (self.backend_path,
                    'social.tests.backends.test_broken.BrokenBackendAuth')
        self.strategy.set_settings(
            {'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': backends})
        self.strategy.set_settings(self.extra_settings())
        # Force backends loading to trash PSA cache
        load_backends(backends, force_load=True)
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        TestCode.reset_cache()

    def tearDown(self):
        HTTPretty.disable()
        self.backend = None
        self.strategy = None
        self.name = None
        self.complete_url = None
        User.reset_cache()
        TestUserSocialAuth.reset_cache()
        TestNonce.reset_cache()
        TestAssociation.reset_cache()
        TestCode.reset_cache()

    def extra_settings(self):
        return {}

    def do_start(self):
        raise NotImplementedError('Implement in subclass')

    def do_login(self):
        user = self.do_start()
        username = self.expected_username
        self.assertEqual(user.username, username)
        self.assertEqual(self.strategy.session_get('username'), username)
        self.assertEqual(self.strategy.get_user(user.id), user)
        self.assertEqual(self.backend.get_user(user.id), user)
        user_backends = user_backends_data(
            user,
            self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
            self.strategy.storage)
        self.assertEqual(len(list(user_backends.keys())), 3)
        self.assertEqual('associated' in user_backends, True)
        self.assertEqual('not_associated' in user_backends, True)
        self.assertEqual('backends' in user_backends, True)
        self.assertEqual(len(user_backends['associated']), 1)
        self.assertEqual(len(user_backends['not_associated']), 1)
        self.assertEqual(len(user_backends['backends']), 2)
        return user

    def pipeline_settings(self):
        self.strategy.set_settings({
            'SOCIAL_AUTH_PIPELINE':
            ('social.pipeline.social_auth.social_details',
             'social.pipeline.social_auth.social_uid',
             'social.pipeline.social_auth.auth_allowed',
             'social.pipeline.partial.save_status_to_session',
             'social.tests.pipeline.ask_for_password',
             'social.tests.pipeline.ask_for_slug',
             'social.pipeline.social_auth.social_user',
             'social.pipeline.user.get_username',
             'social.pipeline.social_auth.associate_by_email',
             'social.pipeline.user.create_user',
             'social.pipeline.social_auth.associate_user',
             'social.pipeline.social_auth.load_extra_data',
             'social.tests.pipeline.set_password',
             'social.tests.pipeline.set_slug',
             'social.pipeline.user.user_details')
        })

    def pipeline_handlers(self, url):
        HTTPretty.register_uri(HTTPretty.GET, url, status=200, body='foobar')
        HTTPretty.register_uri(HTTPretty.POST, url, status=200)

    def pipeline_password_handling(self, url):
        password = '******'
        requests.get(url)
        requests.post(url, data={'password': password})

        data = parse_qs(HTTPretty.last_request.body)
        self.assertEqual(data['password'], password)
        self.strategy.session_set('password', data['password'])
        return password

    def pipeline_slug_handling(self, url):
        slug = 'foo-bar'
        requests.get(url)
        requests.post(url, data={'slug': slug})

        data = parse_qs(HTTPretty.last_request.body)
        self.assertEqual(data['slug'], slug)
        self.strategy.session_set('slug', data['slug'])
        return slug

    def do_partial_pipeline(self):
        url = self.strategy.build_absolute_uri('/password')
        self.pipeline_settings()
        redirect = self.do_start()
        self.assertEqual(redirect.url, url)
        self.pipeline_handlers(url)

        password = self.pipeline_password_handling(url)
        data = self.strategy.session_pop('partial_pipeline')
        idx, backend, xargs, xkwargs = self.strategy.partial_from_session(data)
        self.assertEqual(backend, self.backend.name)
        redirect = self.backend.continue_pipeline(pipeline_index=idx,
                                                  *xargs,
                                                  **xkwargs)

        url = self.strategy.build_absolute_uri('/slug')
        self.assertEqual(redirect.url, url)
        self.pipeline_handlers(url)
        slug = self.pipeline_slug_handling(url)

        data = self.strategy.session_pop('partial_pipeline')
        idx, backend, xargs, xkwargs = self.strategy.partial_from_session(data)
        self.assertEqual(backend, self.backend.name)
        user = self.backend.continue_pipeline(pipeline_index=idx,
                                              *xargs,
                                              **xkwargs)

        self.assertEqual(user.username, self.expected_username)
        self.assertEqual(user.slug, slug)
        self.assertEqual(user.password, password)
        return user
예제 #22
0
파일: tests.py 프로젝트: saulm/Saul2005
 def test_require_email(self):
     backend = module_member('social.backends.facebook.FacebookOAuth2')
     strategy = TestStrategy(backend=backend, storage=TestStorage)
     details = {}