コード例 #1
0
ファイル: roles.py プロジェクト: 1amongus/edx-platform
 def add_users(self, *users):
     """
     Add the supplied django users to this role.
     """
     # silently ignores anonymous and inactive users so that any that are
     # legit get updated.
     for user in users:
         if user.is_authenticated and user.is_active and not self.has_user(user):
             entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org)
             entry.save()
             if hasattr(user, '_roles'):
                 del user._roles
コード例 #2
0
ファイル: roles.py プロジェクト: auvipy/edx-platform
 def add_course(self, *course_keys):
     """
     Grant this object's user the object's role for the supplied courses
     """
     if self.user.is_authenticated() and self.user.is_active:
         for course_key in course_keys:
             entry = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org)
             entry.save()
         if hasattr(self.user, '_roles'):
             del self.user._roles
     else:
         raise ValueError("user is not active. Cannot grant access to courses")
コード例 #3
0
 def add_course(self, *course_keys):
     """
     Grant this object's user the object's role for the supplied courses
     """
     if self.user.is_authenticated and self.user.is_active:
         for course_key in course_keys:
             entry = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org)
             entry.save()
         if hasattr(self.user, '_roles'):
             del self.user._roles
     else:
         raise ValueError("user is not active. Cannot grant access to courses")
コード例 #4
0
 def add_users(self, *users):
     """
     Add the supplied django users to this role.
     """
     # silently ignores anonymous and inactive users so that any that are
     # legit get updated.
     for user in users:
         if user.is_authenticated and user.is_active and not self.has_user(user):
             entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org)
             entry.save()
             if hasattr(user, '_roles'):
                 del user._roles
コード例 #5
0
ファイル: roles.py プロジェクト: rsloot/edx-platform
 def add_users(self, *users):
     """
     Add the supplied django users to this role.
     """
     # silently ignores anonymous and inactive users so that any that are
     # legit get updated.
     from student.models import CourseAccessRole
     for user in users:
         if user.is_authenticated and user.is_active and not self.has_user(user):
             entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org)
             entry.save()
             if hasattr(user, '_roles'):
                 # pylint: disable=protected-access
                 user._roles.add_role(entry)
    def create_course_reference_data(course_key):
        """
        Populates DB with test data
        """
        user = UserFactory()
        group = GroupFactory()
        CourseGroupRelationship(course_id=course_key, group=group).save()
        StudentGradebook(
            user=user,
            course_id=course_key,
            grade=0.9,
            proforma_grade=0.91,
            progress_summary='test',
            grade_summary='test',
            grading_policy='test',
        ).save()
        StudentProgress(user=user, course_id=course_key, completions=1).save()
        CourseModuleCompletion(user=user, course_id=course_key, content_id='test', stage='test').save()
        CourseEnrollment(user=user, course_id=course_key).save()
        CourseAccessRole(user=user, course_id=course_key, org='test', role='TA').save()
        handouts_usage_key = course_key.make_usage_key('course_info', 'handouts')
        StudentModule(student=user, course_id=course_key, module_state_key=handouts_usage_key).save()
        CourseAggregatedMetaData(id=course_key, total_assessments=10, total_modules=20).save()

        structure_json = '{"test": true}'
        course_structure, created = CourseStructure.objects.get_or_create(
            course_id=course_key,
            defaults={'structure_json': structure_json}
        )
        if not created:
            course_structure.structure_json = structure_json
            course_structure.save()

        CourseOverview.get_from_id(course_key)
コード例 #7
0
    def update_team(self, instance, team):
        CourseAccessRole.objects.filter(course_id=instance.id).delete()

        # TODO In the future we can optimize by getting users in a single query.
        CourseAccessRole.objects.bulk_create([
            CourseAccessRole(course_id=instance.id, role=member['role'], user=User.objects.get(username=member['user']))
            for member in team
        ])
コード例 #8
0
    def test_get_cohort(self):
        """
        Make sure cohorts.get_cohort() does the right thing when the course is cohorted
        """
        course = modulestore().get_course(self.toy_course_key)
        self.assertEqual(course.id, self.toy_course_key)
        self.assertFalse(cohorts.is_course_cohorted(course.id))

        user = UserFactory(username="******", email="*****@*****.**")
        other_user = UserFactory(username="******", email="*****@*****.**")
        staff_user = UserFactory(username="******", email="*****@*****.**")

        self.assertIsNone(cohorts.get_cohort(user, course.id),
                          "No cohort created yet")

        cohort = CohortFactory(course_id=course.id,
                               name="TestCohort",
                               users=[user])
        role = CourseAccessRole(user=staff_user,
                                role="staff",
                                course_id=course.id,
                                org=course.org)
        role.save()

        self.assertIsNone(cohorts.get_cohort(user, course.id),
                          "Course isn't cohorted, so shouldn't have a cohort")

        # Make the course cohorted...
        config_course_cohorts(course, is_cohorted=True)

        self.assertEqual(
            cohorts.get_cohort(user, course.id).id, cohort.id,
            "user should be assigned to the correct cohort")

        self.assertEqual(
            cohorts.get_cohort(other_user, course.id).id,
            cohorts.get_cohort_by_name(course.id,
                                       cohorts.DEFAULT_COHORT_NAME).id,
            "other_user should be assigned to the default cohort")

        self.assertEqual(
            cohorts.get_cohort(staff_user, course.id).id,
            cohorts.get_cohort_by_name(course.id,
                                       CourseUserGroup.default_cohort_name).id,
            "staff_user should be assigned to default cohort")
コード例 #9
0
    def update_team(self, instance, team):
        # Existing data should remain intact when performing a partial update.
        if not self.partial:
            CourseAccessRole.objects.filter(course_id=instance.id).delete()

        # TODO In the future we can optimize by getting users in a single query.
        CourseAccessRole.objects.bulk_create([
            CourseAccessRole(course_id=instance.id, role=member['role'], user=User.objects.get(username=member['user']))
            for member in team
        ])
コード例 #10
0
    def has_user(self, user):
        """
        Return whether the supplied django user has access to this role.
        """
        if not (user.is_authenticated() and user.is_active):
            return False

        # pylint: disable=protected-access
        if not hasattr(user, '_roles'):
            user._roles = set(
                CourseAccessRole.objects.filter(user=user).all()
            )

        role = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org)
        return role in user._roles
コード例 #11
0
    def has_course(self, course_key):
        """
        Return whether the role's user has the configured role access to the passed course
        """
        if not (self.user.is_authenticated() and self.user.is_active):
            return False

        # pylint: disable=protected-access
        if not hasattr(self.user, '_roles'):
            self.user._roles = list(
                CourseAccessRole.objects.filter(user=self.user).all()
            )

        role = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org)
        return role in self.user._roles
    def handle(self, *args, **options):
        if len(args) < 1 or len(args) > 2:
            print Command.help
            return

        dry_run = True
        create_log = False

        msg_string = 'Script started on {}'.format(datetime.datetime.now().ctime())

        if 'repair' in args:
            dry_run = False
        if 'dryrun' in args:
            dry_run = True
        if 'createlog' in args:
            create_log = True
            file_handler = logging.FileHandler('repair_internal_admin_instructor_role.log')
            file_handler.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
            file_handler.setFormatter(formatter)
            log.addHandler(file_handler)

        log.info(msg_string)

        if dry_run:
            msg_string = 'Script started in dry run mode, this will print for all internal admins courses for which we need to remove or add theirs instructor role'
        else:
            msg_string = 'Script started in repair mode, this will permanently remove or add instructor role of internal admins. THIS IS IRREVERSIBLE!'

        log.info(msg_string)

        internal_admin_group_name = 'mcka_role_internal_admin'
        internal_tag_group_type = 'tag:internal'
        instructor_role = 'instructor'
        staff_role = 'staff'
        number_of_removed_roles = 0
        number_of_added_roles = 0

        #get all internal admins
        try:
            internal_admin_group = Group.objects.get(name__icontains=internal_admin_group_name)
        except ObjectDoesNotExist:
            internal_admin_group = None

        if internal_admin_group:
            internal_admins = internal_admin_group.user_set.all()

        #get internal tagged courses
        try:
            internal_courses_group = Group.objects.get(groupprofile__group_type=internal_tag_group_type)
        except ObjectDoesNotExist:
            internal_courses_group = None

        if internal_courses_group:
            internal_courses = CourseGroupRelationship.objects.filter(group=internal_courses_group)
            internal_courses_ids = []
            for internal_course in internal_courses:
                internal_courses_ids.append(internal_course.course_id)

        #for all internal admins check their roles and remove instructor role on course if he doesn't have staff role on course and course isn't tagged internal
        for internal_admin in internal_admins:
            user_roles = CourseAccessRole.objects.filter(user=internal_admin)

            instructor_courses = []
            staff_courses = []
            for user_role in user_roles:
                if user_role.role == instructor_role:
                    instructor_courses.append(user_role.course_id)
                if user_role.role == staff_role:
                    staff_courses.append(user_role.course_id)

            for instructor_course in instructor_courses:
                if str(instructor_course) not in internal_courses_ids and instructor_course not in staff_courses:
                    number_of_removed_roles += 1
                    if dry_run:
                        msg_string = 'Remove instructor role for internal admin ' + str(internal_admin.id) + ' on course ' + str(instructor_course) + '.'
                        log.info(msg_string)
                    else:
                        role_to_delete = CourseAccessRole.objects.get(user=internal_admin, role=instructor_role, course_id=instructor_course)
                        role_to_delete.delete()

        #for all internal tagged course check roles and if internal admins don't have instructor role on course add it
        for internal_course in internal_courses:
            course_id = get_course_key(internal_course.course_id)
            course_roles = CourseAccessRole.objects.filter(course_id=course_id)
            instructor_users = []
            for course_role in course_roles:
                if course_role.role == instructor_role:
                    instructor_users.append(course_role.user_id)

            for internal_admin in internal_admins:
                if internal_admin.id not in instructor_users:
                    number_of_added_roles += 1
                    if dry_run:
                        msg_string = 'Add instructor role for internal admin ' + str(internal_admin.id) + ' on course ' + str(course_id) + '.'
                        log.info(msg_string)
                    else:
                        course = courses.get_course(course_id, 0)
                        new_role = CourseAccessRole(user=internal_admin, role=instructor_role, course_id=course.id, org=course.org)
                        new_role.save()

        msg_string = 'Number of removed roles: ' + str(number_of_removed_roles) + '.'
        log.info(msg_string)
        msg_string = 'Number of added roles: ' + str(number_of_added_roles) + '.'
        log.info(msg_string)

        log.info('--------------------------------------------------------------------------------------------------------------------')

        if create_log:
            print 'Script started in create log mode, please open repair_internal_admin_instructor_role.log file.'
コード例 #13
0
    def handle(self, *args, **options):
        if len(args) < 1 or len(args) > 2:
            print(Command.help)
            return

        dry_run = True
        create_log = False

        msg_string = 'Script started on {}'.format(
            datetime.datetime.now().ctime())

        if 'repair' in args:
            dry_run = False
        if 'dryrun' in args:
            dry_run = True
        if 'createlog' in args:
            create_log = True
            file_handler = logging.FileHandler(
                'repair_internal_admin_instructor_role.log')
            file_handler.setLevel(logging.DEBUG)
            formatter = logging.Formatter(
                '%(asctime)s-%(name)s-%(levelname)s-%(message)s')
            file_handler.setFormatter(formatter)
            log.addHandler(file_handler)

        log.info(msg_string)

        if dry_run:
            msg_string = 'Script started in dry run mode, this will print for all internal admins courses for which ' \
                         'we need to remove or add theirs instructor role'
        else:
            msg_string = 'Script started in repair mode, this will permanently remove or add instructor role of ' \
                         'internal admins. THIS IS IRREVERSIBLE!'

        log.info(msg_string)

        internal_admin_group_name = 'mcka_role_internal_admin'
        internal_tag_group_type = 'tag:internal'
        instructor_role = 'instructor'
        staff_role = 'staff'
        number_of_removed_roles = 0
        number_of_added_roles = 0

        #get all internal admins
        try:
            internal_admin_group = Group.objects.get(
                name__icontains=internal_admin_group_name)
        except ObjectDoesNotExist:
            internal_admin_group = None

        if internal_admin_group:
            internal_admins = internal_admin_group.user_set.all()

        #get internal tagged courses
        try:
            internal_courses_group = Group.objects.get(
                groupprofile__group_type=internal_tag_group_type)
        except ObjectDoesNotExist:
            internal_courses_group = None

        if internal_courses_group:
            internal_courses = CourseGroupRelationship.objects.filter(
                group=internal_courses_group)
            internal_courses_ids = []
            for internal_course in internal_courses:
                internal_courses_ids.append(internal_course.course_id)

        # for all internal admins check their roles and remove instructor role on course
        # if he doesn't have staff role on course and course isn't tagged internal
        for internal_admin in internal_admins:
            user_roles = CourseAccessRole.objects.filter(user=internal_admin)

            instructor_courses = []
            staff_courses = []
            for user_role in user_roles:
                if user_role.role == instructor_role:
                    instructor_courses.append(user_role.course_id)
                if user_role.role == staff_role:
                    staff_courses.append(user_role.course_id)

            for instructor_course in instructor_courses:
                if str(
                        instructor_course
                ) not in internal_courses_ids and instructor_course not in staff_courses:
                    number_of_removed_roles += 1
                    if dry_run:
                        msg_string = 'Remove instructor role for internal admin ' + str(internal_admin.id) +\
                                     ' on course ' + str(instructor_course) + '.'
                        log.info(msg_string)
                    else:
                        role_to_delete = CourseAccessRole.objects.get(
                            user=internal_admin,
                            role=instructor_role,
                            course_id=instructor_course)
                        role_to_delete.delete()

        # for all internal tagged course check roles and if internal admins don't have instructor role on course add it
        for internal_course in internal_courses:
            course_id = get_course_key(internal_course.course_id)
            course_roles = CourseAccessRole.objects.filter(course_id=course_id)
            instructor_users = []
            for course_role in course_roles:
                if course_role.role == instructor_role:
                    instructor_users.append(course_role.user_id)

            for internal_admin in internal_admins:
                if internal_admin.id not in instructor_users:
                    number_of_added_roles += 1
                    if dry_run:
                        msg_string = 'Add instructor role for internal admin ' + str(internal_admin.id) + \
                                     ' on course ' + str(course_id) + '.'
                        log.info(msg_string)
                    else:
                        course = courses.get_course(course_id, 0)
                        new_role = CourseAccessRole(user=internal_admin,
                                                    role=instructor_role,
                                                    course_id=course.id,
                                                    org=course.org)
                        new_role.save()

        msg_string = 'Number of removed roles: ' + str(
            number_of_removed_roles) + '.'
        log.info(msg_string)
        msg_string = 'Number of added roles: ' + str(
            number_of_added_roles) + '.'
        log.info(msg_string)

        log.info(
            '---------------------------------------------------------------------------------------------------'
        )

        if create_log:
            print(
                'Script started in create log mode, please open repair_internal_admin_instructor_role.log file.'
            )