Exemplo n.º 1
0
Arquivo: mfa.py Projeto: SURFscz/SBS
def _do_verify_2fa(user: User, secret):
    data = current_request.get_json()
    totp_value = data["totp"]
    totp = pyotp.TOTP(secret)
    if totp.verify(totp_value, valid_window=1):
        if not user.second_factor_auth:
            user.second_factor_auth = secret
        user.last_login_date = datetime.datetime.now()
        user = db.session.merge(user)
        db.session.commit()
        store_user_in_session(user, True, user.has_agreed_with_aup())
        return True
    else:
        return False
Exemplo n.º 2
0
 def test_generate_unique_username(self):
     # we don't want this in the normal seed
     for username in ["jdoe", "jdoe2", "cdoemanchi", "cdoemanchi2", "cdoemanchi3", "u", "u2"]:
         db.session.merge(User(uid=str(uuid.uuid4()), username=username, created_by="test", updated_by="test",
                               name="name"))
     db.session.merge(UserNameHistory(username="******"))
     db.session.commit()
     names = [("John2", "Doe,"), ("Cinderella!", "Doemanchinice"), (None, "髙橋 大"), ("påré", "ÄÄ")]
     short_names = [generate_unique_username(munchify({"given_name": n[0], "family_name": n[1]})) for n in names]
     self.assertListEqual(["jdoe4", "cdoemanchi4", "u3", "paa"], short_names)
Exemplo n.º 3
0
def login_user():
    if not os.environ.get("ALLOW_MOCK_USER_API", None):
        raise Forbidden()

    data = current_request.get_json()
    sub = data["sub"]  # oidc sub maps to sbs uid - see user_claims
    user = User.query.filter(User.uid == sub).first() or User(created_by="system", updated_by="system")

    add_user_claims(data, sub, user, replace_none_values=False)
    db.session.merge(user)

    res = {"admin": is_admin_user(user), "guest": False, "confirmed_admin": user.confirmed_super_user}
    session_data = {
        "id": user.id,
        "uid": user.uid,
        "name": user.name,
        "email": user.email,
        "user_accepted_aup": user.has_agreed_with_aup(),
        "second_factor_confirmed": True
    }
    session["user"] = {**session_data, **res}
    return None, 201
Exemplo n.º 4
0
def resume_session():
    logger = ctx_logger("oidc")

    cfg = current_app.app_config
    oidc_config = cfg.oidc
    code = query_param("code", required=False, default=None)
    if not code:
        # This means that we are not in the redirect callback, but at the redirect from eduTeams
        logger.debug("Redirect to login in resume-session to start OIDC flow")
        authorization_endpoint = _get_authorization_url()
        return redirect(authorization_endpoint)

    scopes = " ".join(oidc_config.scopes)
    payload = {
        "code": code,
        "grant_type": "authorization_code",
        "scope": scopes,
        "redirect_uri": oidc_config.redirect_uri
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cache-Control": "no-cache",
        "Accept": "application/json, application/json;charset=UTF-8"
    }
    response = requests.post(oidc_config.token_endpoint, data=urllib.parse.urlencode(payload),
                             headers=headers, auth=(oidc_config.client_id, oidc_config.client_secret))
    if response.status_code != 200:
        return _redirect_with_error(logger, f"Server error: Token endpoint error (http {response.status_code}")

    token_json = response.json()
    access_token = token_json["access_token"]

    headers = {
        "Accept": "application/json, application/json;charset=UTF-8",
        "Authorization": f"Bearer {access_token}"
    }

    response = requests.get(oidc_config.userinfo_endpoint, headers=headers)
    if response.status_code != 200:
        return _redirect_with_error(logger, f"Server error: User info endpoint error (http {response.status_code}")

    logger = ctx_logger("user")
    user_info_json = response.json()

    logger.debug(f"Userinfo endpoint results {user_info_json}")

    uid = user_info_json["sub"]
    user = User.query.filter(User.uid == uid).first()
    if not user:
        user = User(uid=uid, created_by="system", updated_by="system")
        add_user_claims(user_info_json, uid, user)

        # last_login_date is set later in this method
        user.last_accessed_date = datetime.datetime.now()
        logger.info(f"Provisioning new user {user.uid}")
    else:
        logger.info(f"Updating user {user.uid} with new claims / updated at")
        add_user_claims(user_info_json, uid, user)

    encoded_id_token = token_json["id_token"]
    id_token = decode_jwt_token(encoded_id_token)

    no_mfa_required = not oidc_config.second_factor_authentication_required
    idp_mfa = id_token.get("acr") == ACR_VALUES

    idp_allowed = mfa_idp_allowed(user, user.schac_home_organisation, None)

    second_factor_confirmed = no_mfa_required or idp_mfa or idp_allowed
    if second_factor_confirmed:
        user.last_login_date = datetime.datetime.now()

    user = db.session.merge(user)
    db.session.commit()

    user_accepted_aup = user.has_agreed_with_aup()
    store_user_in_session(user, second_factor_confirmed, user_accepted_aup)

    if not user_accepted_aup:
        location = f"{cfg.base_url}/aup"
    elif not second_factor_confirmed:
        location = f"{cfg.base_url}/2fa"
    else:
        location = session.get("original_destination", cfg.base_url)

    return redirect(location)
Exemplo n.º 5
0
 def test_bugfix_empty_user_claims_affiliation_list(self):
     user = User()
     add_user_claims({"voperson_external_id": []}, "urn:johny", user)
     self.assertIsNone(user.schac_home_organisation)
Exemplo n.º 6
0
 def test_eppn_generate_unique_username(self):
     user = User(eduperson_principal_name="sarah-lee")
     username = generate_unique_username(user)
     # We don't use the eduperson_principal_name anymore
     self.assertEqual("u", username)
Exemplo n.º 7
0
 def test_add_user_claims_user_name(self):
     user = User()
     add_user_claims({"given_name": "John", "family_name": "Doe"}, "urn:johny", user)
     self.assertEqual("jdoe", user.username)
Exemplo n.º 8
0
 def test_user_claims_schac_home_org(self):
     user = User()
     user_info_json_str = self.read_file("user_info.json")
     user_info_json = json.loads(user_info_json_str)
     add_user_claims(user_info_json, "urn:new_user", user)
     self.assertEqual("rug", user.schac_home_organisation)
Exemplo n.º 9
0
 def test_add_user_claims_empty_entitlements(self):
     user = User()
     add_user_claims({"eduperson_entitlement": []}, "urn:johny", user)
     self.assertIsNone(user.entitlement)
Exemplo n.º 10
0
 def test_add_user_claims_affiliation_defensive(self):
     user = User()
     add_user_claims({"voperson_external_id": "university"}, "urn:johny", user)
     self.assertIsNone(user.schac_home_organisation)
Exemplo n.º 11
0
 def test_add_user_claims_no_voperson_external_id(self):
     user = User()
     add_user_claims({}, "urn:johny", user)
     self.assertIsNone(user.schac_home_organisation)
Exemplo n.º 12
0
 def test_add_user_claims_affiliation_list(self):
     user = User()
     add_user_claims({"voperson_external_id": ["*****@*****.**"]}, "urn:johny", user)
     self.assertEqual("sub.uni.org", user.schac_home_organisation)
Exemplo n.º 13
0
 def test_add_user_claims_affiliation(self):
     user = User()
     add_user_claims({"voperson_external_id": "teacher@university"}, "urn:johny", user)
     self.assertEqual("university", user.schac_home_organisation)
Exemplo n.º 14
0
 def test_add_user_claims(self):
     user = User()
     add_user_claims({}, "urn:johny", user)
     self.assertEqual("urn:johny", user.name)
Exemplo n.º 15
0
def seed(db, app_config, skip_seed=False, perf_test=False):
    tables = reversed(metadata.sorted_tables)
    for table in tables:
        db.session.execute(table.delete())

    db.session.execute(text("DELETE FROM audit_logs"))

    db.session.commit()

    if skip_seed:
        return

    john = User(uid="urn:john", name=john_name, email="*****@*****.**", username="******",
                address="Postal 1234AA", confirmed_super_user=True)
    unconfirmed_super_user_mike = User(uid="urn:mike", name=mike_name, email="*****@*****.**", username="******",
                                       confirmed_super_user=False, application_uid="mike_application_uid",
                                       schac_home_organisation="surfnet.nl")
    peter = User(uid="urn:peter", name="Peter Doe", email="*****@*****.**", username="******")
    mary = User(uid="urn:mary", name="Mary Doe", email="*****@*****.**", username="******",
                schac_home_organisation=schac_home_organisation)
    admin = User(uid="urn:admin", name=the_boss_name, email="*****@*****.**", username="******")
    roger = User(uid="urn:roger", name=roger_name, email="*****@*****.**",
                 schac_home_organisation=schac_home_organisation, username="******")
    harry = User(uid="urn:harry", name="Harry Doe", email="*****@*****.**", username="******")
    james = User(uid="urn:james", name=james_name, email="*****@*****.**", username="******",
                 schac_home_organisation=schac_home_organisation_uuc, given_name="James")
    sarah = User(uid="urn:sarah", name=sarah_name, email="*****@*****.**", application_uid="sarah_application_uid",
                 username="******")
    betty = User(uid="urn:betty", name="betty", email="*****@*****.**", username="******")
    jane = User(uid="urn:jane", name=jane_name, email="*****@*****.**", username="******",
                entitlement="urn:mace:surf.nl:sram:allow-create-co")
    paul = User(uid="urn:paul", name="Paul Doe", email="*****@*****.**", username="******",
                schac_home_organisation="example.com")
    service_admin = User(uid="urn:service_admin", name="Service Admin", email="*****@*****.**",
                         username="******", schac_home_organisation="service_admin.com")
    # User seed for suspend testing
    retention = app_config.retention
    current_time = datetime.datetime.utcnow()
    retention_date = current_time - datetime.timedelta(days=retention.allowed_inactive_period_days + 1)

    user_inactive = User(uid="urn:inactive", name="inactive", email="*****@*****.**", username="******",
                         last_login_date=retention_date, last_accessed_date=retention_date,
                         schac_home_organisation="not.exists")
    user_one_suspend = User(uid="urn:one_suspend", name="one_suspend", email="*****@*****.**",
                            username="******",
                            last_login_date=retention_date, last_accessed_date=retention_date)

    user_two_suspend = User(uid="urn:two_suspend", name="two_suspend", email="*****@*****.**",
                            username="******",
                            last_login_date=retention_date, last_accessed_date=retention_date)

    last_login_date = current_time - datetime.timedelta(days=retention.allowed_inactive_period_days + 30)
    user_suspended = User(uid="urn:suspended", name="suspended", email="*****@*****.**", username="******",
                          last_login_date=last_login_date, last_accessed_date=last_login_date,
                          suspended=True)

    deletion_date = current_time - datetime.timedelta(days=retention.remove_suspended_users_period_days + 30)
    user_to_be_deleted = User(uid="urn:to_be_deleted", name="to_be_deleted", email="*****@*****.**",
                              last_login_date=deletion_date, last_accessed_date=deletion_date, username="******",
                              suspended=True)

    _persist(db, john, unconfirmed_super_user_mike, mary, peter, admin, roger, harry, james, sarah, betty, jane,
             user_inactive, user_one_suspend, user_two_suspend, user_suspended, user_to_be_deleted, paul,
             service_admin)

    ssh_key_john = SshKey(user=john, ssh_value="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/nvjea1zJJNCnyUfT6HLcHD"
                                               "hwCMp7uqr4BzxhDAjBnjWcgW4hZJvtLTqCLspS6mogCq2d0/31DU4DnGb2MO28"
                                               "gk74MiVBtAQWI5+TsO5QHupO3V6aLrKhmn8xn1PKc9JycgjOa4BMQ1meomn3Z"
                                               "mph6oo87MCtF2w75cxYEBJ9dJgHzZsn9mw+w8Z3H1vYnkcBT/i2MIK+qfsue/t"
                                               "vEe8ybi+26bGQIZIPDcd+OmDUBxDLWyBwCbVOyRL5M6ywnWJINLdpIwfqCUk24"
                                               "J1q1qiJ5eZu0m0uDcG5KRzgZ+grnSSYBwCx1xCunoGjMg7iwxEMgScD02nKtii"
                                               "jxEpu8soL [email protected]")
    ssh_key_james = SshKey(user=james, ssh_value="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/nvjea1zJJNCnyUfT6HLcHD"
                                                 "hwCMp7uqr4BzxhDAjBnjWcgW4hZJvtLTqCLspS6mogCq2d0/31DU4DnGb2MO28"
                                                 "gk74MiVBtAQWI5+TsO5QHupO3V6aLrKhmn8xn1PKc9JycgjOa4BMQ1meomn3Z"
                                                 "mph6oo87MCtF2w75cxYEBJ9dJgHzZsn9mw+w8Z3H1vYnkcBT/i2MIK+qfsue/t"
                                                 "vEe8ybi+26bGQIZIPDcd+OmDUBxDLWyBwCbVOyRL5M6ywnWJINLdpIwfqCUk24"
                                                 "J1q1qiJ5eZu0m0uDcG5KRzgZ+grnSSYBwCx1xCunoGjMg7iwxEMgScD02nKtii"
                                                 "jxEpu8soL [email protected]")
    ssh_key_sarah = SshKey(user=sarah, ssh_value="some-lame-key")
    _persist(db, ssh_key_john, ssh_key_james, ssh_key_sarah)

    sarah_user_ip_network = UserIpNetwork(network_value="255.0.0.1/32", user=sarah)
    sarah_other_user_ip_network = UserIpNetwork(network_value="255.0.0.9/24", user=sarah)
    _persist(db, sarah_user_ip_network, sarah_other_user_ip_network)

    resend_suspension_date = current_time - datetime.timedelta(retention.reminder_resent_period_days + 1)
    user_one_suspend_notification1 = SuspendNotification(user=user_one_suspend, sent_at=resend_suspension_date,
                                                         is_primary=True)

    resend_suspension_date = current_time - datetime.timedelta(retention.reminder_resent_period_days + 1)
    user_two_suspend_notification1 = SuspendNotification(user=user_two_suspend, sent_at=resend_suspension_date,
                                                         is_primary=True)
    resend_suspension_date = current_time - datetime.timedelta(retention.reminder_expiry_period_days + 1)
    user_two_suspend_notification2 = SuspendNotification(user=user_two_suspend, sent_at=resend_suspension_date,
                                                         is_primary=False)
    user_suspended_notification1 = SuspendNotification(user=user_suspended, sent_at=resend_suspension_date,
                                                       is_primary=True)
    user_suspended_notification2 = SuspendNotification(user=user_suspended, sent_at=resend_suspension_date,
                                                       is_primary=False)

    _persist(db, user_one_suspend_notification1, user_two_suspend_notification1, user_two_suspend_notification2,
             user_suspended_notification1, user_suspended_notification2)

    uuc = Organisation(name=uuc_name, short_name="uuc", identifier=str(uuid.uuid4()),
                       description="Unincorporated Urban Community", logo=read_image("uuc.jpeg"),
                       created_by="urn:admin", updated_by="urnadmin", category="Research",
                       on_boarding_msg="We are using **SRAM** to provide access to the following research tools:"
                                       "\n- Wiki\n- Cloud\n- Awesome things...\n\nIf you want to join one of our "
                                       "collaborations, please send a mail to [[email protected]](mailto:[email protected])."
                                       "\n<br/><br/>\nHappy researching,\n\n*UUC support*",
                       collaboration_creation_allowed=True)
    uva = Organisation(name=amsterdam_uva_name, description="University of Amsterdam", identifier=str(uuid.uuid4()),
                       created_by="urn:admin", updated_by="urn:admin", short_name="uva", logo=read_image("uva.jpg"),
                       category="University")
    tue = Organisation(name="TUE", description="University of Eindhoven", identifier=str(uuid.uuid4()),
                       created_by="urn:admin", updated_by="urn:admin", short_name="tue", logo=read_image("tue.jpeg"),
                       category="University")
    _persist(db, uuc, uva, tue)

    shouuc = SchacHomeOrganisation(name=schac_home_organisation_uuc, organisation=uuc, created_by="urn:admin",
                                   updated_by="urn:admin")
    shouva = SchacHomeOrganisation(name=schac_home_organisation, organisation=uva, created_by="urn:admin",
                                   updated_by="urn:admin")
    _persist(db, shouuc, shouva)

    api_key = ApiKey(hashed_secret=uuc_hashed_secret, organisation=uuc, description="API access",
                     created_by="urn:admin", updated_by="urn:admin")
    _persist(db, api_key)
    organisation_invitation_roger = OrganisationInvitation(message="Please join", hash=organisation_invitation_hash,
                                                           expiry_date=datetime.date.today() + datetime.timedelta(
                                                               days=14),
                                                           invitee_email="*****@*****.**", organisation=uuc,
                                                           intended_role="admin",
                                                           user=john)
    organisation_invitation_pass = OrganisationInvitation(message="Let me please join as I "
                                                                  "really, really, really \n really, "
                                                                  "really, really \n want to...",
                                                          hash=organisation_invitation_expired_hash,
                                                          expiry_date=datetime.date.today() - datetime.timedelta(
                                                              days=21),
                                                          intended_role="admin",
                                                          invitee_email="*****@*****.**", organisation=uuc, user=john)
    _persist(db, organisation_invitation_roger, organisation_invitation_pass)

    organisation_membership_john = OrganisationMembership(role="admin", user=john, organisation=uuc)
    organisation_membership_mary = OrganisationMembership(role="admin", user=mary, organisation=uuc)
    organisation_membership_harry = OrganisationMembership(role="manager", user=harry, organisation=uuc)
    organisation_membership_jane = OrganisationMembership(role="admin", user=jane, organisation=uva)
    organisation_membership_paul_uuc = OrganisationMembership(role="manager", user=paul, organisation=uuc)
    organisation_membership_paul_uva = OrganisationMembership(role="manager", user=paul, organisation=uva)
    _persist(db, organisation_membership_john, organisation_membership_mary, organisation_membership_harry,
             organisation_membership_jane, organisation_membership_paul_uuc, organisation_membership_paul_uva)

    mail = Service(entity_id=service_mail_entity_id, name=service_mail_name, contact_email=john.email,
                   public_visible=True, automatic_connection_allowed=True, logo=read_image("email.jpeg"),
                   accepted_user_policy="https://google.nl", allowed_organisations=[uuc, uva], abbreviation="mail",
                   privacy_policy="https://privacy.org")
    wireless = Service(entity_id="https://wireless", name=service_wireless_name, description="Network Wireless Service",
                       public_visible=True, automatic_connection_allowed=True, contact_email=john.email,
                       logo=read_image("wireless.png"), accepted_user_policy="https://google.nl", abbreviation="wire",
                       allowed_organisations=[uuc, uva], uri="https://wireless", non_member_users_access_allowed=True,
                       privacy_policy="https://privacy.org")
    cloud = Service(entity_id=service_cloud_entity_id, name=service_cloud_name, description="SARA Cloud Service",
                    public_visible=True, automatic_connection_allowed=True, logo=read_image("cloud.jpg"),
                    allowed_organisations=[uuc, uva], abbreviation="cloud", privacy_policy="https://privacy.org",
                    token_enabled=True, hashed_token=secure_hash(service_cloud_token), token_validity_days=1)
    storage = Service(entity_id=service_storage_entity_id, name=service_storage_name, allowed_organisations=[uuc, uva],
                      description="SURF Storage Service", logo=read_image("storage.jpeg"), abbreviation="storage",
                      public_visible=True, automatic_connection_allowed=True, white_listed=True,
                      accepted_user_policy="https://google.nl", privacy_policy="https://privacy.org")
    wiki = Service(entity_id=service_wiki_entity_id, name=service_wiki_name, description="No more wiki's please",
                   uri="https://wiki.surfnet.nl/display/SCZ/Collaboration+Management+System+%28Dutch%3A+"
                       "SamenwerkingBeheerSysteem%29+-+SBS#CollaborationManagementSystem"
                       "(Dutch:SamenwerkingBeheerSysteem)-SBS-DevelopmentofnewopensourceCollaborationManagementSystem",
                   public_visible=True, automatic_connection_allowed=False, logo=read_image("wiki.jpeg"),
                   allowed_organisations=[uuc, uva], contact_email="*****@*****.**", abbreviation="wiki",
                   accepted_user_policy="https://google.nl", privacy_policy="https://privacy.org",
                   ldap_password="******"
                                 "IddqWdPB.AEH2MBb1sggk8pDlrW/Xb00f8xa67cC0nfkuX.",
                   token_enabled=True, hashed_token=secure_hash(wiki_cloud_token), token_validity_days=365)
    network = Service(entity_id=service_network_entity_id, name=service_network_name,
                      description="Network enabling service SSH access", address="Some address",
                      uri="https://uri", identity_type="SSH KEY", accepted_user_policy="https://aup",
                      contact_email="*****@*****.**", logo=read_image("network.jpeg"),
                      public_visible=False, automatic_connection_allowed=True, abbreviation="network",
                      allowed_organisations=[uuc], privacy_policy="https://privacy.org",
                      token_enabled=True, hashed_token=secure_hash(network_cloud_token), token_validity_days=365)
    service_ssh_uva = Service(entity_id="service_ssh_uva", name=service_ssh_uva_name,
                              description="Uva SSH access",
                              uri="https://uri/ssh", identity_type="SSH KEY", accepted_user_policy="https://ssh",
                              contact_email="*****@*****.**", logo=read_image("ssh_uva.png"),
                              public_visible=False, automatic_connection_allowed=False, abbreviation="service_ssh",
                              allowed_organisations=[uva], research_scholarship_compliant=True,
                              code_of_conduct_compliant=True, sirtfi_compliant=True,
                              privacy_policy="https://privacy.org")

    uuc_scheduler = Service(entity_id=uuc_scheduler_entity_id, name=uuc_scheduler_name,
                            accepted_user_policy="https://google.nl", abbreviation="uuc_scheduler",
                            description="UUC Scheduler Service", logo=read_image("scheduler_uuc.jpeg"),
                            public_visible=True, automatic_connection_allowed=False, allowed_organisations=[uuc],
                            privacy_policy="https://privacy.org")

    _persist(db, mail, wireless, cloud, storage, wiki, network, service_ssh_uva, uuc_scheduler)

    service_invitation_cloud = ServiceInvitation(message="Please join", hash=service_invitation_hash,
                                                 expiry_date=datetime.date.today() + datetime.timedelta(days=14),
                                                 invitee_email="*****@*****.**", service=cloud,
                                                 intended_role="admin",
                                                 user=john)
    service_invitation_wiki_expired = ServiceInvitation(message="Please join",
                                                        hash=service_invitation_expired_hash,
                                                        expiry_date=datetime.date.today() - datetime.timedelta(
                                                            days=21),
                                                        intended_role="admin",
                                                        invitee_email="*****@*****.**", service=wiki, user=john)
    _persist(db, service_invitation_cloud, service_invitation_wiki_expired)

    service_membership_james = ServiceMembership(role="admin", user=james, service=cloud)
    service_membership_service_admin_1 = ServiceMembership(role="admin", user=service_admin, service=storage)
    service_membership_service_admin_2 = ServiceMembership(role="admin", user=service_admin, service=network)
    _persist(db, service_membership_james, service_membership_service_admin_1, service_membership_service_admin_2)

    service_group_mail = ServiceGroup(name=service_group_mail_name,
                                      short_name="mail",
                                      auto_provision_members=True,
                                      description="Mail group",
                                      service=mail)
    service_group_wiki = ServiceGroup(name=service_group_wiki_name,
                                      short_name="wiki",
                                      auto_provision_members=False,
                                      description="Wiki group",
                                      service=wiki)
    _persist(db, service_group_mail, service_group_wiki)

    uuc.services.append(uuc_scheduler)
    uuc.services.append(wiki)

    ai_computing = Collaboration(name=ai_computing_name,
                                 identifier=collaboration_ai_computing_uuid,
                                 global_urn=f"ucc:{ai_computing_short_name}",
                                 description="Artifical Intelligence computing for the Unincorporated Urban Community",
                                 logo=read_image("computing.jpeg"),
                                 organisation=uuc, services=[mail, network],
                                 join_requests=[], invitations=[],
                                 short_name=ai_computing_short_name,
                                 website_url="https://www.google.nl",
                                 accepted_user_policy="https://www.google.nl",
                                 disclose_email_information=True,
                                 disclose_member_information=True)
    uva_research = Collaboration(name=uva_research_name,
                                 short_name="research",
                                 global_urn="uva:research",
                                 identifier=collaboration_uva_researcher_uuid,
                                 website_url="https://www.google.nl",
                                 description="University of Amsterdam Research - Urban Crowd Control",
                                 logo=read_image("research.jpeg"),
                                 organisation=uva, services=[cloud, storage, wiki],
                                 join_requests=[], invitations=[],
                                 disclose_member_information=True)
    uuc_teachers = Collaboration(name=uuc_teachers_name,
                                 identifier=str(uuid.uuid4()),
                                 global_urn=f"ucc:{uuc_teachers_name}",
                                 website_url="https://www.google.nl",
                                 description="UUC Teachers",
                                 logo=read_image("teachers.jpeg"),
                                 organisation=uuc, services=[],
                                 join_requests=[], invitations=[],
                                 short_name="uuc_teachers_short_name",
                                 accepted_user_policy="https://www.uuc.nl/teachers")

    uu_disabled_join_request = Collaboration(name=uu_disabled_join_request_name,
                                             short_name="uu_short",
                                             global_urn="uva:uu_short",
                                             website_url="https://www.google.nl",
                                             logo=read_image("uu.png"),
                                             identifier=str(uuid.uuid4()),
                                             description="UU", disable_join_requests=True, organisation=uva,
                                             services=[],
                                             join_requests=[], invitations=[])
    _persist(db, ai_computing, uva_research, uu_disabled_join_request, uuc_teachers)

    john_ai_computing = CollaborationMembership(role="member", user=john, collaboration=ai_computing)
    admin_ai_computing = CollaborationMembership(role="admin", user=admin, collaboration=ai_computing)
    jane_ai_computing = CollaborationMembership(role="member", user=jane, collaboration=ai_computing)
    sarah_ai_computing = CollaborationMembership(role="member", user=sarah, collaboration=ai_computing)

    betty_uuc_teachers = CollaborationMembership(role="member", user=betty, collaboration=uuc_teachers)

    roger_uva_research = CollaborationMembership(role="member", user=roger, collaboration=uva_research)
    peter_uva_research = CollaborationMembership(role="member", user=peter, collaboration=uva_research)
    sarah_uva_research = CollaborationMembership(role="admin", user=sarah, collaboration=uva_research)
    user_two_suspend_uva_research = CollaborationMembership(role="member", user=user_two_suspend,
                                                            collaboration=uva_research)
    _persist(db, john_ai_computing, admin_ai_computing, roger_uva_research, peter_uva_research, sarah_uva_research,
             jane_ai_computing, sarah_ai_computing, user_two_suspend_uva_research, betty_uuc_teachers)

    admin_service_aups = [ServiceAup(user=admin, service=service, aup_url=service.accepted_user_policy) for service in
                          ai_computing.services]
    _persist(db, *admin_service_aups)

    group_researchers = Group(name=ai_researchers_group,
                              short_name=ai_researchers_group_short_name,
                              global_urn="uuc:ai_computing:ai_res",
                              identifier=str(uuid.uuid4()),
                              auto_provision_members=False,
                              description="Artifical computing researchers",
                              collaboration=ai_computing,
                              collaboration_memberships=[john_ai_computing,
                                                         jane_ai_computing])
    group_developers = Group(name="AI developers",
                             short_name="ai_dev",
                             global_urn="uuc:ai_computing:ai_dev",
                             identifier=str(uuid.uuid4()),
                             auto_provision_members=False,
                             description="Artifical computing developers",
                             collaboration=ai_computing,
                             collaboration_memberships=[john_ai_computing])
    group_science = Group(name=group_science_name,
                          short_name="science",
                          global_urn="uva:research:science",
                          identifier=str(uuid.uuid4()),
                          auto_provision_members=True,
                          description="Science",
                          collaboration=uva_research,
                          collaboration_memberships=[roger_uva_research])
    _persist(db, group_researchers, group_developers, group_science)

    join_request_john = JoinRequest(message="Please...", reference=join_request_reference, user=john,
                                    collaboration=ai_computing, hash=generate_token(), status="open")
    join_request_peter = JoinRequest(message="Please...", user=peter, collaboration=ai_computing,
                                     hash=join_request_peter_hash, status="open")
    join_request_mary = JoinRequest(message="Please...", user=mary, collaboration=ai_computing, hash=generate_token(),
                                    status="open")
    join_request_uva_research = JoinRequest(message="Please...", user=james, collaboration=uva_research,
                                            hash=generate_token(), status="open")

    _persist(db, join_request_john, join_request_peter, join_request_mary, join_request_uva_research)

    invitation = Invitation(hash=invitation_hash_curious, invitee_email="*****@*****.**", collaboration=ai_computing,
                            expiry_date=default_expiry_date(), user=admin, message="Please join...",
                            intended_role="admin", status="open")
    invitation_accepted = Invitation(hash=generate_token(), invitee_email="*****@*****.**", collaboration=ai_computing,
                                     expiry_date=default_expiry_date(), user=admin, message="Please join...",
                                     status="accepted", intended_role="admin")
    invitation_uva = Invitation(hash=invitation_hash_uva, invitee_email="*****@*****.**", collaboration=uva_research,
                                expiry_date=default_expiry_date(), user=admin, message="Please join...",
                                intended_role="member", groups=[group_science], status="open")
    invitation_noway = Invitation(hash=invitation_hash_no_way, invitee_email="*****@*****.**", collaboration=ai_computing,
                                  expiry_date=datetime.date.today() - datetime.timedelta(days=21), user=admin,
                                  intended_role="member", status="expired",
                                  message="Let me please join as I really, really, really \n really, "
                                          "really, really \n want to...")
    _persist(db, invitation, invitation_accepted, invitation_uva, invitation_noway)

    collaboration_request_1 = CollaborationRequest(name=collaboration_request_name, short_name="new_collaboration",
                                                   website_url="https://google.com", logo=read_image("request.jpg"),
                                                   status=STATUS_OPEN, message="For research", organisation=uuc,
                                                   requester=peter)
    collaboration_request_2 = CollaborationRequest(name="Polse", short_name="polse",
                                                   website_url="https://www.pols.me/", logo=read_image("pols.jpg"),
                                                   status=STATUS_OPEN, message="For research", organisation=uuc,
                                                   requester=peter)
    _persist(db, collaboration_request_1, collaboration_request_2)

    service_connection_request_network = ServiceConnectionRequest(message="AI computing needs storage",
                                                                  hash=network_service_connection_request_hash,
                                                                  requester=admin, collaboration=ai_computing,
                                                                  service=storage)
    service_connection_request_wiki = ServiceConnectionRequest(message="UVA research needs ssh",
                                                               hash=ssh_service_connection_request_hash,
                                                               requester=sarah, collaboration=uva_research,
                                                               service=service_ssh_uva)
    service_connection_request_wireless = ServiceConnectionRequest(message="AI computing needs wireless",
                                                                   hash=wireless_service_connection_request_hash,
                                                                   requester=jane, collaboration=ai_computing,
                                                                   service=wireless, is_member_request=True)
    _persist(db, service_connection_request_network, service_connection_request_wiki,
             service_connection_request_wireless)

    user_token_sarah = UserToken(name="token", description="some", hashed_token=secure_hash(sarah_user_token),
                                 user=sarah, service=network)
    _persist(db, user_token_sarah)

    if perf_test:
        users = []
        for i in range(1, 84):
            user = User(uid=f"urn:persoon:numero{i:03d}",
                        name=f"Piet Doe de {i}de",
                        email=f"pietdoe{i}@example.org",
                        username=f"pietdoe{i}",
                        schac_home_organisation="harderwijk.edu")
            users.append(user)
        _persist(db, *users)

        for i in range(1, 40):
            co = Collaboration(name=f"Samenwerking Numero {i}",
                               identifier=str(uuid.uuid4()),
                               short_name=f"co_nr_{i:03d}",
                               global_urn=f"ucc:co_nr_{i:03d}",
                               description="Een van vele COs",
                               logo=read_image("computing.jpeg"),
                               organisation=uuc,
                               services=[mail, network],
                               join_requests=[],
                               invitations=[],
                               website_url="https://www.google.nl",
                               accepted_user_policy="https://www.google.nl",
                               disclose_email_information=True,
                               disclose_member_information=True)
            _persist(db, co)
            _persist(db, CollaborationMembership(role="admin", user=users[2 * i + 0], collaboration=co))
            _persist(db, CollaborationMembership(role="member", user=users[2 * i + 1], collaboration=co))
            _persist(db, CollaborationMembership(role="member", user=users[2 * i + 2], collaboration=co))
            _persist(db, CollaborationMembership(role="member", user=users[2 * i + 3], collaboration=co))

    db.session.commit()
Exemplo n.º 16
0
 def test_eligible_users_to_reset_token_no_user_information(self):
     res = eligible_users_to_reset_token(User(organisation_memberships=[], collaboration_memberships=[]))
     self.assertEqual(1, len(res))
     self.assertEqual(self.app.app_config.mail.info_email, res[0]["email"])