Example #1
0
def test_crud_delete_all_user_disabled_admin_success(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        assert session.query(User) \
                .filter(User.enable == False).count() == 1  # noqa

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'delete',
                'model': 'user',
                'filters': {
                    'enable': False
                }
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert response.json['total'] == 1

    with DbSessionContext(config.get('mongo_database_name')) as session:
        assert not session.query(User) \
                .filter(User.enable == False).count()  # noqa
Example #2
0
def test_crud_update_admin_other_user(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
            .filter(User.email == '*****@*****.**').one()

        token = session.query(Emailconfirmationtoken) \
            .filter(Emailconfirmationtoken.user_uid == user.get_uid()).one()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'update',
                'model': 'emailconfirmationtoken',
                'uid': token.get_uid(),
                'data': {
                    'token': 'whatever'
                }
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert response.json['results'][0]['token'] == 'whatever'

    with DbSessionContext(config.get('mongo_database_name')) as session:
        assert session.query(Emailconfirmationtoken) \
            .filter(Emailconfirmationtoken.token == 'whatever').one()
Example #3
0
def test_crud_update_sanitize_data_admin(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
            .filter(User.email == '*****@*****.**').one()

    # CHANGING ROLE IS ALLOWED FOR ADMIN
    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'update',
                'model': 'user',
                'uid': user.get_uid(),
                'data': {
                    'role': 'admin'
                }
            }
        })
    assert response.status_code == 200
    assert response.json['success']

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
            .filter(User.email == '*****@*****.**').one()
        assert user.role == 'admin'
Example #4
0
def test_crud_update_admin_other_user(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
            .filter(User.email == '*****@*****.**').one()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'update',
                'model': 'user',
                'uid': user.get_uid(),
                'data': {
                    'name': 'new_name'
                }
            }
        })
    assert response.status_code == 200
    assert response.json['success']

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
            .filter(User.email == '*****@*****.**').one()
        assert user.name == 'new_name'
Example #5
0
def test_crud_delete_admin_success(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
                .filter(User.email == '*****@*****.**').one()
        token = session.query(Emailconfirmationtoken) \
            .filter(Emailconfirmationtoken.user_uid == user.get_uid()).one()

    token_uid = token.get_uid()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'delete',
                'model': 'emailconfirmationtoken',
                'uid': token_uid
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert response.json['total'] == 1

    with DbSessionContext(config.get('mongo_database_name')) as session:
        assert not session.query(Emailconfirmationtoken) \
                .filter(Emailconfirmationtoken.mongo_id == token_uid).count()
Example #6
0
def test_crud_delete_all_notification_for_specific_user_by_admin(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User)\
            .filter(User.email == '*****@*****.**').one()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'delete',
                'model': 'notification',
                'filters': {
                    'user_uid': user.get_uid()
                }
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert response.json['total'] == 4

    with DbSessionContext(config.get('mongo_database_name')) as session:
        assert not session.query(Notification)\
            .filter(Notification.user_uid == user.get_uid()).count()
Example #7
0
def test_crud_read_for_normal_user(client):
    user = client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        admin = session.query(User) \
                .filter(User.email == '*****@*****.**').one()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'read',
                'model': 'user',
                'uid': user.get_uid()
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert response.json['results'][0]['name'] == 'test'
    assert response.json['total'] == 1

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'read',
                'model': 'user',
                'uid': admin.get_uid()
            }
        })
    assert response.status_code == 200
    assert not response.json['success']
    assert response.json['error'] == 'NotAuthorizedException'
Example #8
0
def test_crud_update_notification_by_admin(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User)\
            .filter(User.email == '*****@*****.**').one()
        notification = session.query(Notification)\
            .filter(Notification.user_uid == user.get_uid()).first()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'update',
                'model': 'notification',
                'uid': notification.get_uid(),
                'data': {
                    'seen': True,
                    'message': 'Updated test'
                }
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert response.json['results'][0]['seen']
    assert response.json['results'][0]['message'] == 'Updated test'
    assert response.json['results'][0]['seen_timestamp']
Example #9
0
def test_validate_reset_password_token_expired(client):
    loop = asyncio.get_event_loop()
    asyncio.set_event_loop(loop)
    with DbSessionContext(config.get('mongo_database_name')) as session:
        old_datetime = dateutil_parser.parse('2012 12 22 00:00:00')
        user = session.query(User).filter(User.email == '*****@*****.**').one()
        reset_password_token = Resetpasswordtoken()
        context = {
            'db_session': session,
            'author': user,
            'data': {
                'user_uid': user.get_uid()
            },
            'mock_expiration_date': old_datetime
        }
        loop.run_until_complete(
            reset_password_token.validate_and_save(context))
        old_token = reset_password_token.token

    response = client.post_json('/api/validate_reset_password_token', {
        'token': client.__token__,
        'reset_password_token': old_token
    })

    assert response.status_code == 200
    assert not response.json['success']
    assert response.json['error'] == 'TokenExpiredException'
Example #10
0
def test_crud_update_normal_user_not_authorized(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        admin = session.query(User) \
            .filter(User.email == '*****@*****.**').one()

        token = session.query(Emailconfirmationtoken) \
            .filter(Emailconfirmationtoken.user_uid == admin.get_uid()).one()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'update',
                'model': 'emailconfirmationtoken',
                'uid': token.get_uid(),
                'data': {
                    'name': 'new_name'
                }
            }
        })
    assert response.status_code == 200
    assert not response.json['success']
    assert response.json['error'] == 'NotAuthorizedException'
def test_confirm_email_right_token(client):
    user = client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        token = session.query(Emailconfirmationtoken)\
            .filter(Emailconfirmationtoken.user_uid == user.get_uid()).one()

    response = client.post_json('/api/confirm_email', {'token': token.token})

    assert response.status_code == 200
    assert response.json['success']
    assert response.json['user']['email'] == '*****@*****.**'

    with DbSessionContext(config.get('mongo_database_name')) as session:
        last_notification = session.query(Notification)\
            .filter(Notification.user_uid == user.get_uid())\
            .descending(Notification.created_ts)\
            .first()

        assert last_notification.message == \
            'notification.YourEmailHasBeenConfirmed'
Example #12
0
    def login(self, email, password='******'):
        self.post_json('/api/login', {
            'email': email,
            'password': password,
            'token': self.__token__
        })
        with DbSessionContext(
                self.config.get('mongo_database_name')) as session:
            user = session.query(User)\
                .filter(User.email == email).one()

        return user
Example #13
0
    def on_model_change(self, form, model, is_created):
        logger.info("on_model_change")
        with DbSessionContext(config.get('mongo_database_name')) as session:
            try:
                m = importlib.import_module(
                    'server.model.{model}'
                    .format(model=self.name.lower())
                )
                model_class = getattr(m, self.name)

                if not is_created:
                    model_obj = session.query(model_class)\
                        .filter(model_class.mongo_id == model['_id'])\
                        .one()
                else:
                    model_obj = model_class()

                context = {}
                context['db_session'] = session
                context['author'] = login.current_user
                context['data'] = form.data
                context['save'] = True

                loop.run_until_complete(model_obj.validate_and_save(context))

                pk = model_obj.get_uid()
                self.coll.update({'_id': pk}, model)

            except Exception as e:
                if isinstance(e, exceptions.ServerBaseException):
                    flash(
                      gettext(
                        'Failed to update record. %(exception)s(%(error)s)',
                        exception=e.get_name(),
                        error=e
                      ),
                      'error'
                    )
                else:
                    flash(
                        gettext(
                            'Failed to update record. %(error)s',
                            error=e
                        ),
                        'error'
                    )
                return False
            else:
                self.after_model_change(form, model, True)

            return True
def test_confirm_email_right_token_wrong_user(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User)\
            .filter(User.email == '*****@*****.**').one()
        token = session.query(Emailconfirmationtoken)\
            .filter(Emailconfirmationtoken.user_uid == user.get_uid()).one()

    response = client.post_json('/api/confirm_email', {'token': token.token})

    assert response.status_code == 200
    assert not response.json['success']
    assert response.json['error'] == 'TokenViolationException'
def test_confirm_email_already_confirmed(client):
    user = client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        token = session.query(Emailconfirmationtoken)\
            .filter(Emailconfirmationtoken.user_uid == user.get_uid()).one()

    response = client.post_json('/api/confirm_email', {'token': token.token})

    assert response.status_code == 200
    assert response.json['success']

    response = client.post_json('/api/confirm_email', {'token': token.token})

    assert response.status_code == 200
    assert not response.json['success']
    assert response.json['error'] == 'TokenAlreadyUsedException'
Example #16
0
def test_crud_combination_multiple_model_multiple_action_by_user_some_allowed(
        client):  # noqa
    user = client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        admin = session.query(User) \
                .filter(User.email == '*****@*****.**').one()

    response = client.post_json(
        '/api/crud', {
            'token':
            client.__token__,
            'actions': [{
                'action': 'create',
                'model': 'user',
                'data': {
                    'email': '*****@*****.**',
                    'name': 'New test',
                    'password': '******'
                }
            }, {
                'action': 'read',
                'model': 'notification',
                'filters': {
                    'user_uid': user.get_uid()
                }
            }, {
                'action': 'update',
                'model': 'user',
                'uid': admin.get_uid(),
                'data': {
                    'name': 'New admin'
                }
            }]
        })
    assert response.status_code == 200
    assert not response.json['success']
    assert type(response.json['error']) == list
    assert len(response.json['error']) == 2
    assert response.json['error'][0] == 'NotAuthorizedException'
    assert response.json['error'][1] == 'NotAuthorizedException'
    assert response.json['results'][0]['error'] == 'NotAuthorizedException'
    assert response.json['results'][1]['total'] == 4
    assert response.json['results'][2]['error'] == 'NotAuthorizedException'
Example #17
0
def test_crud_delete_not_allowed_for_normal_user(client):
    user = client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        token = session.query(Emailconfirmationtoken) \
            .filter(Emailconfirmationtoken.user_uid == user.get_uid()).one()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'delete',
                'model': 'emailconfirmationtoken',
                'uid': token.get_uid()
            }
        })
    assert response.status_code == 200
    assert not response.json['success']
    assert response.json['error'] == 'NotAuthorizedException'
Example #18
0
def test_crud_read_specific_user_with_admin(client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
                .filter(User.email == '*****@*****.**').one()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'read',
                'model': 'user',
                'uid': user.get_uid()
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert len(response.json['results']) == 1
    assert response.json['results'][0]['name'] == 'test'
Example #19
0
def test_after_delete_and_before_delete_called(adm, bdm, client):
    client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user = session.query(User) \
                .filter(User.email == '*****@*****.**').one()

    user_uid = user.get_uid()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'delete',
                'model': 'user',
                'uid': user_uid
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert adm.called
    assert bdm.called
Example #20
0
def test_get_session_with_logged_disabled_user(client):
    user = client.login('*****@*****.**')

    # Get session
    data = {'user_timezone': 'Australia/Sydney'}
    response = client.post_json('/api/get_session', data)
    assert response.status_code == 200
    assert response.json['success']
    assert response.json['user']['email'] == user.email
    assert response.json['user']['name'] == user.name
    assert response.status_code == 200
    assert response.json['success']

    # Disable user
    with DbSessionContext(config.get('mongo_database_name')) as session:
        user.enable = False
        session.update(user)

    # Get session
    data = {'user_timezone': 'Australia/Sydney'}
    response = client.post_json('/api/get_session', data)
    assert not response.json['user']
    assert response.status_code == 200
    assert not response.json['success']

    # Login
    response = client.post_json(
        '/api/login',
        {
            'email': '*****@*****.**',
            'password': '******',
            'token': client.__token__
        }
    )
    assert response.status_code == 200
    assert not response.json['success']
    assert response.json['error'] == 'WrongEmailOrPasswordException'
Example #21
0
def test_crud_update_email(client):
    user = client.login('*****@*****.**')

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'update',
                'model': 'user',
                'uid': user.get_uid(),
                'data': {
                    'name': 'new_name',
                    'email': '*****@*****.**'
                }
            }
        })
    assert response.status_code == 200
    assert response.json['success']

    with DbSessionContext(config.get('mongo_database_name')) as session:
        user_query = session.query(User) \
            .filter(User.email == '*****@*****.**')
        assert user_query.count()

        user = user_query.one()

        assert user.name == 'new_name'
        assert not user.email_confirmed

        last_notification = session.query(Notification)\
            .filter(Notification.user_uid == user.get_uid())\
            .descending(Notification.created_ts)\
            .first()

        assert last_notification.message == \
            'notification.PleaseConfirmYourEmail'
Example #22
0
def test_crud_read_specific_notification(client):
    user = client.login('*****@*****.**')

    with DbSessionContext(config.get('mongo_database_name')) as session:
        notification = session.query(Notification)\
            .filter(Notification.user_uid == user.get_uid()).first()

    response = client.post_json(
        '/api/crud', {
            'token': client.__token__,
            'actions': {
                'action': 'read',
                'model': 'notification',
                'uid': notification.get_uid()
            }
        })
    assert response.status_code == 200
    assert response.json['success']
    assert type(response.json['results']) == list
    assert response.json['results'][0]['message'] == 'Test 1'
    assert response.json['results'][0]['uid'] == notification.get_uid()
    assert not response.json['results'][0]['seen']
    assert response.json['total'] == 1
    assert len(response.json['results']) == 1
Example #23
0
from server.settings import config  # noqa
from server.model.notification import Notification  # noqa
from server.utils import DbSessionContext  # noqa

config.configure()
loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)

if config.get('env', 'production') != 'development':
    print('The "env" variable is not set to development')
    sys.exit(1)

DB_NAME = config.get('mongo_database_name')
drop_database(DB_NAME, config.get('redis_database'))

with DbSessionContext(DB_NAME) as session:
    # INSERT DUMMY DATA
    users = [
        {
            'name': 'test',
            'email': '*****@*****.**',
            'email_validation_token': '123456',
            'password': '******'
        }, {
            'name': 'to.disable',
            'email': '*****@*****.**',
            'email_validation_token': '1337',
            'password': '******'
        }, {
            'name': 'admin',
            'email': '*****@*****.**',
Example #24
0
def client():
    loop = asyncio.get_event_loop()
    asyncio.set_event_loop(loop)

    config = {
        "env": "test",
        "mongo_database_name": "webbase_test",
        "redis_database": 13,
        "mongo_host": "127.0.0.1",
        "server_port": 1337,
        "server_host": "localhost"
    }

    drop_database(config.get('mongo_database_name'),
                  config.get('redis_database'))

    _, _, app = loop.run_until_complete(init(loop, config))

    with DbSessionContext(config.get('mongo_database_name')) as session:

        # INSERT DUMMY DATA
        users = [{
            'name': 'test',
            'email': '*****@*****.**',
            'email_validation_token': '123456',
            'password': '******'
        }, {
            'name': 'to.disable',
            'email': '*****@*****.**',
            'email_validation_token': '1337',
            'password': '******'
        }, {
            'name': 'admin',
            'email': '*****@*****.**',
            'password': '******',
            'role': 'admin'
        }, {
            'name': 'disabled',
            'email': '*****@*****.**',
            'password': '******',
            'enable': False
        }]

        notifications = [{
            'user_uid': None,
            'message': 'Test 1'
        }, {
            'user_uid': None,
            'message': 'Test 2'
        }, {
            'user_uid': None,
            'message': 'Test 3'
        }, {
            'user_uid': None,
            'message': 'Test 4',
            'seen': True
        }]

        for user_data in users:
            user = User()
            context = {
                'db_session': session,
                'method': 'create',
                'data': user_data
            }

            loop.run_until_complete(user.validate_and_save(context))

            context = {
                'db_session': session,
                'method': 'create',
                'data': {
                    'user_uid': user.get_uid()
                }
            }
            resetpasswordtoken = Resetpasswordtoken()
            loop.run_until_complete(
                resetpasswordtoken.validate_and_save(context))
            for notification_data in notifications:
                notification = Notification()
                notification_data['user_uid'] = user.get_uid()

                context = {
                    'db_session': session,
                    'method': 'create',
                    'data': notification_data
                }

                loop.run_until_complete(
                    notification.validate_and_save(context))

    def login(self, email, password='******'):
        self.post_json('/api/login', {
            'email': email,
            'password': password,
            'token': self.__token__
        })
        with DbSessionContext(
                self.config.get('mongo_database_name')) as session:
            user = session.query(User)\
                .filter(User.email == email).one()

        return user

    client = TestApp(app)
    client.config = config
    client.login = types.MethodType(login, client)

    # NOTE Always do an /api/get_session to init the session correctly
    data = {'user_timezone': 'Australia/Sydney'}
    response = client.post_json('/api/get_session', data)
    client.__token__ = response.json['token']

    return client