def test_change_email_is_unique_after_first_view(app, settings, simple_user,
                                                 user_ou1, mailoutbox):
    settings.A2_EMAIL_IS_UNIQUE = True
    new_email = '*****@*****.**'
    email = change_email(app, simple_user, new_email, mailoutbox)
    link = utils.get_link_from_mail(email)
    # user_ou1 take the new email in the meantime
    user_ou1.email = new_email
    user_ou1.save()
    # email change is impossible as email is already taken
    link = utils.get_link_from_mail(email)
    response = app.get(link).follow()
    assert 'is already used by another account' in response.content
Beispiel #2
0
def test_registration(app, db, settings, mailoutbox, external_redirect):
    next_url, good_next_url = external_redirect

    settings.LANGUAGE_CODE = 'en-us'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()

    # disable existing attributes
    models.Attribute.objects.update(disabled=True)

    User = get_user_model()
    url = utils.make_url('registration_register', params={REDIRECT_FIELD_NAME: next_url})
    response = app.get(url)
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()

    assert urlparse(response['Location']).path == reverse('registration_complete')

    response = response.follow()
    assert '2 days' in response.content
    assert '*****@*****.**' in response.content
    assert len(mailoutbox) == 1

    link = get_link_from_mail(mailoutbox[0])

    # test password validation
    response = app.get(link)
    response.form.set('password1', 'toto')
    response.form.set('password2', 'toto')
    response = response.form.submit()
    assert '8 characters' in response.content

    # set valid password
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    if good_next_url:
        assert 'You have just created an account.' in response.content
        assert next_url in response.content
    else:
        assert urlparse(response['Location']).path == '/'
        response = response.follow()
        assert 'You have just created an account.' in response.content
    assert User.objects.count() == 1
    assert len(mailoutbox) == 2
    assert 'was successful' in mailoutbox[1].body

    new_user = User.objects.get()
    assert new_user.email == '*****@*****.**'
    assert new_user.username is None
    assert new_user.check_password('T0==toto')
    assert new_user.is_active
    assert not new_user.is_staff
    assert not new_user.is_superuser
    assert str(app.session['_auth_user_id']) == str(new_user.pk)

    response = app.get('/login/')
    response.form.set('username', '*****@*****.**')
    response.form.set('password', 'T0==toto')
    response = response.form.submit(name='login-password-submit')
    assert urlparse(response['Location']).path == reverse('auth_homepage')
def test_change_email_email_is_unique(app, settings, simple_user, user_ou1,
                                      mailoutbox):
    settings.A2_EMAIL_IS_UNIQUE = True
    email = change_email(app, simple_user, user_ou1.email, mailoutbox)
    link = utils.get_link_from_mail(email)
    # email change is impossible as email is already taken
    assert 'password/reset' in link
def test_change_email(app, simple_user, user_ou1, mailoutbox):
    email = change_email(app, simple_user, user_ou1.email, mailoutbox)
    link = utils.get_link_from_mail(email)
    app.get(link)
    simple_user.refresh_from_db()
    # ok it worked
    assert simple_user.email == user_ou1.email
Beispiel #5
0
def test_api_users_create_send_mail(app, settings, superuser):
    from authentic2.models import Attribute

    # Use case is often that Email is the main identifier
    settings.A2_EMAIL_IS_UNIQUE = True
    Attribute.objects.create(kind='title', name='title', label='title')

    app.authorization = ('Basic', (superuser.username, superuser.username))
    payload = {
        'username': '******',
        'first_name': 'John',
        'last_name': 'Doe',
        'email': '*****@*****.**',
        'title': 'Mr',
        'send_registration_email': True,
    }
    assert len(mail.outbox) == 0
    resp = app.post_json('/api/users/', params=payload, status=201)
    user_id = resp.json['id']
    assert len(mail.outbox) == 1
    # Follow activation link
    url = get_link_from_mail(mail.outbox[0])
    relative_url = url.split('testserver')[1]
    resp = app.get(relative_url, status=200)
    resp.form.set('new_password1', '1234==aA')
    resp.form.set('new_password2', '1234==aA')
    resp = resp.form.submit().follow()
    # Check user was properly logged in
    assert str(app.session['_auth_user_id']) == str(user_id)
def test_change_email_ou_email_is_unique(app, simple_user, user_ou1, user_ou2,
                                         mailoutbox):
    user_ou1.ou.email_is_unique = True
    user_ou1.ou.save()
    user_ou2.email = '*****@*****.**'
    user_ou2.save()
    email = change_email(app, simple_user, user_ou2.email, mailoutbox)
    link = utils.get_link_from_mail(email)
    app.get(link)
    simple_user.refresh_from_db()
    # ok it worked for a differnt ou
    assert simple_user.email == user_ou2.email
    # now set simple_user in same ou as user_ou1
    simple_user.ou = user_ou1.ou
    simple_user.save()
    email = change_email(app, simple_user, user_ou1.email, mailoutbox)
    link = utils.get_link_from_mail(email)
    # email change is impossible as email is already taken in the same ou
    assert 'password/reset' in link
Beispiel #7
0
def test_registration_realm(app, db, settings, mailoutbox):
    settings.LANGUAGE_CODE = 'en-us'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()
    settings.A2_REGISTRATION_REALM = 'realm'
    settings.A2_REDIRECT_WHITELIST = ['http://relying-party.org/']
    settings.A2_REQUIRED_FIELDS = ['username']

    # disable existing attributes
    models.Attribute.objects.update(disabled=True)

    User = get_user_model()
    next_url = 'http://relying-party.org/'
    url = utils.make_url('registration_register', params={REDIRECT_FIELD_NAME: next_url})

    response = app.get(url)
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()

    assert urlparse(response['Location']).path == reverse('registration_complete')

    response = response.follow()
    assert '2 days' in response.content
    assert '*****@*****.**' in response.content
    assert '2 days' in response.content
    assert len(mailoutbox) == 1

    link = get_link_from_mail(mailoutbox[0])

    # register
    response = app.get(link)
    response.form.set('username', 'toto')
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert 'You have just created an account.' in response.content
    assert next_url in response.content
    assert len(mailoutbox) == 2
    assert 'was successful' in mailoutbox[1].body

    # verify user has expected attributes
    new_user = User.objects.get()
    assert new_user.username == 'toto@realm'
    assert new_user.email == '*****@*****.**'
    assert new_user.check_password('T0==toto')
    assert new_user.is_active
    assert not new_user.is_staff
    assert not new_user.is_superuser
    assert str(app.session['_auth_user_id']) == str(new_user.pk)

    # test login
    response = app.get('/login/')
    response.form.set('username', '*****@*****.**')
    response.form.set('password', 'T0==toto')
    response = response.form.submit(name='login-password-submit')
    assert urlparse(response['Location']).path == reverse('auth_homepage')
Beispiel #8
0
def test_username_settings(app, db, settings, mailoutbox):
    settings.LANGUAGE_CODE = 'en-us'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()
    settings.A2_REGISTRATION_FORM_USERNAME_REGEX = r'^(ab)+$'
    settings.A2_REGISTRATION_FORM_USERNAME_LABEL = 'Identifiant'
    settings.A2_REGISTRATION_FORM_USERNAME_HELP_TEXT = 'Bien remplir'
    settings.A2_REGISTRATION_FIELDS = ['username']
    settings.A2_REQUIRED_FIELDS = ['username']

    # disable existing attributes
    models.Attribute.objects.update(disabled=True)

    response = app.get(reverse('registration_register'))
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('registration_complete')

    response = response.follow()
    assert '2 days' in response.content
    assert '*****@*****.**' in response.content
    assert len(mailoutbox) == 1
    link = get_link_from_mail(mailoutbox[0])

    # register
    response = app.get(link)

    # check form render has changed
    assert response.pyquery('[for=id_username]').text() == 'Identifiant:'
    for key in ['username', 'password1', 'password2']:
        assert response.pyquery('[for=id_%s]' % key)
        assert response.pyquery('[for=id_%s]' % key).attr('class') == 'form-field-required'

    assert response.pyquery('#id_username').next('.helptext').text() == 'Bien remplir'
    assert not response.pyquery('.errorlist')

    # check username is validated using regexp
    response.form.set('username', 'abx')
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()

    assert 'Enter a valid value' in response.content

    # check regexp accepts some valid values
    response.form.set('username', 'abab')
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('auth_homepage')
    response = response.follow()
    assert 'You have just created an account.' in response.content
    assert len(mailoutbox) == 2
    assert 'was successful' in mailoutbox[1].body
Beispiel #9
0
def test_reset_password_ldap_user(slapd, settings, app, db):
    settings.LDAP_AUTH_SETTINGS = [{
        'url': [slapd.ldap_url],
        'binddn':
        force_text(slapd.root_bind_dn),
        'bindpw':
        force_text(slapd.root_bind_password),
        'basedn':
        u'o=ôrga',
        'use_tls':
        False,
    }]
    User = get_user_model()
    assert User.objects.count() == 0
    # first login
    response = app.get('/login/')
    response.form['username'] = USERNAME
    response.form['password'] = PASS
    response = response.form.submit('login-password-submit').follow()
    assert User.objects.count() == 1
    assert 'Étienne Michu' in str(response)
    user = User.objects.get()
    assert user.email == EMAIL
    # logout
    response = response.click('Logout')
    if response.status_code == 200:  # Django 1.7, same_origin is bugged; localhost != localhost:80
        response = response.form.submit().maybe_follow()
    else:
        response = response.maybe_follow()
    response = response.click('Reset it!')
    response.form['email'] = EMAIL
    assert len(mail.outbox) == 0
    response = response.form.submit().maybe_follow()
    assert len(mail.outbox) == 1
    reset_email_url = utils.get_link_from_mail(mail.outbox[0])
    response = app.get(reset_email_url, status=302)
    response = response.maybe_follow()
    assert 'login-password-submit' in response.content
    settings.LDAP_AUTH_SETTINGS[0]['can_reset_password'] = True
    response = app.get(reset_email_url, status=200)
    new_password = '******'
    response.form['new_password1'] = new_password
    response.form['new_password2'] = new_password
    response = response.form.submit(status=302).maybe_follow()
    # verify password has changed
    slapd.get_connection().bind_s(DN, new_password)
    with pytest.raises(ldap.INVALID_CREDENTIALS):
        slapd.get_connection().bind_s(DN, PASS)
    assert not User.objects.get().has_usable_password()
Beispiel #10
0
def test_registration_activate_passwords_not_equal(app, db, settings, mailoutbox):
    settings.LANGUAGE_CODE = 'en-us'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()
    settings.A2_EMAIL_IS_UNIQUE = True

    response = app.get(reverse('registration_register'))
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    response = response.follow()
    link = get_link_from_mail(mailoutbox[0])
    response = app.get(link)
    response.form.set('password1', 'azerty12AZ')
    response.form.set('password2', 'AAAazerty12AZ')
    response = response.form.submit()
    assert "The two password fields didn't match." in response.content
Beispiel #11
0
def test_manager_user_password_reset(app, superuser, simple_user):
    resp = login(
        app, superuser,
        reverse('a2-manager-user-detail', kwargs={'pk': simple_user.pk}))
    assert len(mail.outbox) == 0
    resp = resp.form.submit('password_reset')
    assert 'A mail was sent to' in resp
    assert len(mail.outbox) == 1
    url = get_link_from_mail(mail.outbox[0])
    relative_url = url.split('testserver')[1]
    resp = app.get('/logout/').maybe_follow()
    resp = app.get(relative_url, status=200)
    resp.form.set('new_password1', '1234==aA')
    resp.form.set('new_password2', '1234==aA')
    resp = resp.form.submit().follow()
    assert str(app.session['_auth_user_id']) == str(simple_user.pk)
Beispiel #12
0
def test_username_is_unique(app, db, settings, mailoutbox):
    settings.LANGUAGE_CODE = 'en-us'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()
    settings.A2_REGISTRATION_FIELDS = ['username']
    settings.A2_REQUIRED_FIELDS = ['username']
    settings.A2_USERNAME_IS_UNIQUE = True

    # disable existing attributes
    models.Attribute.objects.update(disabled=True)

    response = app.get(reverse('registration_register'))
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('registration_complete')

    response = response.follow()
    assert '2 days' in response.content
    assert '*****@*****.**' in response.content
    assert len(mailoutbox) == 1

    link = get_link_from_mail(mailoutbox[0])

    response = app.get(link)
    response.form.set('username', 'john.doe')
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('auth_homepage')
    response = response.follow()
    assert 'You have just created an account.' in response.content
    assert len(mailoutbox) == 2
    assert 'was successful' in mailoutbox[1].body

    # logout
    app.session.flush()

    # try again
    response = app.get(link)
    response = response.click('create')

    response.form.set('username', 'john.doe')
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert ('This username is already in use. Please supply a different username.' in
            response.content)
Beispiel #13
0
def test_view(app, simple_user, mailoutbox):
    url = reverse('password_reset') + '?next=/moncul/'
    resp = app.get(url, status=200)
    resp.form.set('email', simple_user.email)
    assert len(mailoutbox) == 0
    resp = resp.form.submit()
    assert resp['Location'].endswith('/moncul/')
    assert len(mailoutbox) == 1
    url = utils.get_link_from_mail(mailoutbox[0])
    relative_url = url.split('testserver')[1]
    resp = app.get(relative_url, status=200)
    resp.form.set('new_password1', '1234==aA')
    resp.form.set('new_password2', '1234==aA')
    resp = resp.form.submit()
    # verify user is logged
    assert str(app.session['_auth_user_id']) == str(simple_user.pk)
    # verify next_url was kept
    assert resp['Location'].endswith('/moncul/')
Beispiel #14
0
def test_send_password_reset_email(app, simple_user, mailoutbox):
    from authentic2.utils import send_password_reset_mail
    assert len(mailoutbox) == 0
    send_password_reset_mail(
        simple_user,
        legacy_subject_templates=['registration/password_reset_subject.txt'],
        legacy_body_templates=['registration/password_reset_email.html'],
        context={
            'base_url': 'http://testserver',
        })
    assert len(mailoutbox) == 1
    url = utils.get_link_from_mail(mailoutbox[0])
    relative_url = url.split('testserver')[1]
    resp = app.get(relative_url, status=200)
    resp.form.set('new_password1', '1234==aA')
    resp.form.set('new_password2', '1234==aA')
    resp = resp.form.submit().follow()
    assert str(app.session['_auth_user_id']) == str(simple_user.pk)
Beispiel #15
0
def test_email_is_unique(app, db, settings, mailoutbox):
    settings.LANGUAGE_CODE = 'en-us'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()
    settings.A2_EMAIL_IS_UNIQUE = True

    # disable existing attributes
    models.Attribute.objects.update(disabled=True)

    response = app.get(reverse('registration_register'))
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('registration_complete')

    response = response.follow()
    assert '2 days' in response.content
    assert '*****@*****.**' in response.content
    assert len(mailoutbox) == 1

    link = get_link_from_mail(mailoutbox[0])

    response = app.get(link)
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('auth_homepage')
    response = response.follow()
    assert 'You have just created an account.' in response.content
    assert len(mailoutbox) == 2
    assert 'was successful' in mailoutbox[1].body

    # logout
    app.session.flush()

    response = app.get(reverse('registration_register'))
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('registration_complete')

    response = response.follow()
    assert '2 days' in response.content
    assert '*****@*****.**' in response.content
    assert not 'This email address is already in use.' in response.content
    assert len(mailoutbox) == 3
    assert 'You already have' in mailoutbox[2].body
def test_registration_service_slug(oidc_settings, app, simple_oidc_client, simple_user, hooks,
                                   mailoutbox):
    redirect_uri = simple_oidc_client.redirect_uris.split()[0]

    params = {
        'client_id': simple_oidc_client.client_id,
        'scope': 'openid profile email',
        'redirect_uri': redirect_uri,
        'state': 'xxx',
        'nonce': 'yyy',
        'response_type': 'code',
    }

    authorize_url = make_url('oidc-authorize', params=params)
    response = app.get(authorize_url)

    location = urlparse.urlparse(response['Location'])
    query = urlparse.parse_qs(location.query)
    assert query['service'] == ['client']
    response = response.follow().click('Register')
    location = urlparse.urlparse(response.request.url)
    query = urlparse.parse_qs(location.query)
    assert query['service'] == ['client']

    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    assert len(mailoutbox) == 1
    link = utils.get_link_from_mail(mailoutbox[0])
    response = app.get(link)
    response.form.set('first_name', 'John')
    response.form.set('last_name', 'Doe')
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert hooks.event[0]['kwargs']['name'] == 'sso-request'
    assert hooks.event[0]['kwargs']['service'].slug == 'client'

    assert hooks.event[1]['kwargs']['name'] == 'registration'
    assert hooks.event[1]['kwargs']['service'] == 'client'

    assert hooks.event[2]['kwargs']['name'] == 'login'
    assert hooks.event[2]['kwargs']['how'] == 'email'
    assert hooks.event[2]['kwargs']['service'] == 'client'
Beispiel #17
0
def test_manager_user_change_email(app, superuser_or_admin, simple_user,
                                   mailoutbox):
    ou = get_default_ou()
    ou.validate_emails = True
    ou.save()

    NEW_EMAIL = '*****@*****.**'

    assert NEW_EMAIL != simple_user.email

    response = login(
        app, superuser_or_admin,
        reverse('a2-manager-user-by-uuid-detail',
                kwargs={'slug': unicode(simple_user.uuid)}))
    assert 'Change user email' in response.content
    # cannot click it's a submit button :/
    response = app.get(
        reverse('a2-manager-user-by-uuid-change-email',
                kwargs={'slug': unicode(simple_user.uuid)}))
    assert response.form['new_email'].value == simple_user.email
    response.form.set('new_email', NEW_EMAIL)
    assert len(mailoutbox) == 0
    response = response.form.submit().follow()
    assert 'A mail was sent to [email protected] to verify it.' in response.content
    assert 'Change user email' in response.content
    # cannot click it's a submit button :/
    assert len(mailoutbox) == 1
    assert simple_user.email in mailoutbox[0].body
    assert NEW_EMAIL in mailoutbox[0].body

    # logout
    app.session.flush()

    link = get_link_from_mail(mailoutbox[0])
    response = app.get(link).maybe_follow()
    assert (
        'your request for changing your email for [email protected] is successful'
        in response.content)
    simple_user.refresh_from_db()
    assert simple_user.email == NEW_EMAIL
Beispiel #18
0
def test_registration_redirect_tuple(app, db, settings, mailoutbox, external_redirect):
    next_url, good_next_url = external_redirect

    settings.A2_REGISTRATION_REDIRECT = 'http://cms/welcome/', 'target'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()

    new_next_url = settings.A2_REGISTRATION_REDIRECT[0]
    if good_next_url:
        new_next_url += '?target=' + urlquote(next_url)

    # disable existing attributes
    models.Attribute.objects.update(disabled=True)

    url = utils.make_url('registration_register', params={REDIRECT_FIELD_NAME: next_url})
    response = app.get(url)
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    response = response.follow()
    link = get_link_from_mail(mailoutbox[0])
    response = app.get(link)
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert new_next_url in response.content
Beispiel #19
0
def test_attribute_model(app, db, settings, mailoutbox):
    settings.LANGUAGE_CODE = 'en-us'
    settings.A2_VALIDATE_EMAIL_DOMAIN = can_resolve_dns()
    # disable existing attributes
    models.Attribute.objects.update(disabled=True)

    models.Attribute.objects.create(
        label=u'Prénom',
        name='prenom',
        required=True,
        kind='string')
    models.Attribute.objects.create(
        label=u'Nom',
        name='nom',
        asked_on_registration=True,
        user_visible=True,
        kind='string')
    models.Attribute.objects.create(
        label='Profession',
        name='profession',
        user_editable=True,
        kind='string')

    response = app.get(reverse('registration_register'))
    response.form.set('email', '*****@*****.**')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('registration_complete')

    response = response.follow()
    assert '2 days' in response.content
    assert '*****@*****.**' in response.content
    assert len(mailoutbox) == 1

    link = get_link_from_mail(mailoutbox[0])

    response = app.get(link)

    for key in ['prenom', 'nom', 'password1', 'password2']:
        assert response.pyquery('#id_%s' % key)

    response.form.set('prenom', 'John')
    response.form.set('nom', 'Doe')
    response.form.set('password1', 'T0==toto')
    response.form.set('password2', 'T0==toto')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('auth_homepage')
    response = response.follow()
    assert 'You have just created an account.' in response.content
    assert len(mailoutbox) == 2
    assert 'was successful' in mailoutbox[1].body

    response = app.get(reverse('account_management'))

    assert 'Nom' in response.content
    assert 'Prénom' not in response.content

    response = app.get(reverse('profile_edit'))
    assert 'edit-profile-profession' in response.form.fields
    assert 'edit-profile-prenom' not in response.form.fields
    assert 'edit-profile-nom' not in response.form.fields

    assert response.pyquery('[for=id_edit-profile-profession]')
    assert not response.pyquery('[for=id_edit-profile-profession].form-field-required')
    response.form.set('edit-profile-profession', 'pompier')
    response = response.form.submit()
    assert urlparse(response['Location']).path == reverse('account_management')

    response = response.follow()

    assert 'Nom' in response.content
    assert 'Doe' in response.content
    assert 'Profession' not in response.content
    assert 'pompier' not in response.content
    assert 'Prénom' not in response.content
    assert 'John' not in response.content
Beispiel #20
0
    def test_email_is_unique_double_registration(self):
        from django.contrib.auth import get_user_model
        from rest_framework import test
        from rest_framework import status

        # disable existing attributes
        models.Attribute.objects.update(disabled=True)

        user = self.reguser3
        cred = self.reguser3_cred
        User = get_user_model()
        user_count = User.objects.count()
        client = test.APIClient()
        password = '******'
        username = '******'
        email = '*****@*****.**'
        return_url = 'http://sp.org/register/'
        payload = {
            'email': email,
            'username': username,
            'ou': self.ou.slug,
            'password': password,
            'return_url': return_url,
        }
        outbox_level = len(mail.outbox)
        client.credentials(HTTP_AUTHORIZATION='Basic %s' % cred)
        response = client.post(reverse('a2-api-register'),
                               content_type='application/json',
                               data=json.dumps(payload))
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
        self.assertIn('result', response.data)
        self.assertEqual(response.data['result'], 1)
        self.assertIn('token', response.data)
        token = response.data['token']
        self.assertEqual(len(mail.outbox), outbox_level + 1)
        outbox_level = len(mail.outbox)

        # Second registration
        response2 = client.post(reverse('a2-api-register'),
                                content_type='application/json',
                                data=json.dumps(payload))
        self.assertEqual(response2.status_code, status.HTTP_202_ACCEPTED)
        self.assertIn('result', response2.data)
        self.assertEqual(response2.data['result'], 1)
        self.assertIn('token', response2.data)
        token2 = response2.data['token']
        self.assertEqual(len(mail.outbox), outbox_level + 1)

        activation_mail1, activation_mail2 = mail.outbox

        # User side - user click on first email
        client = Client()
        activation_url = get_link_from_mail(activation_mail1)
        response = client.get(activation_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        assert utils.make_url(return_url, params={'token': token}) in response.content
        self.assertEqual(User.objects.count(), user_count + 1)
        response = client.get(reverse('auth_homepage'))
        self.assertContains(response, username)
        last_user = User.objects.order_by('id').last()
        self.assertEqual(last_user.username, username)
        self.assertEqual(last_user.email, email)
        self.assertEqual(last_user.ou.slug, self.ou.slug)
        self.assertTrue(last_user.check_password(password))

        # User click on second email
        client = Client()
        activation_url = get_link_from_mail(activation_mail2)
        response = client.get(activation_url)
        self.assertEqual(response.status_code, status.HTTP_302_FOUND)
        self.assertEqual(response['Location'],
                         utils.make_url(return_url, params={'token': token2}))
        self.assertEqual(User.objects.count(), user_count + 1)
        response = client.get(reverse('auth_homepage'))
        self.assertContains(response, username)
        last_user2 = User.objects.order_by('id').last()
        self.assertEqual(User.objects.filter(email=payload['email']).count(), 1)
        self.assertEqual(last_user.id, last_user2.id)
        self.assertEqual(last_user2.username, username)
        self.assertEqual(last_user2.email, email)
        self.assertEqual(last_user2.ou.slug, self.ou.slug)
        self.assertTrue(last_user2.check_password(password))

        # Test email is unique with case change
        client = test.APIClient()
        client.credentials(HTTP_AUTHORIZATION='Basic %s' % cred)
        payload = {
            'email': email.upper(),
            'username': username + '1',
            'ou': self.ou.slug,
            'password': password,
            'return_url': return_url,
        }
        response = client.post(reverse('a2-api-register'),
                               content_type='application/json',
                               data=json.dumps(payload))
        self.assertEqual(response.data['errors']['__all__'],
                         [_('You already have an account')])
        # Username is required
        payload = {
            'email': '1' + email,
            'ou': self.ou.slug,
            'password': password,
            'return_url': return_url,
        }
        response = client.post(reverse('a2-api-register'),
                               content_type='application/json',
                               data=json.dumps(payload))
        self.assertEqual(response.data['errors']['__all__'],
                         [_('Username is required in this ou')])
        # Test username is unique
        payload = {
            'email': '1' + email,
            'username': username,
            'ou': self.ou.slug,
            'password': password,
            'return_url': return_url,
        }
        response = client.post(reverse('a2-api-register'),
                               content_type='application/json',
                               data=json.dumps(payload))
        self.assertEqual(response.data['errors']['__all__'],
                         [_('You already have an account')])
Beispiel #21
0
    def test_email_username_is_unique_double_registration(self):
        from django.contrib.auth import get_user_model
        from rest_framework import test
        from rest_framework import status

        # disable existing attributes
        models.Attribute.objects.update(disabled=True)

        cred = self.reguser3_cred
        User = get_user_model()
        user_count = User.objects.count()
        client = test.APIClient()
        password = '******'
        username = '******'
        email = '*****@*****.**'
        return_url = 'http://sp.org/register/'
        payload = {
            'email': email,
            'username': username,
            'ou': self.ou.slug,
            'password': password,
            'return_url': return_url,
        }
        outbox_level = len(mail.outbox)
        client.credentials(HTTP_AUTHORIZATION='Basic %s' % cred)
        response = client.post(reverse('a2-api-register'),
                               content_type='application/json',
                               data=json.dumps(payload))
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
        self.assertIn('result', response.data)
        self.assertEqual(response.data['result'], 1)
        self.assertIn('token', response.data)
        token = response.data['token']
        self.assertEqual(len(mail.outbox), outbox_level + 1)
        outbox_level = len(mail.outbox)

        # Second registration
        payload['email'] = '*****@*****.**'
        response2 = client.post(reverse('a2-api-register'),
                                content_type='application/json',
                                data=json.dumps(payload))
        self.assertEqual(response2.status_code, status.HTTP_202_ACCEPTED)
        self.assertIn('result', response2.data)
        self.assertEqual(response2.data['result'], 1)
        self.assertIn('token', response2.data)
        self.assertEqual(len(mail.outbox), outbox_level + 1)

        activation_mail1, activation_mail2 = mail.outbox

        # User side - user click on first email
        client = Client()
        activation_url = get_link_from_mail(activation_mail1)
        response = client.get(activation_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        assert utils.make_url(return_url, params={'token': token}) in response.content
        self.assertEqual(User.objects.count(), user_count + 1)
        response = client.get(reverse('auth_homepage'))
        self.assertContains(response, username)
        last_user = User.objects.order_by('id').last()
        self.assertEqual(last_user.username, username)
        self.assertEqual(last_user.email, email)
        self.assertEqual(last_user.ou.slug, self.ou.slug)
        self.assertTrue(last_user.check_password(password))

        # User click on second email
        client = Client()
        activation_url = get_link_from_mail(activation_mail2)
        response = client.get(activation_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.status_code, 200)
        self.assertFormError(
            response, 'form', 'username',
            _('This username is already in use. Please supply a different username.'))