Exemple #1
0
def test_tuakiri_login_usgin_eppn(client):
    """Test logging attempt via Shibboleth using differt values to identify the user."""
    org = Organisation(tuakiri_name="ORGANISATION 123ABC")
    org.save()
    user = User.create(email="*****@*****.**",
                       eppn="*****@*****.**",
                       roles=Role.RESEARCHER)
    user.save()

    rv = client.get("/Tuakiri/login",
                    headers={
                        "Auedupersonsharedtoken": "ABC123",
                        "Sn": "LAST NAME/SURNAME/FAMILY NAME",
                        'Givenname': "FIRST NAME/GIVEN NAME",
                        "Mail": "*****@*****.**",
                        "O": "ORGANISATION 123ABC",
                        "Displayname": "TEST USER FROM 123",
                        "Unscoped-Affiliation": "staff",
                        "Eppn": "*****@*****.**"
                    })

    assert rv.status_code == 302
    u = User.get(eppn="*****@*****.**")
    assert u.email == "*****@*****.**"
    assert u.name == "TEST USER FROM 123", "Expected to have the user in the DB"
    assert u.first_name == "FIRST NAME/GIVEN NAME"
    assert u.last_name == "LAST NAME/SURNAME/FAMILY NAME"
Exemple #2
0
def test_link_already_affiliated(request_ctx):
    """Test a user affiliation initialization if the uerer is already affilated."""
    with request_ctx("/link") as ctx:
        org = Organisation(name="THE ORGANISATION", confirmed=True, orcid_client_id="ABC123")
        org.save()
        test_user = User(
            email="*****@*****.**",
            name="TEST USER",
            organisation=org,
            orcid="ABC123",
            confirmed=True)
        test_user.save()
        orcidtoken = OrcidToken(
            user=test_user, org=org, scope="/read-limited", access_token="ABC1234")
        orcidtoken_write = OrcidToken(
            user=test_user,
            org=org,
            scope="/read-limited,/activities/update",
            access_token="ABC234")
        orcidtoken.save()
        orcidtoken_write.save()
        login_user(test_user, remember=True)
        uo = UserOrg(user=test_user, org=org)
        uo.save()

        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"
Exemple #3
0
def test_tuakiri_login_with_org(client):
    """
    Test logging attempt via Shibboleth.

    If a user logs in from an organisation that isn't
    onboared, the user should be informed about that and
    redirected to the login page.
    """
    org = Organisation(tuakiri_name="THE ORGANISATION", confirmed=True)
    org.save()

    rv = client.get("/Tuakiri/login",
                    headers={
                        "Auedupersonsharedtoken": "ABC111",
                        "Sn": "LAST NAME/SURNAME/FAMILY NAME",
                        'Givenname': "FIRST NAME/GIVEN NAME",
                        "Mail": "*****@*****.**",
                        "O": "THE ORGANISATION",
                        "Displayname": "TEST USER FROM THE ORGANISATION",
                        "Unscoped-Affiliation": "staff",
                        "Eppn": "*****@*****.**"
                    },
                    follow_redirects=True)

    u = User.get(email="*****@*****.**")
    assert u.organisation == org
    assert org in u.organisations
    assert b"Your organisation (THE ORGANISATION) is not onboarded" not in rv.data
    uo = UserOrg.get(user=u, org=org)
    assert not uo.is_admin
Exemple #4
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"
Exemple #5
0
def test_db_api(app_req_ctx):
    """Test DB API."""
    with app_req_ctx("/data/api/v0.1/organisations/",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 200
        data = json.loads(rv.data)
        assert "objects" in data
        assert len(data["objects"]) == 4

    with app_req_ctx("/data/api/v0.1/tasks/",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 200
        data = json.loads(rv.data)
        assert "objects" in data
        assert len(data["objects"]) == 0

    org = Organisation.get(id=1)
    with app_req_ctx(f"/data/api/v0.1/organisations/{org.id}",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 200
        data = json.loads(rv.data)
        assert data["name"] == org.name
        assert data["tuakiri_name"] == org.tuakiri_name

    org = Organisation.get(id=2)
    with app_req_ctx(f"/data/api/v0.1/organisations/{org.id}",
                     headers=dict(authorization="Bearer TEST")) as ctx:
        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 200
        data = json.loads(rv.data)
        assert data["name"] == org.name
        assert data["tuakiri_name"] == org.tuakiri_name
Exemple #6
0
def test_tuakiri_login_by_techical_contact_organisation_not_onboarded(client):
    """Test logging attempt by technical contact when organisation is not onboarded."""
    org = Organisation(name="Org112",
                       tuakiri_name="Org112",
                       confirmed=False,
                       is_email_sent=True)
    u = User(email="*****@*****.**",
             confirmed=True,
             roles=Role.TECHNICAL,
             organisation=org)
    org.tech_contact = u
    org.save()

    UserOrg(user=u, org=org, is_admin=True)
    rv = client.get("/Tuakiri/login",
                    headers={
                        "Auedupersonsharedtoken": "ABC11s1",
                        "Sn": "LAST NAME/SURNAME/FAMILY NAME",
                        'Givenname': "FIRST NAME/GIVEN NAME",
                        "Mail": "*****@*****.**",
                        "O": "Org112",
                        "Displayname": "TEST USER FROM THE Org112",
                        "Unscoped-Affiliation": "student",
                        "Eppn": "*****@*****.**"
                    },
                    follow_redirects=True)

    assert u.organisation == org
    assert not org.confirmed
    assert u.is_tech_contact_of(org)
    assert rv.status_code == 200
    assert b"<!DOCTYPE html>" in rv.data, "Expected HTML content"
def test_db_api(client):
    """Test DB API."""
    resp = client.get("/data/api/v0.1/organisations/",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 200
    assert "objects" in resp.json
    assert len(resp.json["objects"]) == 4

    resp = client.get("/data/api/v0.1/tasks/",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 200
    assert "objects" in resp.json
    assert len(resp.json["objects"]) == 0

    org = Organisation.select().where(
        Organisation.tuakiri_name.is_null(False)).first()
    resp = client.get(f"/data/api/v0.1/organisations/{org.id}",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 200
    assert resp.json["name"] == org.name
    assert resp.json["tuakiri_name"] == org.tuakiri_name

    org = Organisation.select().where(Organisation.tuakiri_name.is_null(False),
                                      Organisation.id != org.id).first()
    resp = client.get(f"/data/api/v0.1/organisations/{org.id}",
                      headers=dict(authorization="Bearer TEST"))
    assert resp.status_code == 200
    assert resp.json["name"] == org.name
    assert resp.json["tuakiri_name"] == org.tuakiri_name
Exemple #8
0
def test_test_database(models):
    """Test of the consitency of the test database."""
    assert Organisation.select().count() == 10
    assert User.select().count() == 63
    assert OrcidToken.select().count() == 60
    assert AffiliationRecord.select().count() == 10
    assert FundingRecord.select().count() == 10
    assert FundingContributor.select().count() == 10
    assert FundingInvitee.select().count() == 10
    assert ExternalId.select().count() == 10
    assert WorkRecord.select().count() == 10
    assert WorkContributor.select().count() == 10
    assert WorkExternalId.select().count() == 10
    assert WorkInvitee.select().count() == 10
    assert PeerReviewRecord.select().count() == 10
    assert PeerReviewExternalId.select().count() == 10
    assert PeerReviewInvitee.select().count() == 10
    assert ResearcherUrlRecord.select().count() == 10
    assert OtherNameRecord.select().count() == 10
    assert KeywordRecord.select().count() == 10
    assert Task.select().count() == 30
    assert UserOrgAffiliation.select().count() == 30

    assert User.get(id=43).admin_for.count() == 10
    assert User.get(id=1).admin_for.count() == 0
    assert User.get(id=42).admin_for.count() > 0
    assert User.get(id=2).organisations.count() > 0
    assert Organisation.get(id=1).admins.count() == 1
    assert Organisation.get(id=5).users.count() > 0
    assert Organisation.get(id=5).admins.count() > 0
    assert User.select().where(User.orcid == User.get(
        email="*****@*****.**").orcid).count() == 3
    assert len(User.get(email="*****@*****.**").org_links) == 3

    user = User.get(email="*****@*****.**")
    available_organisations = user.available_organisations
    assert available_organisations.count() == 10

    admin = User.create(email="*****@*****.**", organisation=user.organisation, confirmed=True,
            first_name="TEST", last_name="ADMIN", roles=Role.ADMIN)
    ui = UserInvitation.create(email=user.email, invitee=user, inviter=admin, token="TOKEN-123")
    admin.delete_instance()
    ui = UserInvitation.get(ui.id)
    assert ui.inviter_id is None
    user.delete_instance()
    assert not UserInvitation.select().where(UserInvitation.id == ui.id).exists()

    org = Organisation.select().limit(1).first()
    user = User.select().limit(1).first()
    ot = OrcidToken.create(user=user, org=org, scope="S1,S2,S3")
    assert len(ot.scopes) == 3

    ot.scopes = ["A", "B", "C", "D"]
    assert ot.scope == "A,B,C,D"
Exemple #9
0
def test_profile_wo_orcid(request_ctx):
    """Test a user profile that doesn't hava an ORCID."""
    with request_ctx("/profile") as ctx:
        org = Organisation(name="THE ORGANISATION", confirmed=True)
        org.save()
        test_user = User(
            email="*****@*****.**", organisation=org, orcid=None, confirmed=True)
        test_user.save()
        login_user(test_user, remember=True)

        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 302
        assert rv.location == url_for("link")
Exemple #10
0
def test_link_with_unconfirmed_org(request_ctx):
    """Test a user affiliation initialization if the user Organisation isn't registered yet."""
    with request_ctx("/link") as ctx:
        org = Organisation(
            name="THE ORGANISATION", confirmed=False, orcid_client_id="Test Client id")
        org.save()
        test_user = User(
            name="TEST USER", email="*****@*****.**", confirmed=True, organisation=org)
        test_user.save()
        login_user(test_user, remember=True)

        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 302
Exemple #11
0
def test_user_org_link(test_models):
    assert User.get(id=43).admin_for.count() == 10
    assert User.get(id=1).admin_for.count() == 0
    assert User.get(id=42).admin_for.count() > 0
    assert User.get(id=2).organisations.count() > 0
    assert Organisation.get(id=1).admins.count() == 1
    assert Organisation.get(id=5).users.count() > 0
    assert Organisation.get(id=5).admins.count() > 0
    assert len(
        User.get(email="*****@*****.**").linked_accounts) == 3

    user = User.get(email="*****@*****.**")
    available_organisations = user.available_organisations
    assert available_organisations.count() == 10
Exemple #12
0
def test_org_switch(client):
    """Test organisation switching."""
    user = User.get(orcid=User.select(fn.COUNT(User.orcid).alias("id_count"), User.orcid).group_by(
        User.orcid).having(fn.COUNT(User.orcid) > 1).naive().first().orcid)
    user_orgs = UserOrg.select().join(User).where(User.orcid == user.orcid)
    new_org = Organisation.select().where(Organisation.id.not_in([uo.org_id for uo in user_orgs])).first()
    UserOrg.create(user=user, org=new_org, affiliations=0)

    resp = client.login(user, follow_redirects=True)
    assert user.email.encode() in resp.data
    assert len(user.org_links) > 1
    assert current_user == user

    # Nothing changes if it is the same organisation
    uo = user.userorg_set.where(UserOrg.org_id == user.organisation_id).first()
    resp = client.get(f"/select/user_org/{uo.id}", follow_redirects=True)
    assert User.get(user.id).organisation_id == user.organisation_id
    assert user.email.encode() in resp.data

    # The current org changes if it's a dirrerent org on the list
    uo = user.userorg_set.where(UserOrg.org_id != user.organisation_id).first()
    resp = client.get(f"/select/user_org/{uo.id}", follow_redirects=True)
    assert User.get(user.id).organisation_id != user.organisation_id
    assert User.get(user.id).organisation_id == uo.org_id

    for ol in user.org_links:
        assert ol.org.name.encode() in resp.data
        if UserOrg.get(ol.id).user.id != user.id:
            next_ol = ol

    # Shoud be a totally different user account:
    resp = client.get(f"/select/user_org/{next_ol.id}", follow_redirects=True)
    next_user = UserOrg.get(next_ol.id).user
    assert next_user.id != user.id
def test_process_tasks(app, mocker):
    """Test task hanging."""
    send_email = mocker.patch("orcid_hub.utils.send_email")
    org = Organisation.select().first()
    Task.insert_many(
        dict(org=org,
             updated_at=utils.datetime.utcnow(),
             filename=tt.name,
             task_type=tt.value) for tt in TaskType).execute()
    utils.process_tasks()
    send_email.assert_not_called()

    Task.insert_many(
        dict(org=org,
             created_by=org.tech_contact,
             created_at=utils.datetime(2017, 1, 1),
             updated_at=utils.datetime(2017, 1, 1),
             filename=tt.name,
             task_type=tt.value) for tt in TaskType).execute()
    utils.process_tasks()
    send_email.assert_called()

    task_count = Task.select().count()
    utils.process_tasks()
    assert Task.select().count() == task_count // 2
Exemple #14
0
def test_orcid_login(client):
    """Test login from orcid."""
    org = Organisation.get(name="THE ORGANISATION")
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.TECHNICAL,
                    orcid="123",
                    confirmed=True,
                    organisation=org)
    user_org = UserOrg.create(user=u, org=org, is_admin=True)

    resp = client.get("/orcid/login/NOT-EXISTTING", follow_redirects=True)
    assert resp.status_code == 200
    assert b"Failed to login via ORCID using token NOT-EXISTTING" in resp.data

    token = "TOKEN-1234567"
    ui = UserInvitation.create(org=org, invitee=u, email=u.email, token=token)
    resp = client.get(f"/orcid/login/{token}")
    assert resp.status_code == 200
    orcid_authorize = OrcidAuthorizeCall.get(method="GET")
    assert "&email=test123_test_orcid_login%40test.test.net" in orcid_authorize.url
    ui.created_at -= timedelta(days=100)
    ui.save()
    resp = client.get(f"/orcid/login/{token}")
    assert resp.status_code == 302
    url = urlparse(resp.location)
    assert url.path == '/'
    # Testing the expired token flow for researcher
    user_org.is_admin = False
    user_org.save()
    resp = client.get(f"/orcid/login/{token}")
    assert resp.status_code == 302
    url = urlparse(resp.location)
    assert url.path == '/'
def test_profile(client):
    """Test an affilated user profile and ORCID data retrieval and a user profile that doesn't hava an ORCID."""
    org = Organisation.get(name="THE ORGANISATION")
    test_user = User.create(email="*****@*****.**",
                            organisation=org,
                            orcid="ABC123",
                            confirmed=True)
    OrcidToken.create(user=test_user,
                      org=org,
                      scope="/read-limited,/activities/update",
                      access_token="ABC1234")
    resp = client.login(test_user, follow_redirects=True)
    resp = client.get("/profile", follow_redirects=True)

    assert resp.status_code == 200
    assert b"ABC123" in resp.data
    client.logout()

    # Test a user profile that doesn't hava an ORCID.
    user = User.select().where(User.organisation == org,
                               User.orcid.is_null()).first()
    resp = client.login(user, follow_redirects=True)
    resp = client.get("/profile")
    assert resp.status_code == 302
    assert "/link" in resp.location
Exemple #16
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),
        ])
Exemple #17
0
def test_logout(client):
    """Test to logout."""
    org = Organisation.create(name="THE ORGANISATION:test_logout",
                              tuakiri_name="University of Auckland",
                              confirmed=True,
                              is_email_sent=True)
    user = User.create(email="*****@*****.**",
                       name="TEST USER",
                       roles=Role.TECHNICAL,
                       confirmed=True,
                       organisation=org)

    client.login(user)
    resp = client.get("/logout")
    # UoA user:
    assert resp.status_code == 302
    assert "Shibboleth.sso" in resp.location
    assert "uoa-slo" in resp.location

    org.tuakiri_name = org.name
    org.save()
    client.login(user)
    resp = client.get("/logout")
    # non-UoA user:
    assert resp.status_code == 302
    assert "Shibboleth.sso" in resp.location
    assert "uoa-slo" not in resp.location
Exemple #18
0
def test_orcid_callback(client, mocker):
    """Test orcid researcher deny flow."""
    org = Organisation.create(
        name="THE ORGANISATION:test_orcid_callback",
        tuakiri_name="THE ORGANISATION:test_orcid_callback",
        confirmed=True,
        orcid_client_id="CLIENT ID",
        orcid_secret="Client Secret",
        city="CITY",
        country="COUNTRY",
        disambiguated_id="ID",
        disambiguation_source="RINGGOLD",
        is_email_sent=True)
    user = User.create(email="*****@*****.**",
                       name="TEST USER",
                       roles=Role.TECHNICAL,
                       orcid="123",
                       confirmed=True,
                       organisation=org)
    UserOrg.create(user=user, org=org, is_admin=True)

    client.login(user)
    resp = client.get("/auth?error=access_denied&login=2")
    assert resp.status_code == 302
    assert "/link" in resp.location
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"
Exemple #20
0
def test_orcid_callback(request_ctx):
    """Test orcid researcher deny flow."""
    org = Organisation.create(name="THE ORGANISATION",
                              tuakiri_name="THE ORGANISATION",
                              confirmed=True,
                              orcid_client_id="CLIENT ID",
                              orcid_secret="Client Secret",
                              city="CITY",
                              country="COUNTRY",
                              disambiguated_id="ID",
                              disambiguation_source="SOURCE",
                              is_email_sent=True)

    user = User.create(email="*****@*****.**",
                       name="TEST USER",
                       roles=Role.TECHNICAL,
                       orcid="123",
                       confirmed=True,
                       organisation=org)
    UserOrg.create(user=user, org=org, is_admin=True)

    with request_ctx("/auth") as ctx:
        login_user(user, remember=True)
        request.args = ImmutableMultiDict([('error', 'access_denied'),
                                           ('login', '2')])
        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 302
        assert rv.location.startswith("/link")
Exemple #21
0
def test_upload_affiliation_with_wrong_country(request_ctx, mocker):
    """Test task loading and processing with failures."""
    org = Organisation.get(name="TEST0")
    super_user = User.get(email="*****@*****.**")
    with request_ctx("/") as ctx:
        exception = mocker.patch.object(ctx.app.logger, "exception")
        login_user(super_user)
        # flake8: noqa
        with pytest.raises(ModelException):
            task = Task.load_from_csv(
                """First name\tLast name\temail address\tOrganisation\tCampus/Department\tCity\tCourse or Job title\tStart date\tEnd date\tStudent/Staff\tCountry
FNA\tLBA\[email protected]\tTEST1\tResearch Funding\tWellington\tProgramme Manager - ORCID\t2016-09 19:00:00 PM\t\tStaff\tNO COUNTRY
        """,
                filename="TEST.tsv",
                org=org)

        # this should work:
        task = Task.load_from_csv(
            """First name\tLast name\temail address\tOrganisation\tCampus/Department\tCity\tCourse or Job title\tStart date\tEnd date\tStudent/Staff\tCountry
FNA\tLBA\[email protected]\tTEST1\tResearch Funding\tWellington\tProgramme Manager - ORCID\t2016-09 19:00:00 PM\t\tStaff\t
    """,
            filename="TEST-2.tsv",
            org=org)
        rec = task.records.first()
        assert rec.country is None
    exception.assert_called_once()
Exemple #22
0
def test_orcid_login_callback_researcher_flow(patch, patch2, request_ctx):
    """Test login from orcid callback function for researcher and display profile."""
    org = Organisation.create(name="THE ORGANISATION",
                              tuakiri_name="THE ORGANISATION",
                              confirmed=True,
                              orcid_client_id="CLIENT ID",
                              orcid_secret="Client Secret",
                              city="CITY",
                              country="COUNTRY",
                              disambiguated_id="ID",
                              disambiguation_source="SOURCE",
                              is_email_sent=True)
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="123",
                    confirmed=True,
                    organisation=org)
    UserOrg.create(user=u, org=org, is_admin=False)
    token = utils.generate_confirmation_token(email=u.email, org=org.name)
    UserInvitation.create(email=u.email,
                          token=token,
                          affiliations=Affiliation.EMP)
    OrcidToken.create(user=u,
                      org=org,
                      scope='/read-limited,/activities/update')
    with request_ctx():
        request.args = {"invitation_token": token, "state": "xyz"}
        session['oauth_state'] = "xyz"
        resp = authcontroller.orcid_login_callback(request)
        assert resp.status_code == 302
        # display profile
        assert resp.location.startswith("/profile")
Exemple #23
0
def test_link(request_ctx):
    """Test orcid profile linking."""
    org = Organisation.create(name="THE ORGANISATION",
                              tuakiri_name="THE ORGANISATION",
                              confirmed=True,
                              orcid_client_id="CLIENT ID",
                              orcid_secret="Client Secret",
                              city="CITY",
                              country="COUNTRY",
                              disambiguated_id="ID",
                              disambiguation_source="SOURCE",
                              is_email_sent=True)

    user = User.create(email="*****@*****.**",
                       name="TEST USER",
                       roles=Role.TECHNICAL,
                       orcid="123",
                       confirmed=True,
                       organisation=org)
    UserOrg.create(user=user, org=org, is_admin=True)
    with request_ctx("/link") as ctx:
        login_user(user, remember=True)
        request.args = ImmutableMultiDict([('error', 'access_denied')])
        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 200
        assert b"<!DOCTYPE html>" in rv.data, "Expected HTML content"
Exemple #24
0
def test_orcid_login(request_ctx):
    """Test login from orcid."""
    org = Organisation.create(name="THE ORGANISATION",
                              tuakiri_name="THE ORGANISATION",
                              confirmed=False,
                              orcid_client_id="CLIENT ID",
                              orcid_secret="Client Secret",
                              city="CITY",
                              country="COUNTRY",
                              disambiguated_id="ID",
                              disambiguation_source="SOURCE",
                              is_email_sent=True)
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.TECHNICAL,
                    orcid="123",
                    confirmed=True,
                    organisation=org)
    UserOrg.create(user=u, org=org, is_admin=True)
    token = utils.generate_confirmation_token(email=u.email, org=org.name)
    with request_ctx("/orcid/login/" + token.decode("utf-8")) as ctxx:
        rv = ctxx.app.full_dispatch_request()
        assert rv.status_code == 200
        orcid_authorize = OrcidAuthorizeCall.get(method="GET")
        assert "&email=test123%40test.test.net" in orcid_authorize.url
def test_load_resources_from_csv(models):
    org = Organisation.get()
    raw_data = readup_test_data("resources.tsv", "r")
    task = ResourceRecord.load_from_csv(raw_data,
                                        filename="resources.tsv",
                                        org=org)
    assert task
    assert task.records.count() == 2
Exemple #26
0
def test_create_hub_administrator(app):
    """Test creation of the Hub administrators."""
    org = app.data["org"]
    runner = CliRunner()
    runner.invoke(create_hub_administrator, ["*****@*****.**"])
    assert User.select().where(User.email == "*****@*****.**").exists()
    assert Organisation.select().where(
        Organisation.name == "ORCID Hub").exists()
    runner.invoke(create_hub_administrator,
                  ["*****@*****.**", "-O", "NEW ORGANISATION #0"])
    assert Organisation.select().where(
        Organisation.name == "NEW ORGANISATION #0").exists()
    assert User.get(
        email="*****@*****.**").organisation.name == "NEW ORGANISATION #0"

    runner.invoke(create_hub_administrator,
                  ["*****@*****.**", "-O", "NEW ORG"])
    assert Organisation.select().where(Organisation.name == "NEW ORG").exists()
    assert User.get(email="*****@*****.**").organisation.name == "NEW ORG"

    org_count = Organisation.select().count()
    runner.invoke(create_hub_administrator,
                  ["*****@*****.**", "-O", org.name])
    assert Organisation.select().count() == org_count
    assert User.get(email="*****@*****.**").organisation.name == org.name

    runner.invoke(create_hub_administrator,
                  ["*****@*****.**", "-I", "INTERNAL NAME 111"])
    assert User.select().where(User.email == "*****@*****.**").exists()
    assert Organisation.select().where(
        Organisation.name == "ORCID Hub",
        Organisation.tuakiri_name == "INTERNAL NAME 111").exists()
    assert User.get(email="*****@*****.**"
                    ).organisation.tuakiri_name == "INTERNAL NAME 111"

    runner.invoke(
        create_hub_administrator,
        ["*****@*****.**", "-O", "NEW ORG", "-I", "INTERNAL NAME 222"])
    assert Organisation.select().where(
        Organisation.name == "NEW ORG",
        Organisation.tuakiri_name == "INTERNAL NAME 222").exists()
    assert User.get(email="*****@*****.**"
                    ).organisation.tuakiri_name == "INTERNAL NAME 222"

    org_count = Organisation.select().count()
    runner.invoke(
        create_hub_administrator,
        ["*****@*****.**", "-O", org.name, "-I", "INTERNAL NAME 333"])
    assert Organisation.select().count() == org_count
    assert User.get(email="*****@*****.**"
                    ).organisation.tuakiri_name == "INTERNAL NAME 333"
Exemple #27
0
def test_select_user_org(request_ctx):
    """Test organisation switch of current user."""
    org = Organisation.create(
        name="THE ORGANISATION:test_select_user_org",
        tuakiri_name="THE ORGANISATION:test_select_user_org",
        confirmed=True,
        orcid_client_id="CLIENT ID",
        orcid_secret="Client Secret",
        city="CITY",
        country="COUNTRY",
        disambiguated_id="ID",
        disambiguation_source="RINGGOLD",
        is_email_sent=True)
    org2 = Organisation.create(
        name="THE ORGANISATION2:test_select_user_org",
        tuakiri_name="THE ORGANISATION2:test_select_user_org",
        confirmed=True,
        orcid_client_id="CLIENT ID",
        orcid_secret="Client Secret",
        city="CITY",
        country="COUNTRY",
        disambiguated_id="ID",
        disambiguation_source="RINGGOLD",
        is_email_sent=True)

    user = User.create(
        email="*****@*****.**",
        name="TEST USER",
        roles=Role.TECHNICAL,
        orcid="123",
        confirmed=True,
        organisation=org)
    org.save()
    org2.save()
    user.save()
    UserOrg.create(user=user, org=org, is_admin=True)
    user_org2 = UserOrg.create(user=user, org=org2, is_admin=True)
    with request_ctx(f"/select/user_org/{user_org2.id}") as ctx:
        login_user(user, remember=True)
        resp = ctx.app.full_dispatch_request()
        assert resp.status_code == 302
        assert user.organisation_id != org.id
        # Current users organisation has been changes from 1 to 2
        assert user.organisation_id == org2.id
Exemple #28
0
def test_profile(request_ctx):
    """Test an affilated user profile and ORCID data retrieval."""
    with request_ctx("/profile") as ctx:
        org = Organisation(name="THE ORGANISATION", confirmed=True)
        org.save()
        test_user = User(
            email="*****@*****.**", organisation=org, orcid="ABC123", confirmed=True)
        test_user.save()
        orcidtoken = OrcidToken(
            user=test_user,
            org=org,
            scope="/read-limited,/activities/update",
            access_token="ABC1234")
        orcidtoken.save()
        login_user(test_user, remember=True)

        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 200
        assert b"ABC123" in rv.data
Exemple #29
0
def test_researcher_urls(models):
    org = Organisation.select().first()
    raw_data0 = open(os.path.join(os.path.dirname(__file__), "data", "researchurls.json"), "r").read()
    data0 = load_yaml_json("researchurls.json", raw_data0)
    assert isinstance(data0, list) and isinstance(data0[0], NestedDict)
    task0 = ResearcherUrlRecord.load_from_json(filename="researchurls000.json", source=raw_data0, org=org)
    data = task0.to_dict()
    raw_data = json.dumps(data, cls=JSONEncoder)
    task = ResearcherUrlRecord.load_from_json(filename="researchurls001.json", source=raw_data, org=org)
    assert len(data0) == len(task.to_dict()["records"])
def test_link(request_ctx):
    """Test a user affiliation initialization."""
    with request_ctx("/link") as ctx:
        org = Organisation.get(name="THE ORGANISATION")
        test_user = User.create(
            name="TEST USER 123", email="*****@*****.**", organisation=org, confirmed=True)
        login_user(test_user, remember=True)

        rv = ctx.app.full_dispatch_request()
        assert b"<!DOCTYPE html>" in rv.data, "Expected HTML content"
        assert b"TEST USER 123" in rv.data, "Expected to have the user name on the page"
        assert b"*****@*****.**" in rv.data, "Expected to have the user email on the page"
        assert b"URL_123" in rv.data, "Expected to have ORCiD authorization link on the page"