def test_reset_password(key_values_service, user_claim, client, app, users, mocker):
    with app.app_context():
        user = users[1]
        token_response = _create_token(client, user.email_address)
        assert token_response.status_code == 200
        claim = _get_token(user.email_address)

        old_password = user.password
        new_password = '******'

        assert old_password != new_password

        key_values_service.get_by_key.return_value = {'data': {'age': 3600}}

        response = client.post(
            '/2/reset-password/{}?e={}'.format(claim.token, user.email_address),
            data=json.dumps({
                'email_address': user.email_address,
                'user_id': user.id,
                'password': '******',
                'confirmPassword': '******'
            }),
            content_type='application/json')

        assert response.status_code == 200
        data = json.loads(response.data)
        assert data['message'] == 'User with email {}, successfully updated their password'.format(user.email_address)

        user = User.query.filter(
            User.email_address == user.email_address).first()

        assert encryption.authenticate_user(new_password, user)
        assert not encryption.authenticate_user(old_password, user)
Esempio n. 2
0
def test_reset_password(client, users):
    user = users[1]
    token_response = _create_token(client, user.email_address, 'orams')
    assert token_response.status_code == 200
    token = json.loads(token_response.data)['token']

    old_password = user.password
    new_password = '******'

    assert old_password != new_password

    response = client.post('/2/reset-password/{}'.format(token),
                           data=json.dumps({
                               'email_address': user.email_address,
                               'user_id': user.id,
                               'password': '******',
                               'confirmPassword': '******'
                           }),
                           content_type='application/json')

    assert response.status_code == 200
    data = json.loads(response.data)
    assert data[
        'message'] == 'User with email {}, successfully updated their password'.format(
            user.email_address)

    user = User.query.filter(User.email_address == user.email_address).first()

    assert encryption.authenticate_user(new_password, user)
    assert not encryption.authenticate_user(old_password, user)
Esempio n. 3
0
def login():
    """Login user
    ---
    tags:
      - auth
    security:
      - basicAuth: []
    consumes:
      - application/json
    parameters:
      - name: body
        in: body
        required: true
        schema:
          id: LoginUser
          required:
            - emailAddress
            - password
          properties:
            emailAddress:
              type: string
            password:
              type: string
    responses:
      200:
        description: User
        schema:
          $ref: '#/definitions/UserInfo'
    """
    json_payload = request.get_json()
    email_address = json_payload.get('emailAddress', None)
    user = User.get_by_email_address(email_address.lower())

    if user is None or (user.supplier and user.supplier.status == 'deleted'):
        return jsonify(message='User does not exist'), 403
    elif encryption.authenticate_user(json_payload.get('password', None),
                                      user) and user.active:
        user.logged_in_at = datetime.utcnow()
        user.failed_login_count = 0
        db.session.add(user)
        db.session.commit()

        if '_csrf_token' in session:
            session.pop('_csrf_token')
        if 'csrf' in session:
            session.pop('csrf')

        if current_app.config['REDIS_SESSIONS']:
            session.regenerate()
        login_user(user)

        loaded_user = load_user(user.id)
        return jsonify(user_info(loaded_user))
    else:
        user.failed_login_count += 1
        db.session.add(user)
        db.session.commit()

        return jsonify(message="Could not authorize user"), 403
Esempio n. 4
0
def load_user_from_request(request):
    if not current_app.config.get('BASIC_AUTH'):
        return None

    payload = get_token_from_headers(request.headers)

    if payload is None:
        return None

    email_address, password = b64decode(payload).split(':', 1)
    user = User.get_by_email_address(email_address.lower())

    if user is not None:
        if encryption.authenticate_user(password, user):
            user = LoginUser(user.id, user.email_address, user.supplier_code,
                             None, user.locked, user.active, user.name,
                             user.role, user.terms_accepted_at,
                             user.application_id, user.frameworks)
            return user
Esempio n. 5
0
def auth_user():
    json_payload = get_json_from_request()
    json_has_required_keys(json_payload, ["authUsers"])
    json_payload = json_payload["authUsers"]
    validate_user_auth_json_or_400(json_payload)
    email_address = json_payload.get('email_address', None)
    if email_address is None:
        # will remove camel case email address with future api
        email_address = json_payload.get('emailAddress', None)

    user = User.query.options(
        joinedload('supplier'),
        noload('supplier.*'),
        joinedload('application'),
        noload('application.*'),
        noload('*')
    ).filter(
        User.email_address == email_address.lower()
    ).first()

    if user is None or (user.supplier and user.supplier.status == 'deleted'):
        return jsonify(authorization=False), 404
    elif encryption.authenticate_user(json_payload['password'], user) and user.active:
        user.logged_in_at = datetime.utcnow()
        user.failed_login_count = 0
        db.session.add(user)
        db.session.commit()

        validation_result = None
        if user.role == 'supplier':
            messages = supplier_business.get_supplier_messages(user.supplier_code, False)
            validation_result = (
                messages._asdict() if messages else None
            )

        return jsonify(users=user.serialize(), validation_result=validation_result), 200
    else:
        user.failed_login_count += 1
        db.session.add(user)
        db.session.commit()

        return jsonify(authorization=False), 403
def auth_user():
    json_payload = get_json_from_request()
    json_has_required_keys(json_payload, ["authUsers"])
    json_payload = json_payload["authUsers"]
    validate_user_auth_json_or_400(json_payload)
    email_address = json_payload.get('email_address', None)
    if email_address is None:
        # will remove camel case email address with future api
        email_address = json_payload.get('emailAddress', None)

    user = User.query.options(
        joinedload('supplier'),
        noload('supplier.*'),
        joinedload('application'),
        noload('application.*'),
        noload('*')
    ).filter(
        User.email_address == email_address.lower()
    ).first()

    if user is None or (user.supplier and user.supplier.status == 'deleted'):
        return jsonify(authorization=False), 404
    elif encryption.authenticate_user(json_payload['password'], user) and user.active:
        user.logged_in_at = datetime.utcnow()
        user.failed_login_count = 0
        db.session.add(user)
        db.session.commit()

        validation_result = None
        if user.role == 'supplier':
            messages = supplier_business.get_supplier_messages(user.supplier_code, False)
            validation_result = (
                messages._asdict() if messages else None
            )

        return jsonify(users=user.serialize(), validation_result=validation_result), 200
    else:
        user.failed_login_count += 1
        db.session.add(user)
        db.session.commit()

        return jsonify(authorization=False), 403
def test_authenticate_user(user_is_locked, expected_auth_result):
    password = "******"
    password_hash = hashpw(password)
    mock_user = mock.Mock(password=password_hash, locked=user_is_locked)

    assert authenticate_user(password, mock_user) == expected_auth_result