Example #1
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") as ctx:
        org = Organisation(name="THE ORGANISATION", confirmed=True)
        org.save()
        test_user = User(
            name=name,
            email="*****@*****.**",
            username="******",
            organisation=org,
            orcid="ABC123",
            confirmed=True)
        login_user(test_user, remember=True)

        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(username="******")
        assert u.orcid == "ABC-123-456-789"
        assert u.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"
Example #2
0
def test_reset_db(request_ctx):
    """Test reset_db function for 'testing' cycle reset."""
    with request_ctx("/reset_db") as ctx:
        org = Organisation(name="THE ORGANISATION")
        org.save()
        u = User(email="*****@*****.**",
                 name="TEST USER",
                 username="******",
                 roles=Role.SUPERUSER,
                 orcid=None,
                 confirmed=True)
        u.save()
        root = User(email="*****@*****.**",
                    name="The root",
                    username="******",
                    roles=Role.SUPERUSER,
                    orcid=None,
                    confirmed=True)
        root.save()
        assert User.select().count() == 2
        assert Organisation.select().count() == 1
        login_user(u, remember=True)
        rv = ctx.app.full_dispatch_request()
        assert User.select().count() == 1
        assert Organisation.select().count() == 0
        assert rv.status_code == 302
        assert rv.location == url_for("logout")
Example #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(name="THE ORGANISATION")
    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"
                    },
                    follow_redirects=True)

    u = User.get(email="*****@*****.**")
    assert u.organisation == org
    assert org in u.organisations
    assert u.edu_person_shared_token == "ABC111"
    assert b"Your organisation (INCOGNITO) is not onboarded" not in rv.data
    uo = UserOrg.get(user=u, org=org)
    assert not uo.is_admin
Example #4
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="*****@*****.**",
            username="******",
            organisation=org,
            orcid=None,
            confirmed=True)
        login_user(test_user, remember=True)

        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 302
        assert rv.location == url_for("link")
Example #5
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="*****@*****.**",
            username="******",
            organisation=org,
            orcid="ABC123",
            confirmed=True)
        login_user(test_user, remember=True)

        rv = ctx.app.full_dispatch_request()
        assert rv.status_code == 200
        assert b"TEST1234567890" in rv.data
Example #6
0
 def iati_organisations__iati_organisation(self, element):
     organisation = Organisation()
     organisation.organisation_identifier = element.xpath('iati-identifier/text()')[0]
     self.organisation_identifier = organisation.organisation_identifier
     organisation.code = self.organisation_identifier
     organisation.last_updated_datetime = self.validate_date(element.attrib.get('last-updated-datetime'))
     if '{http://www.w3.org/XML/1998/namespace}lang' in element.attrib:
         organisation.default_lang =  self.get_or_none(codelist_models.Language,code=element.attrib['{http://www.w3.org/XML/1998/namespace}lang'])
     organisation.iati_version_id = self.VERSION
     organisation.default_currency = self.get_or_none(codelist_models.Currency,code=element.attrib.get('default-currency'))
     organisation.save()
     # add to reporting organisation and recipient_organisation
     RecipientOrgBudget.objects.filter(recipient_org_identifier=self.organisation_identifier).update(recipient_org=organisation)
     ReportingOrg.objects.filter(reporting_org_identifier=self.organisation_identifier).update(reporting_org=organisation)
     self.register_model('Organisation', organisation)
     # store element
     return element
Example #7
0
def test_link(request_ctx):
    """Test a user affiliation initialization."""
    with request_ctx("/link") as ctx:
        org = Organisation(name="THE ORGANISATION", confirmed=True)
        org.save()
        test_user = User(
            name="TEST USER 123",
            email="*****@*****.**",
            username="******",
            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"
Example #8
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)
        org.save()
        test_user = User(
            email="*****@*****.**",
            name="TEST USER",
            username="******",
            organisation=org,
            orcid="ABC123",
            confirmed=True)
        test_user.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"
Example #9
0
def invite_organisation():
    """Invite an organisation to register.

    Flow:
        * Hub administrort (super user) invokes the page,
        * Fills in the form with the organisation and organisation technica contatct data (including an email address);
        * Submits the form;
        * A secure registration token gets ceated;
        * An email message with confirmation link gets created and sent off to the technical contact.
    """
    form = OrgRegistrationForm()
    if request.method == "POST":
        if not form.validate():
            flash("Please fill in all fields and try again.", "danger")
        else:
            email = form.orgEmailid.data
            org_name = form.orgName.data
            try:
                User.get(User.email == form.orgEmailid.data)
                flash(
                    "This Email address is already an Admin for one of the organisation",
                    "warning")
            except User.DoesNotExist:
                pass
            finally:
                # TODO: organisation can have mutiple admins:
                # TODO: user OrgAdmin
                try:
                    org = Organisation.get(name=org_name)
                    # TODO: fix it!
                    org.email = email
                except Organisation.DoesNotExist:
                    org = Organisation(name=org_name, email=email)
                org.save()

                try:
                    user = User.get(email=email)
                    user.roles |= Role.ADMIN
                    user.organisation = org
                except User.DoesNotExist:
                    user = User(
                        name=form.orgName.data,
                        email=form.orgEmailid.data,
                        confirmed=True,  # In order to let the user in...
                        roles=Role.ADMIN,
                        organisation=org)
                user.save()
                # Note: Using app context due to issue: https://github.com/mattupstate/flask-mail/issues/63
                with app.app_context():
                    msg = Message("Welcome to OrcidhHub",
                                  recipients=[str(form.orgEmailid.data)])
                    token = generate_confirmation_token(form.orgEmailid.data)
                    # TODO: do it with templates
                    msg.body = "Your organisation is just one step behind to get onboarded" \
                               " please click on following link to get onboarded " \
                               "https://" + environ.get("ENV", "dev") + ".orcidhub.org.nz" + \
                               url_for("confirm_organisation", token=token)
                    mail.send(msg)
                    flash(
                        "Organisation Onboarded Successfully!!! Email Communication has been sent to Admin",
                        "success")

    return render_template('registration.html', form=form)
Example #10
0
import models
from models import Organisation, User, Role

models.drop_talbes()
models.create_tables()

org0 = Organisation(name="The Royal Society of NewZealand",
                    email="*****@*****.**",
                    tuakiri_name="The Royal Society of NewZealand",
                    orcid_client_id="client-123",
                    orcid_secret="secret-123",
                    confirmed=True)
org0.save()

super_user = User(name="The Royal Society of NewZealand",
                  email="*****@*****.**",
                  edu_person_shared_token="aaRtDix1l2z43M0vvWTBpBuf_ek",
                  confirmed=True,
                  roles=Role.SUPERUSER)
super_user.save()

super_user = User(name="The Root",
                  email="*****@*****.**",
                  confirmed=True,
                  roles=Role.SUPERUSER)
super_user.save()
def makeOrganisation(name, list_id, enquete_id, color):
    # Keep a list of added users for the deletion upon error
    userlist = []

    # Create a batch operation
    batch = {"operations":[]}

    config = MailChimpConfig()
    # Create a organisation
    new_organisation = Organisation(name=name, color=color)
    new_organisation.save()

    # Retrieve the enquete
    enquete = Enquete.objects.get(id=enquete_id)
    
    # Create a invulmoment
    new_invulmoment = Invulmoment(organisation=new_organisation, enquete=enquete, time=date.today())
    new_invulmoment.save()

    # Get the list members
    list_endpoint_string = 'lists/' + list_id + '/members'
    list_endpoint = urlparse.urljoin(config.api_root, list_endpoint_string)
    params = {
    # Pagination in API v3.0 is always done with count and offset
    'count': 1000, 'offset': 0
    }   
    list_response = requests.get(list_endpoint, auth=('apikey', config.apikey), params=params, verify=False)
    
    # Add a new Merge tag to the list
    mergetags_endpoint_string = 'lists/' + list_id +'/merge-fields'
    mergetags_endpoint = urlparse.urljoin(config.api_root, mergetags_endpoint_string)
    mergetags_post_data = {"tag":"PWD", "name":"Password", "required":False, "public":False, "type":"text"}
    mergetags_response = requests.post(mergetags_endpoint, auth=('apikey', config.apikey), verify=False, data=json.dumps(mergetags_post_data))
    if mergetags_response.reason != "OK":
        new_organisation.delete()
        new_invulmoment.delete()
        return "Response error!: " + mergetags_response.reason + " , bestaat de Password Mergetag al in Mailchimp?"

    for member in list_response.json()['members']:
        userCheck = User.objects.filter(username=member['email_address'].lower())
        
        if not userCheck.count() == 0:
            new_invulmoment.delete()
            new_organisation.delete()
            if len(userlist) > 0:
                for user in userlist:
                    user.delete()
            return "Gebruiker bestaat al: " + member['email_address'].lower() + " (Geen organisatie aangemaakt!)"
        # For every user add them to the db and patch them to mailchimp (provide pwd merge tag)
        newUser = User(username=member['email_address'].lower(), email=member['email_address'])
        password = User.objects.make_random_password()
        newUser.set_password(password)
        newUser.save()
        userlist.append(newUser)

        # Patch the user (add it to batch operation)
        path_string = "/lists/" + list_id + "/members/" + member['id']
        operation_data = {"merge_fields":{"PWD":password}}
        operation = {"method":"PATCH", "path":path_string, "body":json.dumps(operation_data)}
        batch["operations"].append(operation)

        # Add the user to the organisation
        new_organisation.members.add(newUser)

        # Create a profiel object for this user
        # newProfiel = Profiel(user=newUser, invulmoment=new_invulmoment)
        # newProfiel.save()


    batch_endpoint = urlparse.urljoin(config.api_root, "batches")
    batch_response = requests.post(batch_endpoint, auth=('apikey', config.apikey), verify=False, data=json.dumps(batch))
    print batch_response.text
    if batch_response.reason != "OK":
        new_invulmoment.delete()
        new_organisation.delete()
        if len(userlist) > 0:
            for user in userlist:
                user.delete()
        return "Response Error!: " + batch_response.reason
    return True