示例#1
0
class AccountsTest(TestCase):
    fixtures = [
        'roles.json', 'test_l10n_data.json', 'app_roles.json',
        'test_organisation_data.json', 'test_app_roles.json',
        'test_user_data.json'
    ]

    def setUp(self):
        self.client = SSOClient()

    def tearDown(self):
        pass

    def test_app_admin_user_list(self):
        result = self.client.login(username='******', password='******')
        self.assertEqual(result, True)

        response = self.client.get(
            reverse('accounts:app_admin_user_list'),
            data={'country': OrganisationCountry.objects.first().pk})
        self.assertEqual(response.status_code, 200)

        response = self.client.get(reverse('accounts:app_admin_user_list'),
                                   data={'country': 99999})
        self.assertEqual(response.status_code, 200)

    def test_app_admin_update_user(self):
        result = self.client.login(username='******', password='******')
        self.assertEqual(result, True)

        # User.objects.get()
        response = self.client.get(reverse('accounts:app_admin_user_list'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(
            response,
            reverse('accounts:app_admin_update_user',
                    kwargs={'uuid': 'a8992f0348634f76b0dac2de4e4c83ee'}))

        response = self.client.get(
            reverse('accounts:app_admin_update_user',
                    kwargs={'uuid': 'a8992f0348634f76b0dac2de4e4c83ee'}))
        self.assertEqual(response.status_code, 200)
示例#2
0
 def setUp(self):
     os.environ['RECAPTCHA_TESTING'] = 'True'
     self.client = SSOClient()
示例#3
0
class RegistrationTest(TestCase):
    fixtures = [
        'roles.json', 'app_roles.json', 'test_l10n_data.json',
        'test_organisation_data.json', 'test_app_roles.json',
        'test_user_data.json'
    ]

    def setUp(self):
        os.environ['RECAPTCHA_TESTING'] = 'True'
        self.client = SSOClient()

    def tearDown(self):
        del os.environ['RECAPTCHA_TESTING']

    def get_url_path_from_mail(self):
        outbox = getattr(mail, 'outbox')
        self.assertGreater(len(outbox), 0)
        urls = re.findall(
            'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
            outbox[-1].body)
        self.assertEqual(len(urls), 1)
        scheme, netloc, path, query_string, fragment = urlsplit(
            urls[0])  # @UnusedVariable
        return path

    def test_default_username_generator(self):
        username = default_username_generator("Gunnar", "Scherf")
        self.assertEqual(username, "GunnarScherf1")

        username = default_username_generator("Hans", "Meier")
        self.assertEqual(username, "HansMeier")

        username = default_username_generator(
            "1234567890", "12345678901234567890123456789012345678901234567890"
            "1234567890")
        self.assertEqual(
            username,
            "123456789012345678901234567890123456789012345678901234567890123456789"
        )

    @override_settings(
        RECAPTCHA_PUBLIC_KEY='6LccjewSAAAAAPcFZmUtuzRVkU6hhOona0orqgKh',
        RECAPTCHA_PRIVATE_KEY='6LccjewSAAAAAAhJzHuEyVV40AYApL6CpmjqlmX8')
    def test_registration_register_by_bot(self):
        """
        User self registration with email validation
        """
        data = {
            'email': '*****@*****.**',
            'email2': '*****@*****.**',
            'first_name': 'first_name',
            'last_name': 'last_name',
            'known_person1_first_name': 'known_person1_first_name',
            'known_person2_first_name': 'known_person2_first_name',
            'known_person1_last_name': 'known_person1_last_name',
            'known_person2_last_name': 'known_person2_last_name',
            'country': 81,
            'city': 'Megacity',
            'g-recaptcha-response': 'xyz'
        }
        response = self.client.post(
            reverse('registration:registration_register'), data=data)
        self.assertFormError(response, 'form', 'captcha',
                             ['Error verifying reCAPTCHA, please try again.'])

    def test_registration(self):
        """
        User self registration with email validation
        """
        response = self.client.get(
            reverse('registration:registration_register'))
        self.assertEqual(response.status_code, 200)
        organisation = Organisation.objects.filter(is_active=True).first()

        data = {
            'email': '*****@*****.**',
            'email2': '*****@*****.**',
            'picture':
            "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wgARCABVAFUDASIAAhEBAxEB/8QAGwABAAMBAQEBAAAAAAAAAAAAAAMEBQIB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PUWsYoeqVymJMBZtJhiWo+rqGDEYSnm+tHtOiMZrJkhNpqeFoMDIh6rVgINwz/DjG2aKKEXYvdQCQguznhIEfLhEAzRstSTlMgXHyBfyxow5rRVkQk6PRwQsSl6jxjbNFORkEJqUz0Ilc4+yGnT7lA8iTJjlLTwNIahLiEl298VvRHewphLTAP4aUwCmTMWzPYq9Zn3ASmVymMJkm+X2PGNs0cJrDDYgacz5q5dSHANdXaoNtQc/ekiABKrhV5CJHHkctWl4Gwc/pxjbNHFCiaYbmqa8yroB4OfpQEWnN++l4KYtP9PWlpCNa5cjl4I2zR/OPJ21mCJ/kiIiIiI+w4mORpX/2Q==",
            'first_name': 'first_name',
            'last_name': 'last_name',
            'known_person1_first_name': 'known_person1_first_name',
            'known_person2_first_name': 'known_person2_first_name',
            'known_person1_last_name': 'known_person1_last_name',
            'known_person2_last_name': 'known_person2_last_name',
            'about_me': 'Test',
            'country': 81,
            'city': 'Megacity',
            'organisation': organisation.pk,
            'g-recaptcha-response': 'PASSED'
        }
        for user_extra_attribute in settings.SSO_TEST_USER_EXTRA_ATTRIBUTES:
            data[user_extra_attribute['name']] = user_extra_attribute['value']

        response = self.client.post(
            reverse('registration:registration_register'), data=data)
        self.assertNotContains(response, 'is-invalid')

        # captcha is only displayed once.
        # the second time a signed value is used
        del data['g-recaptcha-response']
        data['state'] = response.context['form'].data['state']

        data[response.context['stage_field']] = "2"
        data[response.context['hash_field']] = response.context['hash_value']

        response = self.client.post(
            reverse('registration:registration_register'), data=data)
        self.assertEqual(response.status_code, 302)

        path = self.get_url_path_from_mail()
        response = self.client.post(path)
        self.assertEqual(response.status_code, 302)

        response = self.client.get(response['Location'])
        self.assertEqual(response.status_code, 200)

    def test_registration_list(self):
        # admin logs in
        self.client.login(username='******', password='******')
        response = self.client.get(
            reverse('registration:user_registration_list'))
        self.assertEqual(response.status_code, 200)
示例#4
0
文件: tests.py 项目: g10f/sso
 def setUp(self):
     self.client = SSOClient()
示例#5
0
文件: tests.py 项目: g10f/sso
class OAuth2BaseTestCase(TestCase):
    fixtures = [
        'roles.json', 'test_l10n_data.json', 'test_organisation_data.json',
        'app_roles.json', 'test_app_roles.json', 'test_user_data.json',
        'test_oauth2_data.json'
    ]
    _client_id = "ec1e39cbe3e746c787b770ace4165d13"
    _state = 'eyJub25jZSI6Ik1sSllaUlc3VWdGdyIsInByb3ZpZGVyIjoyLCJuZXh0IjoiLyJ9'

    def setUp(self):
        self.client = SSOClient()

    def logout(self):
        self.client.logout()
        self.client.cookies = SimpleCookie()

    def login_and_get_code(self,
                           client_id=None,
                           max_age=None,
                           wait=0,
                           username='******',
                           password='******',
                           scope="openid profile email",
                           code_challenge=None,
                           code_challenge_method=None,
                           should_succeed=True):
        self.client.login(username=username, password=password)
        if wait > 0:
            sleep(wait)

        authorize_data = {
            'scope': scope,
            'state': self._state,
            'redirect_uri': "http://localhost",
            'response_type': "code",
            'client_id': client_id if client_id else self._client_id,
        }
        if max_age:
            authorize_data['max_age'] = max_age
        if code_challenge:
            authorize_data['code_challenge'] = code_challenge
        if code_challenge_method:
            authorize_data['code_challenge_method'] = code_challenge_method

        response = self.client.get(reverse('oauth2:authorize'),
                                   data=authorize_data)
        self.assertEqual(response.status_code, 302)
        query_dict = get_query_dict(response['Location'])
        self.assertTrue(
            set({
                'state': self._state
            }.items()).issubset(set(query_dict.items())))
        if should_succeed:
            self.assertIn('code', query_dict)
            return query_dict['code']
        return query_dict

    def login_and_get_implicit_id_token(
            self,
            client_id='92d7d9d71d5d41caa652080c19aaa6d8',
            max_age=None,
            wait=0,
            username='******',
            password='******',
            response_type="id_token token"):
        self.client.login(username=username, password=password)
        if wait > 0:
            sleep(wait)

        authorize_data = {
            'scope': "openid profile email",
            'state': self._state,
            'nonce': get_random_string(12),
            'redirect_uri': "http://localhost",
            'response_type': response_type,
            'client_id': client_id,
        }
        if max_age:
            authorize_data['max_age'] = max_age

        response = self.client.get(reverse('oauth2:authorize'),
                                   data=authorize_data)
        self.assertEqual(response.status_code, 302)
        fragment_dict = get_fragment_dict(response['Location'])

        self.assertIn('id_token', fragment_dict)
        expected = {'state': self._state}
        self.assertTrue(
            set(expected.items()).issubset(set(fragment_dict.items())))
        return fragment_dict

    def get_authorization(self,
                          client_id=None,
                          username='******',
                          password='******',
                          scope="openid profile email"):
        code = self.login_and_get_code(client_id,
                                       username=username,
                                       password=password,
                                       scope=scope)
        token_data = {
            'grant_type': "authorization_code",
            'redirect_uri': "http://localhost",
            'client_secret': "geheim",
            'client_id': client_id if client_id else self._client_id,
            'code': code
        }
        token_response = self.token_request(token_data)
        self.assertEqual(token_response.status_code, 200)
        self.assertIn('application/json', token_response['Content-Type'])
        token = token_response.json()
        self.logout()
        return 'Bearer %s' % token['access_token']

    def get_http_authorization(self, data):
        if 'client_secret' in data and data['client_secret']:
            auth = b"%s:%s" % (data['client_id'].encode(),
                               data['client_secret'].encode())
            del data['client_id']
            del data['client_secret']
            return '%s %s' % ('Basic', base64.b64encode(auth).decode("ascii"))
        else:
            return None

    def token_request(self, token_data):
        data = token_data.copy()
        authorization = self.get_http_authorization(data)
        return self.client.post(reverse('oauth2:token'),
                                data,
                                HTTP_AUTHORIZATION=authorization)
示例#6
0
文件: tests.py 项目: g10f/sso
class OrganisationsTest(TransactionTestCase):
    fixtures = [
        'roles.json', 'app_roles.json', 'test_l10n_data.json',
        'test_organisation_data.json', 'test_app_roles.json',
        'test_user_data.json'
    ]

    def setUp(self):
        self.client = SSOClient()

    def tearDown(self):
        pass

    def test_add_organisation_by_country_admin(self):
        self.client.login(username='******', password='******')
        response = self.client.get(
            reverse('organisations:organisation_create'))

        self.assertEqual(response.status_code, 200)
        # CountryAdmin is admin of County 81
        organisation_country = OrganisationCountry.objects.get(
            uuid='6bc429702f9f442ea9717824a8d76d84')
        countries = response.context['form'].fields[
            'organisation_country'].queryset
        self.assertEqual(len(countries), 1)
        self.assertEqual(organisation_country, countries[0])
        email_domain = settings.SSO_ORGANISATION_EMAIL_DOMAIN if settings.SSO_ORGANISATION_EMAIL_DOMAIN else '@g10f.de'

        # create a new center
        data = {
            'name': 'New Center',
            'center_type': 'g',
            'organisation_country': organisation_country.pk,
            'email_value': 'newcenter' + email_domain,
            'email_forward': '*****@*****.**',
            'is_active': 'on'
        }
        response = self.client.post(
            reverse('organisations:organisation_create'), data=data)
        self.assertEqual(response.status_code, 302)

        # check center attributes
        organisation = Organisation.objects.get(name="New Center")
        self.assertEqual(organisation.organisation_country,
                         organisation_country)
        self.assertIsNotNone(organisation.uuid)

    def test_add_organisation_by_region_admin(self):
        self.client.login(username='******', password='******')
        response = self.client.get(
            reverse('organisations:organisation_create'))

        self.assertEqual(response.status_code, 200)
        # RegionAdmin is admin of Region 0ebf2537fc664b7db285ea773c981404
        organisation_country = OrganisationCountry.objects.get(
            uuid='6bc429702f9f442ea9717824a8d76d84')
        countries = response.context['form'].fields[
            'organisation_country'].queryset
        self.assertEqual(len(countries), 1)
        self.assertEqual(organisation_country, countries[0])
        email_domain = settings.SSO_ORGANISATION_EMAIL_DOMAIN if settings.SSO_ORGANISATION_EMAIL_DOMAIN else '@g10f.de'

        admin_region = AdminRegion.objects.get(
            uuid='0ebf2537fc664b7db285ea773c981404')

        # create a new center
        data = {
            'name': 'New Center',
            'center_type': 'g',
            'organisation_country': organisation_country.pk,
            'admin_region': admin_region.pk,
            'email_value': 'newcenter' + email_domain,
            'email_forward': '*****@*****.**',
            'is_active': 'on'
        }
        response = self.client.post(
            reverse('organisations:organisation_create'), data=data)
        self.assertEqual(response.status_code, 302)

        # check center attributes
        organisation = Organisation.objects.get(name="New Center")
        self.assertEqual(organisation.organisation_country,
                         organisation_country)
        self.assertIsNotNone(organisation.uuid)

    def test_some_list(self):
        self.client.login(username='******', password='******')

        response = self.client.get(reverse('organisations:adminregion_list'))
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            reverse('organisations:adminregion_list'),
            data={'country': OrganisationCountry.objects.first().pk})
        self.assertEqual(response.status_code, 200)

        response = self.client.get(reverse('organisations:adminregion_list'),
                                   data={'country': 99999})
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            reverse('organisations:organisation_list_txt'))
        self.assertEqual(response.status_code, 200)