Esempio n. 1
0
def test_link_orcid_auth_callback(name, mocker, client):
    """Test ORCID callback - the user authorized the organisation access to the ORCID profile."""
    mocker.patch("requests_oauthlib.OAuth2Session.fetch_token", lambda self, *args, **kwargs: dict(
        name="NEW TEST",
        access_token="ABC123",
        orcid="ABC-123-456-789",
        scope=["/read-limited"],
        expires_in="1212",
        refresh_token="ABC1235"))

    org = Organisation.get(name="THE ORGANISATION")
    test_user = User.create(
        name=name,
        email="*****@*****.**",
        organisation=org,
        orcid="ABC123",
        confirmed=True)
    UserOrg.create(user=test_user, org=org, affiliations=Affiliation.NONE)
    client.login(test_user)
    User.update(name=name).execute()
    resp = client.get("/link")
    state = session['oauth_state']
    resp = client.get(f"/auth?state={state}")
    assert resp.status_code == 302, "If the user is already affiliated, the user should be redirected ..."
    assert "profile" in resp.location, "redirection to 'profile' showing the ORCID"

    u = User.get(id=test_user.id)
    orcidtoken = OrcidToken.get(user=u)
    assert u.orcid == "ABC-123-456-789"
    assert orcidtoken.access_token == "ABC123"
    if name:
        assert u.name == name, "The user name should be changed"
    else:
        assert u.name == "NEW TEST", "the user name should be set from record coming from ORCID"
Esempio n. 2
0
def test_link_orcid_auth_callback_with_affiliation(name, request_ctx):
    """Test ORCID callback - the user authorized the organisation access to the ORCID profile."""
    with patch("orcid_hub.orcid_client.MemberAPI") as m, patch(
            "orcid_hub.orcid_client.SourceClientId"), request_ctx("/auth?state=xyz") as ctx:
        org = Organisation.create(
            name="THE ORGANISATION",
            confirmed=True,
            orcid_client_id="CLIENT ID",
            city="CITY",
            country="COUNTRY",
            disambiguated_id="ID",
            disambiguation_source="SOURCE")

        test_user = User.create(
            name=name,
            email="*****@*****.**",
            organisation=org,
            orcid="ABC123",
            confirmed=True)

        UserOrg.create(user=test_user, org=org, affiliations=Affiliation.EMP | Affiliation.EDU)

        login_user(test_user, remember=True)
        session['oauth_state'] = "xyz"
        api_mock = m.return_value
        ctx.app.full_dispatch_request()
        assert test_user.orcid == "ABC-123-456-789"

        orcid_token = OrcidToken.get(user=test_user, org=org)
        assert orcid_token.access_token == "ABC123"

        api_mock.create_or_update_affiliation.assert_has_calls([
            call(affiliation=Affiliation.EDU, initial=True),
            call(affiliation=Affiliation.EMP, initial=True),
        ])
Esempio n. 3
0
def test_link_orcid_auth_callback(name, request_ctx):
    """Test ORCID callback - the user authorized the organisation access to the ORCID profile."""
    with request_ctx("/auth?state=xyz") as ctx:
        org = Organisation(name="THE ORGANISATION", confirmed=True)
        org.save()

        test_user = User.create(
            name=name,
            email="*****@*****.**",
            organisation=org,
            orcid="ABC123",
            confirmed=True)
        orcidtoken = OrcidToken.create(
            user=test_user,
            org=org,
            scope="/read-limited,/activities/update",
            access_token="ABC1234")
        login_user(test_user, remember=True)
        session['oauth_state'] = "xyz"
        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 302, "If the user is already affiliated, the user should be redirected ..."
        assert "profile" in rv.location, "redirection to 'profile' showing the ORCID"

        u = User.get(id=test_user.id)
        orcidtoken = OrcidToken.get(user=u)
        assert u.orcid == "ABC-123-456-789"
        assert orcidtoken.access_token == "ABC1234"
        if name:
            assert u.name == name, "The user name should be changed"
        else:
            assert u.name == "NEW TEST", "the user name should be set from record coming from ORCID"
Esempio n. 4
0
def test_link_orcid_auth_callback_with_affiliation(name, request_ctx):
    """Test ORCID callback - the user authorized the organisation access to the ORCID profile."""
    with patch("orcid_hub.orcid_client.MemberAPI") as m, patch(
            "orcid_hub.orcid_client.SourceClientId"), request_ctx(
                "/auth?state=xyz") as ctx:
        org = Organisation.get(name="THE ORGANISATION")
        test_user = User.create(name=name,
                                email="*****@*****.**",
                                organisation=org,
                                orcid="ABC123",
                                confirmed=True)

        UserOrg.create(user=test_user,
                       org=org,
                       affiliations=Affiliation.EMP | Affiliation.EDU)

        login_user(test_user, remember=True)
        session['oauth_state'] = "xyz"
        api_mock = m.return_value
        ctx.app.full_dispatch_request()
        assert test_user.orcid == "ABC-123-456-789"

        orcid_token = OrcidToken.get(user=test_user, org=org)
        assert orcid_token.access_token == "ABC123"

        api_mock.create_or_update_affiliation.assert_has_calls([
            call(affiliation=Affiliation.EDU, initial=True),
            call(affiliation=Affiliation.EMP, initial=True),
        ])
        # User with no Affiliation, should get flash warning.
        user_org = UserOrg.get(user=test_user, org=org)
        user_org.affiliations = Affiliation.NONE
        user_org.save()
        orcid_token.delete_instance()
        resp = ctx.app.full_dispatch_request()
        assert resp.status_code == 302
        assert b"<!DOCTYPE HTML" in resp.data, "Expected HTML content"
        assert "profile" in resp.location, "redirection to 'profile' showing the ORCID"
Esempio n. 5
0
def test_link_orcid_auth_callback_with_affiliation(name, mocker, client):
    """Test ORCID callback - the user authorized the organisation access to the ORCID profile."""
    mocker.patch("requests_oauthlib.OAuth2Session.fetch_token", lambda self, *args, **kwargs: dict(
        name="NEW TEST",
        access_token="ABC123",
        orcid="ABC-123-456-789",
        scope=['/read-limited,/activities/update'],
        expires_in="1212",
        refresh_token="ABC1235"))
    m = mocker.patch("orcid_hub.orcid_client.MemberAPI")
    mocker.patch("orcid_hub.orcid_client.SourceClientId")

    org = Organisation.get(name="THE ORGANISATION")
    test_user = User.create(
        name=name,
        email="*****@*****.**",
        organisation=org,
        orcid="ABC123",
        confirmed=True)

    UserOrg.create(user=test_user, org=org, affiliations=Affiliation.EMP | Affiliation.EDU)

    client.login(test_user)
    resp = client.get("/link")
    state = session['oauth_state']

    resp = client.get(f"/auth?state={state}")
    api_mock = m.return_value
    test_user = User.get(test_user.id)
    assert test_user.orcid == "ABC-123-456-789"

    orcid_token = OrcidToken.get(user=test_user, org=org)
    assert orcid_token.access_token == "ABC123"

    api_mock.create_or_update_affiliation.assert_has_calls([
        call(affiliation=Affiliation.EDU, initial=True),
        call(affiliation=Affiliation.EMP, initial=True),
    ])

    # User with no Affiliation, should get flash warning.
    user_org = UserOrg.get(user=test_user, org=org)
    user_org.affiliations = Affiliation.NONE
    user_org.save()
    orcid_token.delete_instance()

    assert OrcidToken.select().where(OrcidToken.user == test_user, OrcidToken.org == org).count() == 0
    resp = client.get(f"/auth?state={state}")
    assert resp.status_code == 302
    assert b"<!DOCTYPE HTML" in resp.data, "Expected HTML content"
    assert "profile" in resp.location, "redirection to 'profile' showing the ORCID"
    assert OrcidToken.select().where(OrcidToken.user == test_user, OrcidToken.org == org).count() == 1

    get_person = mocker.patch("requests_oauthlib.OAuth2Session.get", return_value=Mock(status_code=200))
    resp = client.get(f"/profile", follow_redirects=True)
    assert b"can create and update research activities" in resp.data
    get_person.assert_called_once()

    get_person = mocker.patch("requests_oauthlib.OAuth2Session.get", return_value=Mock(status_code=401))
    resp = client.get(f"/profile", follow_redirects=True)
    assert b"you'll be taken to ORCID to create or sign into your ORCID record" in resp.data
    get_person.assert_called_once()
Esempio n. 6
0
def test_user_and_token_api(client, resource, version):
    """Test the echo endpoint."""
    user = User.get(email="*****@*****.**")
    org2_user = User.get(email="*****@*****.**")
    resp = client.get(f"/api/{version}/{resource}/ABC123",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 400
    assert "error" in resp.json
    assert "incorrect identifier" in resp.json["error"].lower()

    resp = client.get(f"/api/{version}/{resource}/0000-0000-0000-0000",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 400
    assert "error" in resp.json
    assert "incorrect identifier" in resp.json["error"].lower()

    resp = client.get(f"/api/{version}/{resource}/[email protected]",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 404
    assert "error" in resp.json
    assert "not found" in resp.json["error"].lower()

    resp = client.get(f"/api/{version}/{resource}/0000-0000-0000-0001",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 404
    assert "error" in resp.json
    assert "not found" in resp.json["error"].lower()

    for identifier in [
            user.email,
            user.orcid,
    ]:
        resp = client.get(f"/api/{version}/{resource}/{identifier}",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        if resource == "users":
            assert resp.json["email"] == user.email
            assert resp.json["eppn"] == user.eppn
            assert resp.json["orcid"] == user.orcid
        else:
            token = OrcidToken.get(user_id=user.id)
            assert resp.json["access_token"] == token.access_token

    if resource == "users":  # test user listing
        resp = client.get(f"/api/{version}/{resource}",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 11

        resp = client.get(
            f"/api/{version}/{resource}?page=INVALID&page_size=INVALID",
            headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 11

        resp = client.get(f"/api/{version}/{resource}?page=2&page_size=3",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 3

        resp = client.get(f"/api/{version}/{resource}?page_size=3",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 3

        resp = client.get(f"/api/{version}/{resource}?page=42",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 0

        resp = client.get(f"/api/{version}/{resource}?from_date=ABCD",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 422

        resp = client.get(f"/api/{version}/{resource}?from_date=2018-01-01",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 4

        resp = client.get(f"/api/{version}/{resource}?to_date=2018-01-01",
                          headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 7

        resp = client.get(
            f"/api/{version}/{resource}?from_date=2017-12-20&to_date=2017-12-21",
            headers=dict(authorization="Bearer TEST"))
        assert resp.status_code == 200
        assert len(resp.json) == 2

    if resource == "tokens":
        user2 = User.get(email="*****@*****.**")
        for identifier in [
                user2.email,
                user2.orcid,
        ]:
            resp = client.get(f"/api/{version}/tokens/{identifier}",
                              headers=dict(authorization="Bearer TEST"))
            assert resp.status_code == 404
            assert "error" in resp.json

    resp = client.get(f"/api/{version}/{resource}/{org2_user.email}",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 404
    assert "error" in resp.json
Esempio n. 7
0
def test_user_and_token_api(app_req_ctx, resource, version):
    """Test the echo endpoint."""
    user = User.get(email="*****@*****.**")
    org2_user = User.get(email="*****@*****.**")
    with app_req_ctx(f"/api/{version}/{resource}/ABC123",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        resp = ctx.app.full_dispatch_request()
        assert resp.status_code == 400
        data = json.loads(resp.data)
        assert "error" in data
        assert "incorrect identifier" in data["error"].lower()
    with app_req_ctx(f"/api/{version}/{resource}/0000-0000-0000-0000",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        resp = ctx.app.full_dispatch_request()
        assert resp.status_code == 400
        data = json.loads(resp.data)
        assert "error" in data
        assert "incorrect identifier" in data["error"].lower()
    with app_req_ctx(f"/api/{version}/{resource}/[email protected]",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        resp = ctx.app.full_dispatch_request()
        assert resp.status_code == 404
        data = json.loads(resp.data)
        assert "error" in data
        assert "not found" in data["error"].lower()
    with app_req_ctx(f"/api/{version}/{resource}/0000-0000-0000-0001",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        resp = ctx.app.full_dispatch_request()
        assert resp.status_code == 404
        data = json.loads(resp.data)
        assert "error" in data
        assert "not found" in data["error"].lower()
    for identifier in [
            user.email,
            user.orcid,
    ]:
        with app_req_ctx(f"/api/{version}/{resource}/{identifier}",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            if resource == "users":
                assert data["email"] == user.email
                assert data["eppn"] == user.eppn
                assert data["orcid"] == user.orcid
            else:
                token = OrcidToken.get(user_id=user.id)
                assert data["access_token"] == token.access_token
    if resource == "users":  # test user listing
        with app_req_ctx(f"/api/{version}/{resource}",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            assert len(data) == 11
        with app_req_ctx(f"/api/{version}/{resource}?page=2&page_size=3",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            assert len(data) == 3
        with app_req_ctx(f"/api/{version}/{resource}?page_size=3",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            assert len(data) == 3
        with app_req_ctx(f"/api/{version}/{resource}?page=42",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            assert len(data) == 0
        with app_req_ctx(f"/api/{version}/{resource}?from_date=ABCD",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 422
        with app_req_ctx(f"/api/{version}/{resource}?from_date=2018-01-01",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            assert len(data) == 4
        with app_req_ctx(f"/api/{version}/{resource}?to_date=2018-01-01",
                         headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            assert len(data) == 7
        with app_req_ctx(
                f"/api/{version}/{resource}?from_date=2017-12-20&to_date=2017-12-21",
                headers=dict(authorization="Bearer TEST")) as ctx:
            resp = ctx.app.full_dispatch_request()
            data = json.loads(resp.data)
            assert resp.status_code == 200
            data = json.loads(resp.data)
            assert len(data) == 2

    if resource == "tokens":
        user2 = User.get(email="*****@*****.**")
        for identifier in [
                user2.email,
                user2.orcid,
        ]:
            with app_req_ctx(f"/api/{version}/tokens/{identifier}",
                             headers=dict(authorization="Bearer TEST")) as ctx:
                resp = ctx.app.full_dispatch_request()
                assert resp.status_code == 404
                data = json.loads(resp.data)
                assert "error" in data

    with app_req_ctx(f"/api/{version}/{resource}/{org2_user.email}",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        resp = ctx.app.full_dispatch_request()
        assert resp.status_code == 404
        data = json.loads(resp.data)
        assert "error" in data