async def test_registration_with_confirmation(client, capsys, monkeypatch):
    monkeypatch.setitem(cfg, "REGISTRATION_CONFIRMATION_REQUIRED", True)
    db = get_storage(client.app)
    url = client.app.router["auth_register"].url_for()
    r = await client.post(url,
                          json={
                              "email": EMAIL,
                              "password": PASSWORD,
                              "confirm": PASSWORD
                          })
    data, error = unwrap_envelope(await r.json())
    assert r.status == 200, (data, error)

    user = await db.get_user({"email": EMAIL})
    assert user["status"] == UserStatus.CONFIRMATION_PENDING.name

    assert "verification link" in data["message"]

    # retrieves sent link by email (see monkeypatch of email in conftest.py)
    out, err = capsys.readouterr()
    link = parse_link(out)
    assert "/auth/confirmation/" in str(link)
    resp = await client.get(link)
    text = await resp.text()

    assert "welcome to fake web front-end" in text
    assert resp.status == 200

    user = await db.get_user({"email": EMAIL})
    assert user["status"] == UserStatus.ACTIVE.name
    await db.delete_user(user)
Example #2
0
async def is_user_guest(app: web.Application, user_id: int) -> bool:
    """Returns True if the user exists and is a GUEST"""
    db = get_storage(app)
    user = await db.get_user({"id": user_id})
    if not user:
        logger.warning("Could not find user with id '%s'", user_id)
        return False

    return bool(UserRole(user["role"]) == UserRole.GUEST)
async def test_registration_with_existing_email(client):
    db = get_storage(client.app)
    url = client.app.router['auth_register'].url_for()
    async with NewUser() as user:
        r = await client.post(url, json={
            'email': user['email'],
            'password': user['raw_password'],
            'confirm': user['raw_password']
        })
    await assert_error(r, web.HTTPConflict, cfg.MSG_EMAIL_EXISTS)
Example #4
0
async def delete_user(app: web.Application, user_id: int) -> None:
    """Deletes a user from the database if the user exists"""
    db = get_storage(app)
    user = await db.get_user({"id": user_id})
    if not user:
        logger.warning(
            "User with id '%s' could not be deleted because it does not exist", user_id
        )
        return

    await db.delete_user(user)
async def test_registration_with_invitation(
    client,
    is_invitation_required,
    has_valid_invitation,
    expected_response,
):
    from servicelib.application_keys import APP_CONFIG_KEY
    from simcore_service_webserver.login.config import CONFIG_SECTION_NAME

    client.app[APP_CONFIG_KEY][CONFIG_SECTION_NAME] = {
        "registration_confirmation_required": False,
        "registration_invitation_required": is_invitation_required,
    }

    #
    # User gets an email with a link as
    #   https:/some-web-address.io/#/registration/?invitation={code}
    #
    # Front end then creates the following request
    #
    async with NewInvitation(client) as confirmation:
        print(get_confirmation_info(confirmation))

        url = client.app.router["auth_register"].url_for()

        r = await client.post(
            url,
            json={
                "email":
                EMAIL,
                "password":
                PASSWORD,
                "confirm":
                PASSWORD,
                "invitation":
                confirmation["code"] if has_valid_invitation else "WRONG_CODE",
            },
        )
        await assert_status(r, expected_response)

        # check optional fields in body
        if not has_valid_invitation or not is_invitation_required:
            r = await client.post(url,
                                  json={
                                      "email": "new-user" + EMAIL,
                                      "password": PASSWORD
                                  })
            await assert_status(r, expected_response)

        if is_invitation_required and has_valid_invitation:
            db = get_storage(client.app)
            assert not await db.get_confirmation(confirmation)
async def test_registration_with_existing_email(client):
    db = get_storage(client.app)
    url = client.app.router["auth_register"].url_for()
    async with NewUser() as user:
        r = await client.post(
            url,
            json={
                "email": user["email"],
                "password": user["raw_password"],
                "confirm": user["raw_password"],
            },
        )
    await assert_error(r, web.HTTPConflict, cfg.MSG_EMAIL_EXISTS)
async def test_registration_without_confirmation(client, monkeypatch):
    monkeypatch.setitem(cfg, "REGISTRATION_CONFIRMATION_REQUIRED", False)
    db = get_storage(client.app)
    url = client.app.router["auth_register"].url_for()
    r = await client.post(
        url, json={"email": EMAIL, "password": PASSWORD, "confirm": PASSWORD}
    )
    data, error = unwrap_envelope(await r.json())

    assert r.status == 200, (data, error)
    assert cfg.MSG_LOGGED_IN in data["message"]

    user = await db.get_user({"email": EMAIL})
    assert user
    await db.delete_user(user)
async def test_registration_with_expired_confirmation(client, monkeypatch):
    monkeypatch.setitem(cfg, 'REGISTRATION_CONFIRMATION_REQUIRED', True)
    monkeypatch.setitem(cfg, 'REGISTRATION_CONFIRMATION_LIFETIME', -1)

    db = get_storage(client.app)
    url = client.app.router['auth_register'].url_for()

    async with NewUser({'status': UserStatus.CONFIRMATION_PENDING.name}) as user:
        confirmation = await db.create_confirmation(user, ConfirmationAction.REGISTRATION.name)
        r = await client.post(url, json={
            'email': user['email'],
            'password': user['raw_password'],
            'confirm': user['raw_password'],
        })
        await db.delete_confirmation(confirmation)

    await assert_error(r, web.HTTPConflict, cfg.MSG_EMAIL_EXISTS)
Example #9
0
async def delete_user(app: web.Application, user_id: int) -> None:
    """Deletes a user from the database if the user exists"""
    # FIXME: user cannot be deleted without deleting first all ist project
    # otherwise this function will raise asyncpg.exceptions.ForeignKeyViolationError
    # Consider "marking" users as deleted and havning a background job that
    # cleans it up
    db: AsyncpgStorage = get_storage(app)
    user = await db.get_user({"id": user_id})
    if not user:
        logger.warning(
            "User with id '%s' could not be deleted because it does not exist",
            user_id)
        return

    await db.delete_user(user)

    # This user might be cached in the auth. If so, any request
    # with this user-id will get thru producing unexpected side-effects
    clean_auth_policy_cache(app)
async def test_registration_with_expired_confirmation(client, monkeypatch):
    monkeypatch.setitem(cfg, "REGISTRATION_CONFIRMATION_REQUIRED", True)
    monkeypatch.setitem(cfg, "REGISTRATION_CONFIRMATION_LIFETIME", -1)

    db = get_storage(client.app)
    url = client.app.router["auth_register"].url_for()

    async with NewUser({"status":
                        UserStatus.CONFIRMATION_PENDING.name}) as user:
        confirmation = await db.create_confirmation(
            user, ConfirmationAction.REGISTRATION.name)
        r = await client.post(
            url,
            json={
                "email": user["email"],
                "password": user["raw_password"],
                "confirm": user["raw_password"],
            },
        )
        await db.delete_confirmation(confirmation)

    await assert_error(r, web.HTTPConflict, cfg.MSG_EMAIL_EXISTS)
Example #11
0
async def test_logout(client):
    db = get_storage(client.app)

    logout_url = client.app.router["auth_logout"].url_for()
    protected_url = client.app.router["auth_change_email"].url_for()

    async with LoggedUser(client) as user:

        # try to access protected page
        r = await client.post(protected_url, json={"email": user["email"]})
        assert r.url_obj.path == protected_url.path
        await assert_status(r, web.HTTPOk)

        # logout
        r = await client.post(logout_url)
        assert r.url_obj.path == logout_url.path
        await assert_status(r, web.HTTPOk)

        # and try again
        r = await client.post(protected_url)
        assert r.url_obj.path == protected_url.path
        await assert_status(r, web.HTTPUnauthorized)

    await db.delete_user(user)
Example #12
0
 def __init__(self, params=None, app: web.Application = None):
     self.params = params
     self.user = None
     self.db = get_storage(app) if app else cfg.STORAGE  # FIXME: