def test_load(self):
     site_auths.initialize()
     AuthUpdater.add_empty_groups_for_tests(EXPORT)
     AuthUpdater.add_empty_roles_for_tests(TMG_ROLE, DATA_MANAGER_ROLE,
                                           SITE_DATA_MANAGER_ROLE)
     import_module(f"edc_action_item.auths")
     AuthUpdater(verbose=True)
 def test_load(self):
     # import_module("edc_dashboard.auths")
     import_module("edc_navbar.auths")
     # import_module("edc_data_manager.auths")
     # import_module("edc_lab.auths")
     import_module("edc_adverse_event.auths")
     AuthUpdater.add_empty_groups_for_tests(EXPORT)
     AuthUpdater.add_empty_roles_for_tests(DATA_MANAGER_ROLE, SITE_DATA_MANAGER_ROLE)
     AuthUpdater(verbose=True)
Exemple #3
0
 def test_password_setter_user(self):
     AuthUpdater(verbose=False)
     usernames = create_users(5)
     user = User.objects.all()[0]
     pwsetter = PasswordSetter(super_username=user.username)
     pwsetter.reset_users(usernames)
     self.assertEqual(len(mail.outbox), 5)  # noqa
    def test_add_group_with_callable(self):
        def codenames_callable():
            return [
                "edc_auth.add_subjectrequisition",
                "edc_auth.change_subjectrequisition",
                "edc_auth.delete_subjectrequisition",
                "edc_auth.view_subjectrequisition",
            ]

        codenames = [
            "edc_auth.add_testmodel",
            "edc_auth.change_testmodel",
            "edc_auth.delete_testmodel",
            "edc_auth.view_testmodel",
        ]
        codenames_with_callable = copy(codenames)
        codenames_with_callable.append(codenames_callable)
        site_auths.clear()
        site_auths.add_group(*codenames_with_callable, name="GROUP")
        AuthUpdater()
        group = Group.objects.get(name="GROUP")

        codenames.extend(codenames_callable())
        codenames.sort()
        self.assertEqual(
            [
                p.codename for p in group.permissions.filter(
                    content_type__app_label="edc_auth").order_by("codename")
            ],
            [c.split(".")[1] for c in codenames],
        )
Exemple #5
0
    def test_post_migrate(self):
        """Assert post-migrate updated defaults for model Role."""
        AuthUpdater(verbose=False)
        self.assertGreater(Role.objects.all().count(), 0)
        for role_name in [
                ACCOUNT_MANAGER_ROLE,
                AUDITOR_ROLE,
                CLINICIAN_ROLE,
                CLINICIAN_SUPER_ROLE,
                CUSTOM_ROLE,
                NURSE_ROLE,
                STAFF_ROLE,
                STATISTICIAN,
        ]:
            try:
                Role.objects.get(name=role_name)
            except ObjectDoesNotExist:
                self.fail(
                    f"Role name unexpectedly does not exist. Got {role_name}")

        role = Role.objects.get(name=CLINICIAN_ROLE)
        groups_from_role = [group.name for group in role.groups.all()]
        groups_from_role.sort()
        groups_from_site_auths = site_auths.roles.get(CLINICIAN_ROLE)
        groups_from_site_auths.sort()
        self.assertEqual(groups_from_role, groups_from_site_auths)
    def test_add_group_convert_to_export_with_callable(self):
        def more_codenames():
            return [
                "edc_auth.add_subjectrequisition",
                "edc_auth.change_subjectrequisition",
                "edc_auth.delete_subjectrequisition",
                "edc_auth.view_subjectrequisition",
            ]

        codenames = [
            "edc_auth.add_testmodel",
            "edc_auth.change_testmodel",
            "edc_auth.delete_testmodel",
            "edc_auth.view_testmodel",
            more_codenames,
        ]
        site_auths.clear()
        site_auths.add_group(*codenames,
                             name="GROUP_EXPORT",
                             convert_to_export=True)
        AuthUpdater()
        group = Group.objects.get(name="GROUP_EXPORT")
        self.assertEqual(
            [
                p.codename for p in group.permissions.filter(
                    content_type__app_label="edc_auth")
            ],
            ["export_subjectrequisition", "export_testmodel"],
        )
Exemple #7
0
    def test_bad_username(self):
        AuthUpdater(verbose=False)
        self.assertRaises(
            UserImporterError,
            UserImporter,
            username=None,
            first_name=fake.first_name(),
            last_name=None,
            email=fake.email(),
            site_names=[],
            role_names=[],
            send_email_to_user=True,
        )

        self.assertRaises(
            UserImporterError,
            UserImporter,
            username="******",
            first_name=fake.first_name(),
            last_name=fake.last_name(),
            email=fake.email(),
            site_names=[],
            role_names=[],
            send_email_to_user=True,
        )
Exemple #8
0
 def test_password_setter_sites(self):
     AuthUpdater(verbose=False)
     count = User.objects.filter(userprofile__sites__name="harare").count()
     create_users(5, site_name="harare")
     user = User.objects.all()[0]
     pwsetter = PasswordSetter(super_username=user.username)
     pwsetter.reset_by_sites(["harare"])
     self.assertEqual(len(mail.outbox), User.objects.all().count() + count)  # noqa
Exemple #9
0
 def test_password_setter_groups(self):
     AuthUpdater(verbose=False)
     count = User.objects.filter(groups__name=CLINIC).count()
     create_users(5, group_name=CLINIC)
     user = User.objects.all()[0]
     pwsetter = PasswordSetter(super_username=user.username)
     pwsetter.reset_by_groups([CLINIC])
     self.assertEqual(len(mail.outbox), User.objects.all().count() + count)  # noqa
 def test_add_groups_for_role(self):
     AuthUpdater(verbose=False)
     user = User.objects.create(
         username="******", is_superuser=False, is_active=True, is_staff=True
     )
     self.assertEqual(user.groups.all().count(), 0)
     role = Role.objects.get(name=CLINICIAN_ROLE)
     user.userprofile.roles.add(role)
     user.refresh_from_db()
     self.assertGreater(user.groups.all().count(), 0)
 def test_randomization_list_model_add_change_delete_perms_removed_everywhere(
         self):
     AuthUpdater(verbose=False)
     for group in Group.objects.all():
         qs = group.permissions.all()
         self.assertNotIn("add_randomizationlist",
                          "|".join([o.codename for o in qs]))
         self.assertNotIn("change_randomizationlist",
                          "|".join([o.codename for o in qs]))
         self.assertNotIn("delete_randomizationlist",
                          "|".join([o.codename for o in qs]))
 def setUpTestData(cls):
     url_names.register("dashboard_url", "dashboard_url", "edc_dashboard")
     site_auths.clear()
     site_auths.add_group("edc_dashboard.view_my_listboard", name=CLINIC)
     site_auths.add_custom_permissions_tuples(
         model="edc_dashboard.dashboard",
         codename_tuples=(("edc_dashboard.view_my_listboard",
                           "View my listboard"), ),
     )
     AuthUpdater(verbose=False, warn_only=True)
     return super().setUpTestData()
Exemple #13
0
    def test_mocca_register_changelist(self):
        import_module("mocca_auth.auths")
        AuthUpdater(verbose=True)

        make_recipe("mocca_screening.moccaregistercontact",
                    mocca_register=self.mocca_register)
        mocca_register_contact = make_recipe(
            "mocca_screening.moccaregistercontact",
            mocca_register=self.mocca_register)

        self.login(superuser=False, groups=[EVERYONE, AUDITOR, SCREENING])

        change_list_url = reverse(self.changelist_url_name)
        change_list_url = f"{change_list_url}?q={self.mocca_register.mocca_study_identifier}"
        screening_add_url = reverse(
            "mocca_screening_admin:mocca_screening_subjectscreening_add")
        refusal_add_url = reverse(
            "mocca_screening_admin:mocca_screening_subjectrefusalscreening_add"
        )

        # Test screening and refusal buttons are shown
        # (for alive, don't call again, willing to attend)
        mocca_register_contact.survival_status = ALIVE
        mocca_register_contact.call = NO
        mocca_register_contact.willing_to_attend = YES
        mocca_register_contact.save()
        self.assertTrue(mocca_register_contact.call == NO)
        self.assertTrue(mocca_register_contact.willing_to_attend == YES)
        self.assertTrue(mocca_register_contact.survival_status == ALIVE)
        response = self.app.get(change_list_url, user=self.user, status=200)
        self.assertIn(self.mocca_register.mocca_study_identifier, response)
        self.assertIn(screening_add_url, response)
        self.assertIn(refusal_add_url, response)

        # Test screening button hidden, refusal button shown
        # (for alive, don't call again, NOT willing to attend)
        mocca_register_contact.willing_to_attend = NO
        mocca_register_contact.save()
        self.assertTrue(mocca_register_contact.willing_to_attend == NO)
        response = self.app.get(change_list_url, user=self.user, status=200)
        self.assertIn(self.mocca_register.mocca_study_identifier, response)
        self.assertNotIn(screening_add_url, response)
        self.assertIn(refusal_add_url, response)

        # Test neither the refusal nor the screening button shown
        # (for deceased status)
        mocca_register_contact.willing_to_attend = NOT_APPLICABLE
        mocca_register_contact.survival_status = DEAD
        mocca_register_contact.save()
        self.assertTrue(mocca_register_contact.survival_status == DEAD)
        response = self.app.get(change_list_url, user=self.user, status=200)
        self.assertNotIn(screening_add_url, response)
        self.assertNotIn(refusal_add_url, response)
Exemple #14
0
 def test_unknown_role(self):
     AuthUpdater(verbose=False)
     self.assertRaises(
         UserImporterError,
         UserImporter,
         username="******",
         first_name=fake.first_name(),
         last_name=fake.last_name(),
         email=fake.email(),
         site_names=["harare"],
         role_names=["blah"],
         send_email_to_user=True,
     )
Exemple #15
0
 def test_add_roles_to_user(self):
     AuthUpdater(verbose=False)
     create_users()
     user = user_model.objects.all()[0]
     self.assertEqual(user.groups.all().count(), 0)
     role = Role.objects.get(name=CLINICIAN_ROLE)
     # should trigger post add m2m signal
     user.userprofile.roles.add(role)
     user.refresh_from_db()
     self.assertGreater(user.groups.all().count(), 0)
     # see groups_by_role_name for expected group counts
     # note, count is the unique list count
     self.assertEqual(user.groups.all().count(),
                      len(site_auths.roles.get(CLINICIAN_ROLE)))
 def test_group_has_randomization_list_model_view_perms(self):
     """Assert group has view perms for each randomizer,
     others perms are removed.
     """
     AuthUpdater(verbose=False)
     group = Group.objects.get(name=RANDO_BLINDED)
     qs = group.permissions.all()
     self.assertGreater(qs.count(), 0)
     self.assertIn("view_randomizationlist",
                   "|".join([o.codename for o in qs]))
     group = Group.objects.get(name=RANDO_UNBLINDED)
     qs = group.permissions.all()
     self.assertGreater(qs.count(), 0)
     self.assertIn("view_randomizationlist",
                   "|".join([o.codename for o in qs]))
    def test_rando_tuples(self):
        """Given the two registered randomizers, assert view codenames are returned"""
        AuthUpdater(verbose=False)
        self.assertIn(
            ("edc_randomization.view_randomizationlist",
             "Can view randomization list"),
            get_rando_permissions_tuples(),
        )

        self.assertIn(
            (
                "edc_auth.view_customrandomizationlist",
                "Can view custom randomization list",
            ),
            get_rando_permissions_tuples(),
        )
Exemple #18
0
 def test_remove_roles_to_user(self):
     AuthUpdater(verbose=False)
     create_users()
     user = user_model.objects.all()[0]
     self.assertEqual(user.groups.all().count(), 0)
     clinician_role = Role.objects.get(name=CLINICIAN_ROLE)
     clinician_super_role = Role.objects.get(name=CLINICIAN_SUPER_ROLE)
     clinician_groups = site_auths.roles.get(CLINICIAN_ROLE)
     clinician_super_groups = site_auths.roles.get(CLINICIAN_SUPER_ROLE)
     unique_group_cnt = len(
         list(set(clinician_groups + clinician_super_groups)))
     user.userprofile.roles.add(clinician_role)
     user.userprofile.roles.add(clinician_super_role)
     user.refresh_from_db()
     self.assertEqual(user.groups.all().count(), unique_group_cnt)
     # should trigger post remove m2m signal
     user.userprofile.roles.remove(clinician_super_role)
     self.assertEqual(user.groups.all().count(), len(clinician_groups))
Exemple #19
0
    def test_import_users(self):
        AuthUpdater(verbose=False)
        # import new users
        import_users(self.filename, resource_name=None, send_email_to_user=True)
        self.assertEqual(len(mail.outbox), User.objects.all().count())  # noqa
        self.assertEqual(
            mail.outbox[0].subject,
            f"{Protocol().project_name}: Your example.com user account is ready.",
        )

        # update existing users
        import_users(self.filename, resource_name=None, send_email_to_user=True)
        user_count = User.objects.all().count()
        self.assertEqual(len(mail.outbox), user_count * 2)  # noqa
        self.assertEqual(
            mail.outbox[0].subject,
            f"{Protocol().project_name}: Your example.com user account is ready.",
        )
 def test_add_group(self):
     codenames = [
         "edc_auth.add_testmodel",
         "edc_auth.change_testmodel",
         "edc_auth.delete_testmodel",
         "edc_auth.view_testmodel",
     ]
     site_auths.clear()
     site_auths.add_group(*codenames, name="GROUP")
     AuthUpdater()
     group = Group.objects.get(name="GROUP")
     self.assertEqual(
         [
             p.codename for p in group.permissions.filter(
                 content_type__app_label="edc_auth")
         ],
         [c.split(".")[1] for c in codenames],
     )
 def test_add_group_view_only(self):
     codenames = [
         "edc_auth.add_testmodel",
         "edc_auth.change_testmodel",
         "edc_auth.delete_testmodel",
         "edc_auth.view_testmodel",
     ]
     site_auths.clear()
     site_auths.add_group(*codenames,
                          name="GROUP_VIEW_ONLY",
                          view_only=True)
     AuthUpdater()
     group = Group.objects.get(name="GROUP_VIEW_ONLY")
     self.assertEqual(
         [
             p.codename for p in group.permissions.filter(
                 content_type__app_label="edc_auth")
         ],
         ["view_testmodel"],
     )
 def test_removes_randomization_list_model_perms2(self):
     self.assertIn(
         "view_customrandomizationlist",
         "|".join([o.codename for o in Permission.objects.all()]),
     )
     AuthUpdater(verbose=True)
     Permission.objects.filter(
         content_type__app_label__in=["edc_randomization", "edc_auth"])
     # confirm add_, change_, delete_ codenames for rando
     # do not exists in any groups.
     for group in Group.objects.all():
         qs = group.permissions.all()
         for model_name in ["customrandomizationlist", "randomizationlist"]:
             self.assertNotIn(f"add_{model_name}",
                              "|".join([o.codename for o in qs]))
             self.assertNotIn(f"change_{model_name}",
                              "|".join([o.codename for o in qs]))
             self.assertNotIn(f"delete_{model_name}",
                              "|".join([o.codename for o in qs]))
             if group.name in [RANDO_UNBLINDED, RANDO_BLINDED]:
                 self.assertIn(f"view_{model_name}",
                               "|".join([o.codename for o in qs]))
    def test_removes_for_apps_not_installed_by_exact_match(self):
        """The app edc_action_blah is not installed, and will
        be removed."""
        AuthUpdater(groups={
            "ACTION_GROUP": [
                "edc_action_blah.view_actionitem",
                "edc_action_item.view_actionitem",
            ]
        }, )
        groups = Group.objects.get(name="ACTION_GROUP")
        try:
            groups.permissions.get(content_type__app_label="edc_action_item",
                                   codename="view_actionitem")
        except ObjectDoesNotExist:
            self.fail("Permission unexpectedly does not exist")

        self.assertRaises(
            ObjectDoesNotExist,
            groups.permissions.get,
            content_type__app_label="edc_action_blah",
            codename="view_actionitem",
        )
    def test_add_group_remove_delete_with_callable(self):
        def more_codenames():
            return [
                "edc_auth.add_subjectrequisition",
                "edc_auth.change_subjectrequisition",
                "edc_auth.delete_subjectrequisition",
                "edc_auth.view_subjectrequisition",
            ]

        codenames = [
            "edc_auth.add_testmodel",
            "edc_auth.change_testmodel",
            "edc_auth.delete_testmodel",
            "edc_auth.view_testmodel",
            more_codenames,
        ]
        site_auths.clear()
        site_auths.add_group(*codenames,
                             name="GROUP_NO_DELETE",
                             no_delete=True)
        AuthUpdater()
        group = Group.objects.get(name="GROUP_NO_DELETE")

        codenames = [
            "add_subjectrequisition",
            "add_testmodel",
            "change_subjectrequisition",
            "change_testmodel",
            "view_subjectrequisition",
            "view_testmodel",
        ]
        self.assertEqual(
            [
                p.codename for p in group.permissions.filter(
                    content_type__app_label="edc_auth").order_by("codename")
            ],
            codenames,
        )
 def test_removes_edc_dashboard_dashboard_model_perms(self):
     """Perms for the dummy model edc_dashboard"""
     qs = Permission.objects.filter(
         content_type__app_label="edc_dashboard",
         codename__in=[
             "add_dashboard",
             "change_dashboard",
             "view_dashboard",
             "delete_dashboard",
         ],
     )
     self.assertEqual(qs.count(), 4)
     AuthUpdater()
     for group in Group.objects.all():
         qs = group.permissions.all()
         self.assertNotIn("add_dashboard",
                          "|".join([o.codename for o in qs]))
         self.assertNotIn("change_dashboard",
                          "|".join([o.codename for o in qs]))
         self.assertNotIn("view_dashboard",
                          "|".join([o.codename for o in qs]))
         self.assertNotIn("delete_dashboard",
                          "|".join([o.codename for o in qs]))
Exemple #26
0
 def test_with_custom_templates(self):
     AuthUpdater(verbose=False)
     created_email_template = Template("Hi $first_name, \n\nStay Classy")
     updated_email_template = Template(
         "Hi $first_name, \n\nYou stay classy San Diego"
     )
     first_name = fake.first_name()
     UserImporter(
         username="******",
         first_name=first_name,
         last_name=fake.last_name(),
         email=fake.email(),
         site_names=["harare"],
         role_names=[CLINICIAN_ROLE],
         send_email_to_user=True,
         created_email_template=created_email_template,
         updated_email_template=updated_email_template,
     )
     self.assertEqual(
         mail.outbox[0].body,
         created_email_template.safe_substitute(first_name=first_name),
     )
     UserImporter(
         username="******",
         first_name=first_name,
         last_name=fake.last_name(),
         email=fake.email(),
         site_names=["harare"],
         role_names=[CLINICIAN_ROLE],
         send_email_to_user=True,
         created_email_template=created_email_template,
         updated_email_template=updated_email_template,
     )
     self.assertEqual(
         mail.outbox[1].body,
         updated_email_template.safe_substitute(first_name=first_name),
     )
 def setUpTestData(cls):
     site_auths.initialize()
     import_module("edc_data_manager.auths")
     import_module("edc_dashboard.auths")
     import_module("edc_navbar.auths")
     AuthUpdater(verbose=False)
Exemple #28
0
 def test_load(self):
     import_module(f"edc_dashboard.auths")
     import_module(f"edc_navbar.auths")
     AuthUpdater(verbose=True)
Exemple #29
0
 def test_load(self):
     site_auths.autodiscover()
     AuthUpdater(verbose=False)
 def test_load(self):
     site_auths.initialize()
     import_module("edc_data_manager.auths")
     import_module("edc_dashboard.auths")
     import_module("edc_navbar.auths")
     AuthUpdater(verbose=False)