コード例 #1
0
def test_decode_invitation_token_does_not_work_if_token_expired(email_app):
    with freeze_time('2015-01-02 03:04:05'):
        data = {'email_address': '*****@*****.**', 'supplier_name': 'A. Supplier'}
        token = generate_token(data, email_app.config['SHARED_EMAIL_KEY'], email_app.config['INVITE_EMAIL_SALT'])
    with email_app.app_context():

        assert decode_invitation_token(token, role='supplier') is None
コード例 #2
0
def generate_buyer_creation_token(name, email_address, **unused):
    data = {
        'name': name,
        'email_address': email_address,
    }
    token = generate_token(data, current_app.config['SECRET_KEY'], current_app.config['BUYER_CREATION_TOKEN_SALT'])
    return token
コード例 #3
0
def generate_buyer_creation_token(name, email_address, **unused):
    data = {
        'name': name,
        'email_address': email_address,
    }
    token = generate_token(data, current_app.config['SECRET_KEY'], current_app.config['BUYER_CREATION_TOKEN_SALT'])
    return token
    def test_token_created_before_last_updated_password_cannot_be_used(self):
        self.data_api_client.get_user.return_value = self.user(
            123,
            "*****@*****.**",
            1234,
            'email',
            'Name',
            is_token_valid=False)
        token = generate_token(self._user, self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['RESET_PASSWORD_TOKEN_NS'])
        url = '/user/reset-password/{}'.format(token)

        res = self.client.post(url,
                               data={
                                   'password': '******',
                                   'confirm_password': '******'
                               },
                               follow_redirects=True)

        assert res.status_code == 200
        document = html.fromstring(res.get_data(as_text=True))
        error_selector = cssselect.CSSSelector('div.dm-alert.dm-alert--error')
        error_elements = error_selector(document)
        assert len(error_elements) == 1
        assert reset_password.EXPIRED_PASSWORD_RESET_TOKEN_MESSAGE in error_elements[
            0].text_content()
        assert self.data_api_client.update_user_password.called is False
コード例 #5
0
def test_parse_timestamp_from_token():
    test_time = datetime(2000, 1, 1)
    with freeze_time(test_time):
        data = {}
        token = generate_token(data, TEST_SECRET_KEY, 'PassSalt')
    timestamp = parse_fernet_timestamp(token)
    assert timestamp == test_time
コード例 #6
0
def test_parse_timestamp_from_token():
    test_time = datetime(2000, 1, 1)
    with freeze_time(test_time):
        data = {}
        token = generate_token(data, TEST_SECRET_KEY, 'PassSalt')
    timestamp = parse_fernet_timestamp(token)
    assert timestamp == test_time
コード例 #7
0
def test_decode_invitation_token_does_not_work_if_token_expired(email_app):
    with freeze_time('2015-01-02 03:04:05'):
        data = {'email_address': '*****@*****.**', 'supplier_name': 'A. Supplier'}
        token = generate_token(data, TEST_SECRET_KEY, email_app.config['INVITE_EMAIL_SALT'])

    with email_app.app_context():
        assert decode_invitation_token(token, role='supplier') is None
コード例 #8
0
    def test_should_render_correct_error_page_for_old_style_expired_supplier_token(self):
        with freeze_time('2016-09-28 16:00:00'):
            token = generate_token(
                {
                    "supplier_id": '12345',
                    "supplier_name": 'Supplier Name',
                    "email_address": '*****@*****.**'
                },
                self.app.config['SHARED_EMAIL_KEY'],
                self.app.config['INVITE_EMAIL_TOKEN_NS']
            )

        res = self.client.get(
            '/user/create/{}'.format(token)
        )

        assert res.status_code == 400

        messages = [
            'The link you used to create an account may have expired.',
            'Check you’ve entered the correct link or ask the person who invited you to send a new invitation.'
        ]

        for message in messages:
            assert message in res.get_data(as_text=True)
コード例 #9
0
    def test_should_render_correct_error_page_for_old_style_expired_buyer_token(self):
        with freeze_time('2016-09-28 16:00:00'):
            token = generate_token(
                {"email_address": '*****@*****.**'},
                self.app.config['SHARED_EMAIL_KEY'],
                self.app.config['INVITE_EMAIL_TOKEN_NS']
            )

        res = self.client.get(
            '/user/create/{}'.format(token)
        )

        assert res.status_code == 400
        doc = html.fromstring(res.get_data())
        p = doc.xpath(
            "//p[contains(normalize-space(string()),$t)][contains(normalize-space(string()),$m)]",
            t="The link you used to create an account may have expired.",
            m="Check you’ve entered the correct link or send a new one",
        )
        assert p
        assert p[0].xpath(
            ".//a[@href=$u][normalize-space(string())=$t]",
            u="/buyers/create",
            t="send a new one",
        )
    def test_invalid_token_contents_500s(self):
        token = generate_token({'this_is_not_expected': 1234},
                               self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['INVITE_EMAIL_TOKEN_NS'])

        with pytest.raises(KeyError):
            self.client.get('/user/create/{}'.format(token))
コード例 #11
0
def test_decode_password_reset_token_ok_for_good_token(email_app, user):
    user['users']['passwordChangedAt'] = "2016-01-01T12:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user
    with email_app.app_context():
        data = {'user': '******'}
        token = generate_token(data, TEST_SECRET_KEY, 'PassSalt')
        assert decode_password_reset_token(token, data_api_client) == data
コード例 #12
0
 def _generate_token(self, email_address='*****@*****.**'):
     return generate_token(
         {
             'email_address': email_address
         },
         self.app.config['SHARED_EMAIL_KEY'],
         self.app.config['INVITE_EMAIL_SALT']
     )
コード例 #13
0
def test_decode_invitation_token_decodes_ok_for_supplier(email_app):
    with email_app.app_context():
        data = {
            'email_address': '*****@*****.**',
            'supplier_code': 1234,
            'supplier_name': 'A. Supplier'
        }
        token = generate_token(data, TEST_SECRET_KEY, 'Salt')
        assert decode_invitation_token(token, role='supplier') == data
コード例 #14
0
def test_cant_decode_token_with_wrong_key():
    token = generate_token({
        "key1": "value1",
        "key2": "value2"},
        secret_key=TEST_SECRET_KEY,
        salt="1234567890")

    with pytest.raises(InvalidToken):
        decode_token(token, 'WrongKeyWrongKeyWrongKeyWrongKeyWrongKeyXXX=', '1234567890')
コード例 #15
0
def test_decode_password_reset_token_ok_for_good_token(email_app):
    user = user_json()
    user['users']['passwordChangedAt'] = "2016-01-01T12:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user
    with email_app.app_context():
        data = {'user': '******'}
        token = generate_token(data, 'Secret', 'PassSalt')
        assert decode_password_reset_token(token, data_api_client) == data
コード例 #16
0
def generate_supplier_invitation_token(name, email_address, supplier_code, supplier_name):
    data = {
        'name': name,
        'emailAddress': email_address,
        'supplierCode': supplier_code,
        'supplierName': supplier_name,
    }
    token = generate_token(data, current_app.config['SECRET_KEY'], current_app.config['SUPPLIER_INVITE_TOKEN_SALT'])
    return token
コード例 #17
0
    def test_should_be_an_error_for_invalid_token_contents(
            self, data_api_client):
        token = generate_token({'this_is_not_expected': 1234},
                               self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['INVITE_EMAIL_SALT'])

        res = self.client.get('/suppliers/create-user/{}'.format(token))
        assert res.status_code == 400
        assert data_api_client.get_user.called is False
        assert data_api_client.get_supplier.called is False
コード例 #18
0
def test_decode_password_reset_token_does_not_work_if_bad_token(email_app):
    user = user_json()
    user['users']['passwordChangedAt'] = "2016-01-01T12:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user
    data = {'user': '******'}
    token = generate_token(data, TEST_SECRET_KEY, 'PassSalt')[1:]

    with email_app.app_context():
        assert decode_password_reset_token(token, data_api_client) == {'error': 'token_invalid'}
コード例 #19
0
    def test_should_be_an_error_for_invalid_token_contents(
            self, data_api_client):
        token = generate_token({'this_is_not_expected': 1234},
                               self.app.config['SECRET_KEY'],
                               self.app.config['SUPPLIER_INVITE_TOKEN_SALT'])

        res = self.client.get(self.url_for('main.create_user', token=token))
        assert res.status_code == 404
        assert data_api_client.get_user.called is False
        assert data_api_client.get_supplier.called is False
    def _generate_token(self, email_address='*****@*****.**', role='buyer'):
        token_data = {'role': role, 'email_address': email_address}

        if role == 'buyer':
            token_data.update({"phoneNumber": "020-7930-4832"})
        elif role == 'supplier':
            token_data.update({"supplier_id": '12345'})

        return generate_token(token_data, self.app.config['SHARED_EMAIL_KEY'],
                              self.app.config['INVITE_EMAIL_TOKEN_NS'])
コード例 #21
0
 def _generate_token(self, supplier_id=1234, supplier_name='Supplier Name', email_address='*****@*****.**'):
     return generate_token(
         {
             'supplier_id': supplier_id,
             'supplier_name': supplier_name,
             'email_address': email_address
         },
         self.app.config['SHARED_EMAIL_KEY'],
         self.app.config['INVITE_EMAIL_SALT']
     )
コード例 #22
0
def test_decode_password_reset_token_does_not_work_if_bad_token(email_app):
    user = user_json()
    user['users']['passwordChangedAt'] = "2016-01-01T12:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user
    data = {'user': '******'}
    token = generate_token(data, 'Secret', 'PassSalt')[1:]

    with email_app.app_context():
        assert decode_password_reset_token(token, data_api_client) == {'error': 'token_invalid'}
コード例 #23
0
def test_can_generate_token():
    token = generate_token({
        "key1": "value1",
        "key2": "value2"
    },
                           secret_key=TEST_SECRET_KEY,
                           salt="1234567890")

    token = decode_token(token, TEST_SECRET_KEY, '1234567890')
    assert {"key1": "value1", "key2": "value2"} == token
コード例 #24
0
def test_decode_invitation_token_does_not_work_if_bad_token(email_app):
    with email_app.app_context():
        data = {
            'email_address': '*****@*****.**',
            'supplier_name': 'A. Supplier'
        }
        token = generate_token(data, TEST_SECRET_KEY,
                               email_app.config['INVITE_EMAIL_SALT'])[1:]

        assert decode_invitation_token(token, role='supplier') is None
コード例 #25
0
def test_cant_decode_token_with_wrong_key():
    token = generate_token({
        "key1": "value1",
        "key2": "value2"},
        secret_key="1234567890",
        salt="1234567890")

    with pytest.raises(BadTimeSignature) as error:
        decode_token(token, "failed", "1234567890")
    assert "does not match" in str(error.value)
コード例 #26
0
 def _generate_token(self,
                     supplier_id=1234,
                     supplier_name='Supplier Name',
                     email_address='*****@*****.**'):
     return generate_token(
         {
             'supplier_id': supplier_id,
             'supplier_name': supplier_name,
             'email_address': email_address
         }, self.app.config['SHARED_EMAIL_KEY'],
         self.app.config['INVITE_EMAIL_SALT'])
コード例 #27
0
ファイル: helpers.py プロジェクト: das2011/orams
def generate_creation_token(name, email_address, user_type, framework,
                            **unused):
    data = {
        'name': name,
        'email_address': email_address,
        'user_type': user_type,
        'framework': framework
    }
    token = generate_token(data, current_app.config['SECRET_KEY'],
                           current_app.config['SIGNUP_INVITATION_TOKEN_SALT'])
    return token
コード例 #28
0
def test_can_generate_token():
    token = generate_token({
        "key1": "value1",
        "key2": "value2"},
        secret_key=TEST_SECRET_KEY,
        salt="1234567890")

    token = decode_token(token, TEST_SECRET_KEY, '1234567890')
    assert {
        "key1": "value1",
        "key2": "value2"} == token
コード例 #29
0
def invite_user_to_application(application_id):
    json_payload = request.get_json(True)
    email_address = json_payload.get('email')
    name = json_payload.get('name')

    application = data_api_client.get_application(application_id)
    if not application:
        return abort(404)

    user_json = data_api_client.get_user(email_address=email_address)

    if user_json:
        return abort(400)

    token_data = {'id': application_id, 'name': name, 'email_address': email_address}
    token = generate_token(token_data, current_app.config['SECRET_KEY'], current_app.config['INVITE_EMAIL_SALT'])
    try:
        token = token.decode()
    except AttributeError:
        pass

    url = '{}://{}/{}/{}'.format(
        current_app.config['DM_HTTP_PROTO'],
        current_app.config['DM_MAIN_SERVER_NAME'],
        current_app.config['CREATE_APPLICANT_PATH'],
        format(token)
    )

    email_body = render_template(
        'emails/invite_user_application_email.html',
        url=url,
        supplier=application['application']['name'],
        name=name,
    )

    try:
        send_email(
            email_address,
            email_body,
            current_app.config['INVITE_EMAIL_SUBJECT'],
            current_app.config['INVITE_EMAIL_FROM'],
            current_app.config['INVITE_EMAIL_NAME'],
        )
    except EmailError as e:
        current_app.logger.error(
            'Invitation email failed to send error {} to {} supplier {} supplier code {} '.format(
                str(e),
                email_address,
                current_user.supplier_name,
                current_user.supplier_code)
        )
        abort(503, "Failed to send user invite reset")

    return jsonify(success=True), 200
コード例 #30
0
    def test_email_should_be_decoded_from_token(self):
        with self.app.app_context():
            token = generate_token(
                self._user,
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])
            url = '/reset-password/{}'.format(token)

        res = self.client.get(url)
        assert res.status_code == 200
        assert "Reset password for [email protected]" in res.get_data(as_text=True)
コード例 #31
0
def send_invite_user():
    form = EmailAddressForm()

    if form.validate_on_submit():
        token = generate_token(
            {
                "supplier_id": current_user.supplier_id,
                "supplier_name": current_user.supplier_name,
                "email_address": form.email_address.data
            },
            current_app.config['SHARED_EMAIL_KEY'],
            current_app.config['INVITE_EMAIL_SALT']
        )
        url = url_for('main.create_user', encoded_token=token, _external=True)
        email_body = render_template(
            "emails/invite_user_email.html",
            url=url,
            user=current_user.name,
            supplier=current_user.supplier_name)

        try:
            send_email(
                form.email_address.data,
                email_body,
                current_app.config['DM_MANDRILL_API_KEY'],
                current_app.config['INVITE_EMAIL_SUBJECT'],
                current_app.config['INVITE_EMAIL_FROM'],
                current_app.config['INVITE_EMAIL_NAME'],
                ["user-invite"]
            )
        except MandrillException as e:
            current_app.logger.error(
                "Invitation email failed to send. "
                "error {error} supplier_id {supplier_id} email_hash {email_hash}",
                extra={'error': six.text_type(e),
                       'supplier_id': current_user.supplier_id,
                       'email_hash': hash_email(current_user.email_address)})
            abort(503, "Failed to send user invite reset")

        data_api_client.create_audit_event(
            audit_type=AuditTypes.invite_user,
            user=current_user.email_address,
            object_type='suppliers',
            object_id=current_user.supplier_id,
            data={'invitedEmail': form.email_address.data},
        )

        flash('user_invited', 'success')
        return redirect(url_for('.list_users'))
    else:
        return render_template(
            "auth/submit_email_address.html",
            form=form), 400
コード例 #32
0
def send_invite_user():
    form = EmailAddressForm()

    if form.validate_on_submit():
        token = generate_token(
            {
                "supplier_id": current_user.supplier_id,
                "supplier_name": current_user.supplier_name,
                "email_address": form.email_address.data
            },
            current_app.config['SHARED_EMAIL_KEY'],
            current_app.config['INVITE_EMAIL_SALT']
        )
        url = url_for('main.create_user', encoded_token=token, _external=True)
        email_body = render_template(
            "emails/invite_user_email.html",
            url=url,
            user=current_user.name,
            supplier=current_user.supplier_name)

        try:
            send_email(
                form.email_address.data,
                email_body,
                current_app.config['DM_MANDRILL_API_KEY'],
                current_app.config['INVITE_EMAIL_SUBJECT'],
                current_app.config['INVITE_EMAIL_FROM'],
                current_app.config['INVITE_EMAIL_NAME'],
                ["user-invite"]
            )
        except MandrillException as e:
            current_app.logger.error(
                "Invitation email failed to send. "
                "error {error} supplier_id {supplier_id} email_hash {email_hash}",
                extra={'error': six.text_type(e),
                       'supplier_id': current_user.supplier_id,
                       'email_hash': hash_email(current_user.email_address)})
            abort(503, "Failed to send user invite reset")

        data_api_client.create_audit_event(
            audit_type=AuditTypes.invite_user,
            user=current_user.email_address,
            object_type='suppliers',
            object_id=current_user.supplier_id,
            data={'invitedEmail': form.email_address.data},
        )

        flash('user_invited', 'success')
        return redirect(url_for('.list_users'))
    else:
        return render_template(
            "auth/submit_email_address.html",
            form=form), 400
コード例 #33
0
def test_can_generate_token():
    token = generate_token({
        "key1": "value1",
        "key2": "value2"},
        secret_key="1234567890",
        salt="1234567890")

    token, timestamp = decode_token(token, "1234567890", "1234567890")
    assert {
        "key1": "value1",
        "key2": "value2"} == token
    assert timestamp
    def test_should_not_strip_whitespace_surrounding_reset_password_password_field(
            self):
        token = generate_token(self._user, self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['RESET_PASSWORD_TOKEN_NS'])
        url = '/user/reset-password/{}'.format(token)

        self.client.post(url,
                         data={
                             'password': '******',
                             'confirm_password': '******'
                         })
        self.data_api_client.update_user_password.assert_called_with(
            self._user.get('user'), '  password12345', self._user.get('email'))
    def test_passwords_should_match(self):
        token = generate_token(self._user, self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['RESET_PASSWORD_TOKEN_NS'])
        url = '/user/reset-password/{}'.format(token)

        res = self.client.post(url,
                               data={
                                   'password': '******',
                                   'confirm_password': '******'
                               })
        assert res.status_code == 400
        assert PASSWORD_MISMATCH_ERROR_MESSAGE in res.get_data(as_text=True)
        assert self.data_api_client.update_user_password.called is False
コード例 #36
0
def test_decode_password_reset_token_does_not_work_if_token_expired(email_app):
    user = user_json()
    user['users']['passwordChangedAt'] = "2016-01-01T12:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user
    with freeze_time('2015-01-02 03:04:05'):
        # Token was generated a year before current time
        data = {'user': '******'}
        token = generate_token(data, TEST_SECRET_KEY, 'PassSalt')

    with freeze_time('2016-01-02 03:04:05'):
        with email_app.app_context():
            assert decode_password_reset_token(token, data_api_client) == {'error': 'token_invalid'}
コード例 #37
0
def test_decode_password_reset_token_does_not_work_if_token_expired(email_app):
    user = user_json()
    user['users']['passwordChangedAt'] = "2016-01-01T12:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user
    with freeze_time('2015-01-02 03:04:05'):
        # Token was generated a year before current time
        data = {'user': '******'}
        token = generate_token(data, 'Secret', 'PassSalt')

    with freeze_time('2016-01-02 03:04:05'):
        with email_app.app_context():
            assert decode_password_reset_token(token, data_api_client) == {'error': 'token_expired'}
    def test_password_should_not_be_in_blocklist(self, bad_password):
        token = generate_token(self._user, self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['RESET_PASSWORD_TOKEN_NS'])
        url = '/user/reset-password/{}'.format(token)

        res = self.client.post(url,
                               data={
                                   'password': bad_password,
                                   'confirm_password': bad_password,
                               })
        assert res.status_code == 400
        assert PASSWORD_BLOCKLIST_ERROR_MESSAGE in res.get_data(as_text=True)
        assert self.data_api_client.update_user_password.called is False
コード例 #39
0
    def test_redirect_to_login_page_on_success(self):
        with self.app.app_context():
            token = generate_token(
                self._user,
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])
            url = '/reset-password/{}'.format(token)

            res = self.client.post(url, data={
                'password': '******',
                'confirm_password': '******'
            })
            assert res.status_code == 302
            assert res.location == 'http://localhost/login'
コード例 #40
0
    def test_passwords_should_match(self):
        with self.app.app_context():
            token = generate_token(
                self._user,
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])
            url = '/reset-password/{}'.format(token)

            res = self.client.post(url, data={
                'password': '******',
                'confirm_password': '******'
            })
            assert res.status_code == 400
            assert PASSWORD_MISMATCH_ERROR in res.get_data(as_text=True)
コード例 #41
0
    def test_should_be_an_error_for_invalid_token_contents(self, data_api_client):
        token = generate_token(
            {
                'this_is_not_expected': 1234
            },
            self.app.config['SHARED_EMAIL_KEY'],
            self.app.config['INVITE_EMAIL_SALT']
        )

        res = self.client.get(
            '/create-user/{}'.format(token)
        )
        assert res.status_code == 400
        assert data_api_client.get_user.called is False
コード例 #42
0
    def test_should_not_strip_whitespace_surrounding_reset_password_password_field(self):
        with self.app.app_context():
            token = generate_token(
                self._user,
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])
            url = '/reset-password/{}'.format(token)

            self.client.post(url, data={
                'password': '******',
                'confirm_password': '******'
            })
            self.data_api_client_mock.update_user_password.assert_called_with(
                self._user.get('user'), '  1234567890', self._user.get('email'))
コード例 #43
0
    def test_reset_password_form_and_inputs_specify_input_purpose(
            self, data_api_client):
        data_api_client.get_user.return_value = self.user(
            123, "*****@*****.**", 1234, 'email', 'name')
        token = generate_token({
            "user": 123,
            "email": '*****@*****.**',
        }, self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['RESET_PASSWORD_TOKEN_NS'])

        url = '/user/reset-password/{}'.format(token)

        self._forms_and_inputs_specify_input_purpose(
            url, "Reset password", "Reset password for [email protected]")
コード例 #44
0
def invite_user_to_application(application_id):
    json_payload = request.get_json(True)
    email_address = json_payload.get('email')
    name = json_payload.get('name')

    application = data_api_client.get_application(application_id)
    if not application:
        return abort(404)

    user_json = data_api_client.get_user(email_address=email_address)

    if user_json:
        return abort(400)

    token_data = {'id': application_id, 'name': name, 'email_address': email_address}
    token = generate_token(token_data, current_app.config['SECRET_KEY'], current_app.config['INVITE_EMAIL_SALT'])

    url = '{}://{}/{}/{}'.format(
        current_app.config['DM_HTTP_PROTO'],
        current_app.config['DM_MAIN_SERVER_NAME'],
        current_app.config['CREATE_APPLICANT_PATH'],
        format(token)
    )

    email_body = render_template(
        'emails/invite_user_application_email.html',
        url=url,
        supplier=application['application']['name'],
        name=name,
    )

    try:
        send_email(
            email_address,
            email_body,
            current_app.config['INVITE_EMAIL_SUBJECT'],
            current_app.config['INVITE_EMAIL_FROM'],
            current_app.config['INVITE_EMAIL_NAME'],
        )
    except EmailError as e:
        current_app.logger.error(
            'Invitation email failed to send error {} to {} supplier {} supplier code {} '.format(
                str(e),
                email_address,
                current_user.supplier_name,
                current_user.supplier_code)
        )
        abort(503, "Failed to send user invite reset")

    return jsonify(success=True), 200
    def test_password_should_not_be_empty(self):
        token = generate_token(self._user, self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['RESET_PASSWORD_TOKEN_NS'])
        url = '/user/reset-password/{}'.format(token)

        res = self.client.post(url,
                               data={
                                   'password': '',
                                   'confirm_password': ''
                               })
        assert res.status_code == 400
        assert NEW_PASSWORD_EMPTY_ERROR_MESSAGE in res.get_data(as_text=True)
        assert NEW_PASSWORD_CONFIRM_EMPTY_ERROR_MESSAGE in res.get_data(
            as_text=True)
        assert self.data_api_client.update_user_password.called is False
コード例 #46
0
def test_decode_password_reset_token_does_not_work_if_password_changed_later_than_token(email_app):
    user = user_json()
    user['users']['passwordChangedAt'] = "2016-01-01T13:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user

    with freeze_time('2016-01-01T12:00:00.30Z'):
        # Token was generated an hour earlier than password was changed
        data = {'user': '******'}
        token = generate_token(data, 'Secret', 'PassSalt')

    with freeze_time('2016-01-01T14:00:00.30Z'):
        # Token is two hours old; password was changed an hour ago
        with email_app.app_context():
            assert decode_password_reset_token(token, data_api_client) == {'error': 'token_invalid'}
コード例 #47
0
    def test_password_should_not_be_empty(self):
        with self.app.app_context():
            token = generate_token(
                self._user,
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])
            url = '/reset-password/{}'.format(token)

            res = self.client.post(url, data={
                'password': '',
                'confirm_password': ''
            })
            assert res.status_code == 400
            assert NEW_PASSWORD_EMPTY_ERROR in res.get_data(as_text=True)
            assert NEW_PASSWORD_CONFIRM_EMPTY_ERROR in res.get_data(as_text=True)
コード例 #48
0
def test_decode_password_reset_token_does_not_work_if_password_changed_later_than_token(email_app):
    user = user_json()
    user['users']['passwordChangedAt'] = "2016-01-01T13:00:00.30Z"
    data_api_client = mock.Mock()
    data_api_client.get_user.return_value = user

    with freeze_time('2016-01-01T12:00:00.30Z'):
        # Token was generated an hour earlier than password was changed
        data = {'user': '******'}
        token = generate_token(data, TEST_SECRET_KEY, 'PassSalt')

    with freeze_time('2016-01-01T14:00:00.30Z'):
        # Token is two hours old; password was changed an hour ago
        with email_app.app_context():
            assert decode_password_reset_token(token, data_api_client) == {'error': 'token_invalid'}
コード例 #49
0
def reset_password(user_id):
    user = data_api_client.get_user(user_id)

    token = generate_token(
        {
            "user_id": user_id,
            "email_address": user['users']['emailAddress']
        },
        current_app.config['SECRET_KEY'],
        current_app.config['RESET_PASSWORD_SALT']
    )

    return redirect('{}://{}/2/reset-password/{}'.format(current_app.config['DM_HTTP_PROTO'],
                                                         current_app.config['DM_MAIN_SERVER_NAME'],
                                                         token))
コード例 #50
0
    def test_should_be_an_error_for_invalid_token_contents(self, data_api_client):
        token = generate_token(
            {
                'this_is_not_expected': 1234
            },
            self.app.config['SECRET_KEY'],
            self.app.config['SUPPLIER_INVITE_TOKEN_SALT']
        )

        res = self.client.get(
            self.url_for('main.create_user', token=token)
        )
        assert res.status_code == 404
        assert data_api_client.get_user.called is False
        assert data_api_client.get_supplier.called is False
コード例 #51
0
    def test_password_should_be_under_51_chars_long(self):
        with self.app.app_context():
            token = generate_token(
                self._user,
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])
            url = '/reset-password/{}'.format(token)

            res = self.client.post(url, data={
                'password':
                    '******',
                'confirm_password':
                    '******'
            })
            assert res.status_code == 400
            assert PASSWORD_INVALID_ERROR in res.get_data(as_text=True)
コード例 #52
0
    def test_reset_password_form_and_inputs_not_autofillable(
            self, data_api_client):
        data_api_client.get_user.return_value = self.user(
            123, "*****@*****.**", 1234, 'email', 'name')

        with self.app.app_context():
            token = generate_token({
                "user": 123,
                "email": '*****@*****.**',
            }, self.app.config['SECRET_KEY'],
                                   self.app.config['RESET_PASSWORD_SALT'])

            url = self.expand_path('/reset-password/{}').format(token)

        self._forms_and_inputs_not_autofillable(
            url,
            "Reset password",
        )
    def test_redirect_to_login_page_on_success(self):
        token = generate_token(self._user, self.app.config['SHARED_EMAIL_KEY'],
                               self.app.config['RESET_PASSWORD_TOKEN_NS'])
        url = '/user/reset-password/{}'.format(token)

        res = self.client.post(url,
                               data={
                                   'password': '******',
                                   'confirm_password': '******'
                               })
        assert res.status_code == 302
        assert res.location == 'http://localhost/user/login'
        res = self.client.get(res.location)

        assert reset_password.PASSWORD_UPDATED_MESSAGE in res.get_data(
            as_text=True)
        self.data_api_client.update_user_password.assert_called_with(
            self._user.get('user'), 'password12345', self._user.get('email'))
コード例 #54
0
    def test_token_created_before_last_updated_password_cannot_be_used(
            self, data_api_client
    ):
        with self.app.app_context():
            data_api_client.get_user.return_value = self.user(
                123, "*****@*****.**", 1234, 'email', 'Name', is_token_valid=False
            )
            token = generate_token(
                self._user,
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])
            url = '/reset-password/{}'.format(token)

            res = self.client.post(url, data={
                'password': '******',
                'confirm_password': '******'
            }, follow_redirects=True)

            assert res.status_code == 200
            assert TOKEN_CREATED_BEFORE_PASSWORD_LAST_CHANGED_ERROR in res.get_data(as_text=True)
コード例 #55
0
    def test_reset_password_form_and_inputs_not_autofillable(
            self, data_api_client
    ):
        data_api_client.get_user.return_value = self.user(
            123, "*****@*****.**", 1234, 'email', 'name'
        )

        with self.app.app_context():
            token = generate_token(
                {
                    "user": 123,
                    "email": '*****@*****.**',
                },
                self.app.config['SECRET_KEY'],
                self.app.config['RESET_PASSWORD_SALT'])

            url = self.expand_path('/reset-password/{}').format(token)

        self._forms_and_inputs_not_autofillable(
            url,
            "Reset password",
        )
コード例 #56
0
def test_decode_invitation_token_does_not_work_if_bad_token(email_app):
    with email_app.app_context():
        data = {'email_address': '*****@*****.**', 'supplier_name': 'A. Supplier'}
        token = generate_token(data, email_app.config['SHARED_EMAIL_KEY'], email_app.config['INVITE_EMAIL_SALT'])[1:]

        assert decode_invitation_token(token, role='supplier') is None
コード例 #57
0
def test_decode_invitation_token_decodes_ok_for_supplier(email_app):
    with email_app.app_context():
        data = {'email_address': '*****@*****.**', 'supplier_id': 1234, 'supplier_name': 'A. Supplier'}
        token = generate_token(data, 'Key', 'Salt')
        assert decode_invitation_token(token, role='supplier') == data
コード例 #58
0
def test_decode_invitation_token_decodes_ok_for_buyer(email_app):
    with email_app.app_context():
        data = {'email_address': '*****@*****.**'}
        token = generate_token(data, 'Key', 'Salt')
        assert decode_invitation_token(token, role='buyer') == data