def test_save_reset_password_fails_user_doesnt_exist(postgresql_db):
    session = postgresql_db.session
    create_reset_password_table(session)
    assert query_first_reset_password(session) is None

    email = '*****@*****.**'

    reset_password_to_save = ResetPassword(email)
    sut = ResetPasswordPersistence(postgresql_db)
    with pytest.raises(ResetPasswordForNonExistentUserException):
        sut.save(reset_password_to_save)
def test_get_reset_password_by_email_successfully(postgresql_db):
    session = postgresql_db.session
    create_reset_password_table(session)
    assert query_first_reset_password(session) is None

    email = '*****@*****.**'

    reset_password_to_save = ResetPassword(email)
    sut = ResetPasswordPersistence(postgresql_db)
    sut.save(reset_password_to_save)

    reset_password_obtained = email = '*****@*****.**'
    assert reset_password_obtained is not None
def test_save_reset_password_successfully(postgresql_db):
    session = postgresql_db.session
    create_reset_password_table(session)
    assert query_first_reset_password(session) is None

    email = '*****@*****.**'

    reset_password_to_save = ResetPassword(email)
    sut = ResetPasswordPersistence(postgresql_db)
    sut.save(reset_password_to_save)
    row = query_first_reset_password(session)
    assert row is not None
    assert row[1] == email
def _reset_password(user_email):

    logger.debug('Reset password request from user:{0}'.format(user_email))

    data = request.json
    token_received = data['token']
    password_received = data['new_password']

    reset_password_persistence = ResetPasswordPersistence(current_app.db)
    try:
        reset_password_obtained = reset_password_persistence.get_reset_password_by_email(
            user_email)
        if reset_password_obtained.token == token_received:
            if reset_password_obtained.is_token_expired():
                logger.debug('Token is expired')
                result = {'Error': 'token expired. Already sent new one'}
                status_code = HTTPStatus.UNAUTHORIZED
                _forgot_password(user_email)
            else:
                logger.debug('Valid token')
                user_persistence = UserPersistence(current_app.db)

                try:
                    user_persistence.change_password_for_user(
                        user_email, password_received)
                    reset_password_persistence.delete(user_email)
                    result = {
                        'Reset password':
                        '******'.format(user_email)
                    }
                    status_code = HTTPStatus.OK
                    logger.debug('Password updated')
                except CantChangePasswordForFirebaseUser:
                    logger.critical(
                        'Trying to change password for firebase user!')
                    result = {
                        'Error':
                        'user {0} is a firebase user'.format(user_email)
                    }
                    status_code = HTTPStatus.INTERNAL_SERVER_ERROR
                except UserNotFoundException:
                    logger.critical('Cant find user!')
                    result = {
                        'Error': 'user {0} doesnt exist'.format(user_email)
                    }
                    status_code = HTTPStatus.INTERNAL_SERVER_ERROR
                except ResetPasswordNotFoundException:
                    logger.critical('Cant reset password to delete!')
                    result = {
                        'Error':
                        'cant delete reset password request for user {0}'.
                        format(user_email)
                    }
                    status_code = HTTPStatus.INTERNAL_SERVER_ERROR
        else:
            logger.debug('The token {0} is NOT correct'.format(token_received))
            result = {'Error': 'token is NOT correct'}
            status_code = HTTPStatus.NOT_FOUND
    except ResetPasswordNotFoundException:
        logger.debug('This user didnt request to reset password')
        result = {
            'Error':
            'user {0} didnt request to reset password'.format(user_email)
        }
        status_code = HTTPStatus.NOT_FOUND

    return result, status_code
def _forgot_password(user_email):

    logger.debug('Forgot password request from user:{0}'.format(user_email))

    try:
        user_persistence = UserPersistence(current_app.db)
        user = user_persistence.get_user_by_email(user_email)

        if user.is_firebase_user():
            result = {
                "Error": "user {0} is a firebase user".format(user_email)
            }
            status_code = HTTPStatus.PRECONDITION_FAILED
            logger.debug('User is firebase user. Cant change password')
        else:
            reset_password_persistence = ResetPasswordPersistence(
                current_app.db)
            try:
                # Ya teniamos un codigo para resetear la pass de este usuario
                # Si esta vencido le damos uno nuevo y sino le mandamos el mismo
                reset_password_obtained = reset_password_persistence.get_reset_password_by_email(
                    user_email)
                logger.debug('User already has reset password')
                if reset_password_obtained.is_token_expired():
                    try:
                        logger.debug('Token expired. Regenerating new one')
                        reset_password_persistence.delete(user_email)
                        reset_password_updated = ResetPassword(user_email)
                        reset_password_persistence.save(reset_password_updated)

                        send_email_with_reset_password_token(
                            user_email, reset_password_updated.token)

                        result = {
                            "Forgot password":
                            "******".format(user_email)
                        }
                        status_code = HTTPStatus.OK
                        logger.debug(
                            'Email sent to user:{0}'.format(user_email))
                    except ResetPasswordNotFoundException:
                        logger.critical(
                            'Trying to delete non existent reset password')
                        result = {
                            "Error":
                            "couldnt update token for user {0}".format(
                                user_email)
                        }
                        status_code = HTTPStatus.INTERNAL_SERVER_ERROR
                    except ResetPasswordForNonExistentUserException:
                        logger.critical(
                            'Trying to generate reset password for inexistent user in Users table. Super critical!'
                        )
                        result = {
                            "Error":
                            "user {0} doesnt exist in table users".format(
                                user_email)
                        }
                        status_code = HTTPStatus.INTERNAL_SERVER_ERROR
                else:
                    logger.debug('Token is still valid. Sending email again')
                    send_email_with_reset_password_token(
                        user_email, reset_password_obtained.token)
                    result = {
                        "Forgot password":
                        "******".format(user_email)
                    }
                    status_code = HTTPStatus.OK
                    logger.debug('Email sent to user:{0}'.format(user_email))
            except ResetPasswordNotFoundException:
                # No tenemos un codigo activo para resetear la pass de este user
                # Creamos uno
                logger.debug('User hasnt reset password. Lets create one')
                try:
                    reset_password_to_save = ResetPassword(user_email)
                    reset_password_persistence.save(reset_password_to_save)

                    result = {
                        "Forgot password":
                        "******".format(user_email)
                    }
                    status_code = HTTPStatus.OK

                    send_email_with_reset_password_token(
                        user_email, reset_password_to_save.token)

                    logger.debug('Email sent to user:{0}'.format(user_email))
                except ResetPasswordForNonExistentUserException:
                    logger.critical(
                        'Trying to generate reset password for inexistent user in Users table!'
                    )
                    result = {
                        "Error":
                        "user {0} doesnt exist in table users".format(
                            user_email)
                    }
                    status_code = HTTPStatus.INTERNAL_SERVER_ERROR
    except UserNotFoundException:
        result = {"Error": "user {0} doesnt exist".format(user_email)}
        status_code = HTTPStatus.NOT_FOUND
        logger.debug('User doesnt exist')

    return result, status_code
def test_cant_delete_reset_password_with_given_email_not_found(postgresql_db):
    session = postgresql_db.session
    create_reset_password_table(session)
    sut = ResetPasswordPersistence(postgresql_db)
    with pytest.raises(ResetPasswordNotFoundException):
        user = sut.delete('*****@*****.**')
def test_reset_password_with_given_email_not_found(postgresql_db):
    session = postgresql_db.session
    create_reset_password_table(session)
    sut = ResetPasswordPersistence(postgresql_db)
    with pytest.raises(ResetPasswordNotFoundException):
        user = sut.get_reset_password_by_email('*****@*****.**')