Ejemplo n.º 1
0
def test_exists_no_pkey_fail(app, mocker):

    # mock db query
    query_mock = mocker.patch('flask_sqlalchemy._QueryProperty.__get__')
    query_mock.return_value \
        .get.return_value = None

    errors, models = exists({}, SomeModel, 'field', None)

    assert errors == {'field': ["Missing data for required field."]}
    assert models is None
Ejemplo n.º 2
0
def post_user():
    """Creates a new user.

    :returns: JSON string of the new user's data; status code
    :rtype: (str, int)
    """

    # pre-validate data
    errors = unique({}, User, User.username,
                    request.json.get('username', None))

    errors = unique_email(errors, User, User.email,
                          request.json.get('email', None))

    errors, roles = exists(errors, Role, 'roles',
                           request.json.get('roles', []))

    # validate data
    try:
        data = UserAdminSchema().load(request.json)
    except ValidationError as err:
        errors = dict(list(errors.items()) + list(err.messages.items()))

    # return any errors
    if errors:
        return jsonify({"error": errors}), 400

    # save user
    user = User(username=data['username'].lower().strip(),
                email=data['email'].lower().strip(),
                password=data['password'],
                is_verified=data['is_verified'],
                status=data['status'],
                status_changed_at=datetime.now())

    for role in roles:
        user.roles.append(role)

    # save user profile
    if 'profile' in data:
        user_profile = UserProfile(
            user=user,
            first_name=data['profile']['first_name'].strip(),
            last_name=data['profile']['last_name'].strip(),
            joined_at=data['profile']['joined_at'],
            status=data['status'],
            status_changed_at=datetime.now())
        db.session.add(user_profile)

    db.session.add(user)
    db.session.commit()

    # response
    return jsonify({'user': UserAdminSchema().dump(user)}), 201
Ejemplo n.º 3
0
def test_exists_no_pkey_custom_message_fail(app, mocker):

    # mock db query
    query_mock = mocker.patch('flask_sqlalchemy._QueryProperty.__get__')
    query_mock.return_value \
        .get.return_value = None

    errors, models = exists({}, SomeModel, 'field', None, missing_error="bar")

    assert errors == {'field': ["bar"]}
    assert models is None
Ejemplo n.º 4
0
def test_exists_multiple_fail(app, mocker):

    # mock db query
    query_mock = mocker.patch('flask_sqlalchemy._QueryProperty.__get__')
    query_mock.return_value \
        .get.return_value = None

    errors, models = exists({}, SomeModel, 'field', [1, 2])

    assert errors == {'field': ["Invalid value."]}
    assert models == []
Ejemplo n.º 5
0
def test_exists_multiple_pass(app, mocker):
    test_model = SomeModel()
    test_model.id = 1

    # mock db query
    query_mock = mocker.patch('flask_sqlalchemy._QueryProperty.__get__')
    query_mock.return_value \
        .get.return_value = test_model

    errors, models = exists({}, SomeModel, 'field', [1, 2])

    assert errors == {}
    assert models == [test_model, test_model]
Ejemplo n.º 6
0
def post_administrator():
    """Creates a new administrator
    :returns: JSON string of the new administrator's data; status code
    :rtype: (str, int)
    """

    # pre-validate data
    errors = unique({}, Administrator, Administrator.username,
                    request.json.get('username', None))

    errors = unique_email(errors, Administrator, Administrator.email,
                          request.json.get('email', None))

    errors, roles = exists(errors, Role, 'roles',
                           request.json.get('roles', []))

    # validate data
    try:
        data = AdministratorAdminSchema().load(request.json)
    except ValidationError as err:
        errors = dict(list(errors.items()) + list(err.messages.items()))

    # return any errors
    if errors:
        return jsonify({"error": errors}), 400

    # save admin
    admin = Administrator(username=data['username'].lower().strip(),
                          email=data['email'].lower().strip(),
                          first_name=data['first_name'],
                          last_name=data['last_name'],
                          password=data['password'],
                          joined_at=data['joined_at'],
                          status=data['status'],
                          status_changed_at=datetime.now())

    for role in roles:
        admin.roles.append(role)

    db.session.add(admin)
    db.session.commit()

    # response
    return jsonify({'administrator':
                    AdministratorAdminSchema().dump(admin)}), 201
Ejemplo n.º 7
0
def put_user(user_id):
    """Updates an existing user.

    :param user_id: ID of user
    :type user_id: int
    :returns: JSON string of the user's data; status code
    :rtype: (str, int)
    """

    # get user
    user = User.query.get(user_id)
    if user is None:
        abort(404)

    # pre-validate data
    errors = unique({},
                    User,
                    User.username,
                    request.json.get('username', None),
                    update=user)

    errors = unique_email(errors,
                          User,
                          User.email,
                          request.json.get('email', None),
                          update=user)

    errors, roles = exists(errors, Role, 'roles',
                           request.json.get('roles', []))

    # validate data
    try:
        if request.json.get('password', None):
            data = UserAdminSchema().load(request.json)
        else:
            data = UserAdminSchema(exclude=('password', )).load(request.json)
    except ValidationError as err:
        errors = dict(list(errors.items()) + list(err.messages.items()))

    # return any errors
    if errors:
        return jsonify({"error": errors}), 400

    # save user
    user.username = data['username'].lower().strip()
    user.email = data['email'].lower().strip()
    user.is_verified = data['is_verified']

    if 'password' in data:
        user.password = data['password']

    user.roles[:] = []
    for role in roles:
        user.roles.append(role)

    if user.status != data['status']:
        user.status = data['status']
        user.status_changed_at = datetime.now()

    # save user profile
    if 'profile' in data:
        user_profile = user.profile if user.profile else None
        if user_profile:
            user_profile.first_name = data['profile']['first_name'].strip()
            user_profile.last_name = data['profile']['last_name'].strip()
            user_profile.joined_at = data['profile']['joined_at']
            if user_profile.status != data['status']:
                user_profile.status = data['status']
                user_profile.status_changed_at = datetime.now()
        else:
            user_profile = UserProfile(
                user_id=user.id,
                first_name=data['profile']['first_name'].strip(),
                last_name=data['profile']['last_name'].strip(),
                joined_at=data['profile']['joined_at'],
                status=data['status'],
                status_changed_at=datetime.now())
            db.session.add(user_profile)
            user.profile = user_profile

    db.session.commit()

    # response
    return jsonify({'user': UserAdminSchema().dump(user)}), 200
Ejemplo n.º 8
0
def put_administrator(administrator_id):
    """Updates an existing administrator
    :param administrator_id: ID of administrator
    :type administrator_id: int
    :returns: JSON string of the administrator's data; status code
    :rtype: (str, int)
    """

    # get administrator
    administrator = Administrator.query.get(administrator_id)
    if administrator is None:
        abort(404)

    # pre-validate data
    errors = unique({},
                    Administrator,
                    Administrator.username,
                    request.json.get('username', None),
                    update=administrator)

    errors = unique_email(errors,
                          Administrator,
                          Administrator.email,
                          request.json.get('email', None),
                          update=administrator)

    errors, roles = exists(errors, Role, 'roles',
                           request.json.get('roles', []))

    # validate data
    try:
        if request.json.get('password', None):
            data = AdministratorAdminSchema().load(request.json)
        else:
            data = AdministratorAdminSchema(exclude=('password', )).load(
                request.json)
    except ValidationError as err:
        errors = dict(list(errors.items()) + list(err.messages.items()))

    # return any errors
    if errors:
        return jsonify({"error": errors}), 400

    # save administrator
    administrator.username = data['username'].lower().strip()
    administrator.email = data['email'].lower().strip()
    administrator.first_name = data['first_name']
    administrator.last_name = data['last_name']
    administrator.joined_at = data['joined_at']

    if 'password' in data:
        administrator.password = data['password']

    administrator.roles[:] = []
    for role in roles:
        administrator.roles.append(role)

    if administrator.status != data['status']:
        administrator.status = data['status']
        administrator.status_changed_at = datetime.now()

    db.session.commit()

    # response
    return jsonify(
        {'administrator': AdministratorAdminSchema().dump(administrator)}), 200
Ejemplo n.º 9
0
def post_user_account_step1():
    """User registration step 1.

    :returns: JSON string of the user's account information; status code
    :rtype: (str, int)
    """

    # pre-validate data
    errors = unique({}, User, User.username,
                    str(request.json.get('username')).lower().strip()
                    if request.json.get('username', None) else None)

    errors = unique_email(
        errors, User, User.email,
        str(request.json.get('email')).lower().strip() if request.json.get(
            'email', None) else None)

    errors, tos = exists(errors,
                         TermsOfService,
                         'tos_id',
                         request.json.get('tos_id', None),
                         missing_error="Please agree to the terms of service.")

    if (request.json.get('password', None)
            and request.json.get('password2', None)):
        if request.json.get('password') != request.json.get('password2'):
            errors['password2'] = ["Passwords must match."]

    # validate data
    try:
        data = UserAccountSchema(exclude=(
            'first_name',
            'last_name',
        )).load(request.json)
    except ValidationError as err:
        errors = dict(list(errors.items()) + list(err.messages.items()))

    # return any errors
    if errors:
        return jsonify({"error": errors}), 400

    # save user
    user = User(username=data['username'].lower().strip(),
                email=data['email'].lower().strip(),
                password=data['password'],
                is_verified=False,
                status=User.STATUS_ENABLED,
                status_changed_at=datetime.now())

    user_role = Role.query.filter(Role.name == 'USER').first()
    if user_role:
        user.roles.append(user_role)

    db.session.add(user)

    # save user terms of service
    user_tos = UserTermsOfService(user=user,
                                  terms_of_service=tos,
                                  accept_date=datetime.now(),
                                  ip_address=request.environ.get(
                                      'HTTP_X_REAL_IP', request.remote_addr))
    db.session.add(user_tos)

    # save password history
    pass_history = UserPasswordHistory(user=user,
                                       password=user.password,
                                       set_date=datetime.now())
    db.session.add(pass_history)

    db.session.commit()

    # prep output
    output = {
        'id': user.id,
        'username': user.username,
        'email': user.email,
        'password_changed_at': user.password_changed_at,
        'is_verified': user.is_verified,
        'first_name': None,
        'last_name': None,
        'joined_at': None,
    }

    # response
    return jsonify({'user_account': UserAccountSchema().dump(output)}), 201