Exemple #1
0
def test_user_model_validates(user):
    """Tests user validator returns user after correct validation"""
    User.drop_collection()

    validated_user = _service.validate_user_model(user)

    assert isinstance(validated_user, User)
def test_can_authenticate_password():
    """Tests whether a users hashed password can be authenticated"""
    User.drop_collection()
    User(id=str(uuid4()),
         email="*****@*****.**",
         password=_service.hash_password("S0meFunkyP455")).save()
    result = User.objects(email="*****@*****.**").first()

    assert _service.check_password("S0meFunkyP455", result.password)
Exemple #3
0
def test_user_is_created():
    """Tests whether a user can be added to the database"""
    User.drop_collection()

    user = generate_user()
    user.save()

    result = User.objects(email=user.email).first()

    assert result.email == user.email
    def check_user_id_exists(self, id: str) -> bool:
        """Checks the user exists by id"""

        if User.objects(id__exists=id) is False:
            return False

        return True
Exemple #5
0
def seed_some_users(amount=50) -> None:
    me = User(id=str(uuid4()),
              email="*****@*****.**",
              password=_auth_service.hash_password("FunkyP455")).save()

    super_user = Role.objects(name="SuperUser").first()

    me.roles.append(super_user)

    me.save()

    for _ in range(amount):
        User(id=str(uuid4()),
             email=fake.ascii_company_email(),
             password=_auth_service.hash_password(
                 fake.password(length=10,
                               digits=True,
                               upper_case=True,
                               lower_case=True))).save()
Exemple #6
0
def generate_user():
    user = User(
        id=str(uuid4()),
        email=faker.ascii_company_email(),
        password=_auth_service.hash_password(
                    faker.password(length=10,
                                   digits=True,
                                   upper_case=True,
                                   lower_case=True)))
    return user
Exemple #7
0
def test_register_user_returns_correct_users_email():
    """Tests the user registration returns user"""
    user = {}
    user["email"] = "*****@*****.**"
    user["password"] = "******"

    _auth_repo.register_user(user)

    result = User.objects(email="*****@*****.**").first()

    assert result.email == "*****@*****.**"
Exemple #8
0
def test_can_add_role_to_user():
    role = _role_repo.create_new_role("Testing Role")

    user = User(
        id=str(uuid4()),
        email=faker.ascii_company_email(),
        password=_auth_service.hash_password(
                    faker.password(length=10,
                                   digits=True,
                                   upper_case=True,
                                   lower_case=True)))

    user.save()

    data = {}
    data["roleId"] = role.id
    data["userId"] = user.id

    result = _user_repo.add_role_to_user(data)

    assert result is not None
def test_can_login_user():
    """Tests successful login returns user"""
    user = User(id=str(uuid4()),
                email="*****@*****.**",
                password=_service.hash_password("S0meFunkyP455")).save()

    login_input = {}
    login_input["email"] = user.email
    login_input["password"] = "******"

    logged_in_user = _repo.login(login_input)

    assert logged_in_user.access_token is not None
def setup_logout_a_user(email: str):
    email = email

    token = _service.get_token(email)

    User(id=str(uuid4()),
         email=email,
         password=_service.hash_password("S0m3p4ss"),
         access_token=token).save()

    headers = {"authorization": "Bearer " + token}

    request = mock_context(headers)

    return request
Exemple #11
0
def test_can_update_users_email():
    user = User(
        id=str(uuid4()),
        email="*****@*****.**",
        password=_auth_service.hash_password("T35tpass")
    ).save()

    data = {}
    data["userId"] = user.id
    data["currentEmail"] = user.email
    data["newEmail"] = "*****@*****.**"
    data["password"] = "******"

    saved_user = _user_repo.update_email(data)

    assert saved_user.email == data["newEmail"]
    def check_email_exists(self, email: str) -> bool:
        """Checks to see if email exists in database"""

        # if User.objects(email__iexact=email) is True:
        #     return True

        # if User.objects(email__match=email) is True:
        #     return True

        # if User.objects(email__exists=email) is True:
        #     return True

        # only one that works correctly: ?

        if User.objects(email=email).first() is not None:
            return True

        return False
    def validate_user_model(self, user_input: dict) -> User:
        """ Validates the user model """

        id = str(uuid4())
        email = user_input["email"]
        password = user_input["password"]

        if self.check_email_exists(email):
            raise ValueError("Email already exists.")

        if not self.validate_email(email):
            raise ValueError("Valid email not supplied.")

        if not self.validate_password(password):
            raise ValueError("Password must contain 1 uppercase, 1 lowercase, "
                             "and either 1 number or 1 special character.")
        return User(id=id,
                    email=email,
                    password=self._auth_service.hash_password(password))
Exemple #14
0
    def login(self, data: dict) -> User:
        """
        Allows a user to login with email and password.
        """
        email = data["email"]
        password = data["password"]

        if email is None:
            raise ValueError("Email is required.")

        if password is None:
            raise ValueError("Password is required.")

        user = None

        if self._val_service.validate_email(email) is False:
            raise ValueError("Invalid email.")

        if self._val_service.check_email_exists(email) is False:
            raise ValueError("Login incorrect.")

        user = User.objects(email=email).first()

        if user is None:
            raise ValueError("Login incorrect")

        if self._val_service.validate_password(password) is False:
            raise ValueError("Invalid password.")

        if self._auth_service.check_password(password, user.password) is False:
            raise ValueError("Login incorrect.")

        token = self._auth_service.get_token(email)

        user.access_token = token
        user.updated_at = dt.datetime.utcnow()
        user.save()

        return user
Exemple #15
0
    def get_user_from_token(self, token: str) -> User:
        """Retrieves the tokens user from the database"""

        if token is None:
            raise ValueError("Token not found.")

        decoded = self.decode_jwt(token)

        email = decoded["email"]

        # We cannot refactor this to use the User repo as it adds a circular
        # dependency.
        user = User.objects(email=email).first()

        if user is not None:
            return user
        else:
            self._logger.log(
                LogEntry(
                    LogLevel.ERROR, __name__,
                    "We decoded a valid token but did not find the "
                    "user with corresponding email in the database!"))

        raise ValueError("User not found.")
Exemple #16
0
def seed_all(all_permissions: dict) -> None:
    User.drop_collection()
    Role.drop_collection()
    Permission.drop_collection()
    seed_roles_and_permissions(all_permissions)
    seed_some_users()
def register_test_db():
    connect(alias='default', host="mongodb://localhost/maintesoft_test")
    User.drop_collection()
    Role.drop_collection()
    Permission.drop_collection()
def drop_all_collections():
    User.drop_collection()
    Role.drop_collection()
    Permission.drop_collection()