Ejemplo n.º 1
0
def test_spamcheck(client, dummy_stageuser, mocker, spamcheck_status,
                   spamcheck_on):
    user = User(ipa_admin.stageuser_show("dummy")["result"])
    assert user.status_note != spamcheck_status
    token = make_token({"sub": "dummy"}, audience=Audience.spam_check)
    with mailer.record_messages() as outbox:
        response = client.post(
            "/register/spamcheck-hook",
            json={
                "token": token,
                "status": spamcheck_status
            },
        )
    assert response.status_code == 200
    assert response.json == {"status": "success"}
    # Check that the status was changed
    user = User(ipa_admin.stageuser_show("dummy")["result"])
    assert user.status_note == spamcheck_status
    # Sent email
    if spamcheck_status == "active":
        assert len(outbox) == 1
        message = outbox[0]
        assert message.subject == "Verify your email address"
        assert message.recipients == ["*****@*****.**"]
    else:
        assert len(outbox) == 0
Ejemplo n.º 2
0
def confirm_registration():
    username = request.args.get('username')
    if not username:
        abort(400, "No username provided")
    try:
        user = User(ipa_admin.stageuser_show(a_uid=username)['result'])
    except python_freeipa.exceptions.NotFound:
        flash(_("The registration seems to have failed, please try again."),
              "warning")
        return redirect(f"{url_for('.root')}?tab=register")

    if current_app.config["BASSET_URL"] and user.status_note != "active":
        abort(401, "You should not be here")

    form = ResendValidationEmailForm()
    if form.validate_on_submit():
        _send_validation_email(user)
        flash(
            _('The address validation email has be sent again. Make sure it did not land in '
              'your spam folder'),
            'success',
        )
        return redirect(request.url)

    return render_template('registration-confirmation.html',
                           user=user,
                           form=form)
Ejemplo n.º 3
0
def test_strip(client, post_data_step_1, cleanup_dummy_user, field_name):
    """Register a user with fields that contain trailing spaces"""
    post_data_step_1[f"register-{field_name}"] = "Dummy "
    with mailer.record_messages() as outbox:
        result = client.post('/', data=post_data_step_1)
    assert result.status_code == 302, str(result.data, "utf8")
    user = User(ipa_admin.stageuser_show(a_uid="dummy")['result'])
    assert getattr(user, field_name) == "Dummy"
    assert len(outbox) == 1
Ejemplo n.º 4
0
def test_gecos(client, post_data_non_ascii, cleanup_dummy_user, mocker):
    record_signal = mocker.Mock()
    with mailer.record_messages() as _, stageuser_created.connected_to(
            record_signal):
        result = client.post('/', data=post_data_non_ascii)
    assert result.status_code == 302

    # Check that default values are added
    user = User(ipa_admin.stageuser_show("dummy")['result'])

    assert user.gecos == "Xi Jin Ping aeoeue ss AeOeUe Ss An Bei Jin San"
Ejemplo n.º 5
0
def spamcheck_wait():
    username = request.args.get('username')
    if not username:
        abort(400, "No username provided")

    try:
        user = User(ipa_admin.stageuser_show(a_uid=username)["result"])
    except python_freeipa.exceptions.NotFound:
        flash(_("The registration seems to have failed, please try again."),
              "warning")
        return redirect(f"{url_for('.root')}?tab=register")

    if user.status_note == "active":
        return redirect(
            f"{url_for('.confirm_registration')}?username={username}")

    return render_template('registration-spamcheck-wait.html', user=user)
Ejemplo n.º 6
0
def test_step_1(client, post_data_step_1, cleanup_dummy_user, mocker):
    """Register a user, step 1"""
    record_signal = mocker.Mock()
    with mailer.record_messages() as outbox, stageuser_created.connected_to(
            record_signal):
        result = client.post('/', data=post_data_step_1)
    assert result.status_code == 302
    assert result.location == "http://localhost/register/confirm?username=dummy"
    # Emitted signal
    record_signal.assert_called_once()
    # Sent email
    assert len(outbox) == 1
    message = outbox[0]
    assert message.subject == "Verify your email address"
    assert message.recipients == ["*****@*****.**"]
    # Check that default values are added
    user = User(ipa_admin.stageuser_show("dummy")['result'])
    # Creation time
    assert user.creation_time is not None
    # Locale
    assert user.locale == current_app.config["USER_DEFAULTS"]["locale"]
    # Timezone
    assert user.timezone == current_app.config["USER_DEFAULTS"]["timezone"]
Ejemplo n.º 7
0
def activate_account():
    register_url = f"{url_for('.root')}?tab=register"
    token_string = request.args.get('token')
    if not token_string:
        flash(_('No token provided, please check your email validation link.'),
              'warning')
        return redirect(register_url)

    try:
        token = read_token(token_string, audience=Audience.email_validation)
    except jwt.exceptions.DecodeError:
        flash(_("The token is invalid, please register again."), "warning")
        return redirect(register_url)
    except jwt.exceptions.ExpiredSignatureError:
        flash(_("This token is no longer valid, please register again."),
              "warning")
        return redirect(register_url)

    try:
        user = User(ipa_admin.stageuser_show(token["sub"])["result"])
    except python_freeipa.exceptions.NotFound:
        flash(_("This user cannot be found, please register again."),
              "warning")
        return redirect(register_url)

    token_mail = token["mail"]
    if not user.mail == token_mail:
        current_app.logger.error(
            f'User {user.username} tried to validate a token for address {token_mail} while they '
            f'are registered with address {user.mail}, something fishy may be going on.'
        )
        flash(
            _("The username and the email address don't match the token you used, "
              "please register again."),
            "warning",
        )
        return redirect(register_url)

    form = PasswordSetForm()

    if form.validate_on_submit():
        with handle_form_errors(form):
            password = form.password.data
            # First we activate the stage user
            try:
                ipa_admin.stageuser_activate(user.username)
            except python_freeipa.exceptions.FreeIPAError as e:
                current_app.logger.error(
                    f'An unhandled error {e.__class__.__name__} happened while activating '
                    f'stage user {user.username}: {e.message}')
                raise FormError(
                    "non_field_errors",
                    _("Something went wrong while creating your account, "
                      "please try again later."),
                )
            # User activation succeeded. Send signal.
            user_registered.send(user, request=request._get_current_object())
            # Now we set the password.
            try:
                # First, set it as an admin. This will mark it as expired.
                ipa_admin.user_mod(user.username, userpassword=password)
                # And now we set it again as the user, so it is not expired any more.
                ipa = untouched_ipa_client(current_app)
                ipa.change_password(user.username,
                                    new_password=password,
                                    old_password=password)
            except python_freeipa.exceptions.PWChangePolicyError as e:
                # The user is active but the password does not match the policy.
                # Tell the user what's going to happen.
                flash(
                    _(
                        'Your account has been created, but the password you chose does not '
                        'comply with the policy (%(policy_error)s) and has thus been set as '
                        'expired. You will be asked to change it after logging in.',
                        policy_error=e.policy_error,
                    ),
                    'warning',
                )
                return redirect(url_for(".root"))
            except python_freeipa.exceptions.ValidationError as e:
                # for example: invalid username. We don't know which field to link it to
                _handle_registration_validation_error(user.username, e)
            except python_freeipa.exceptions.FreeIPAError as e:
                current_app.logger.error(
                    f'An unhandled error {e.__class__.__name__} happened while changing initial '
                    f'password for user {user.username}: {e.message}')
                # At this point the user has been activated, they can't register again. Send them to
                # the login page with an appropriate warning.
                flash(
                    _(
                        'Your account has been created, but an error occurred while setting your '
                        'password (%(message)s). You may need to change it after logging in.',
                        message=e.message,
                    ),
                    'warning',
                )
                return redirect(url_for(".root"))

            # Try to log them in directly, so they don't have to type their password again.
            try:
                ipa = maybe_ipa_login(current_app, session, user.username,
                                      password)
            except python_freeipa.exceptions.FreeIPAError:
                ipa = None
            if ipa:
                flash(
                    _(
                        'Congratulations, your account has been created! Welcome, %(name)s.',
                        name=user.name,
                    ),
                    'success',
                )
            else:
                # No shortcut for you, you'll have to login properly (maybe the password is
                # expired).
                flash(
                    _('Congratulations, your account has been created! Go ahead and sign in '
                      'to proceed.'),
                    'success',
                )
            return redirect(url_for('.root'))

    return render_template('registration-activation.html',
                           user=user,
                           form=form)