Exemple #1
0
def get_user_role(user, location, context):
    """
    Return corresponding string if user has staff or instructor role in Studio.
    This will not return student role because its purpose for using in Studio.

    :param location: a descriptor.location
    :param context: a course_id
    """
    if auth.has_access(user, CourseInstructorRole(location, context)):
        return 'instructor'
    else:
        return 'staff'
Exemple #2
0
 def test_detail_post_no_json(self):
     resp = self.client.post(
         self.detail_url,
         data={"role": "staff"},
         HTTP_ACCEPT="application/json",
     )
     self.assertEqual(resp.status_code, 204)
     # reload user from DB
     ext_user = User.objects.get(email=self.ext_user.email)
     self.assertTrue(auth.user_has_role(ext_user, CourseStaffRole(self.course.id)))
     self.assertFalse(auth.user_has_role(ext_user, CourseInstructorRole(self.course.id)))
     self.assert_enrolled()
Exemple #3
0
def get_user_role(user, location, context=None):
    """
    Return corresponding string if user has staff or instructor role in Studio.
    This will not return student role because its purpose for using in Studio.

    :param location: a descriptor.location (which may be a Location or a CourseLocator)
    :param context: a course_id. This is not used if location is a CourseLocator.
    """
    if auth.has_access(user, CourseInstructorRole(location, context)):
        return 'instructor'
    else:
        return 'staff'
Exemple #4
0
 def test_get_user_role_instructor(self):
     """
     Verifies if user is instructor.
     """
     add_users(self.global_admin, CourseInstructorRole(self.course_key),
               self.instructor)
     self.assertEqual('instructor',
                      get_user_role(self.instructor, self.course_key))
     add_users(self.global_admin, CourseStaffRole(self.course_key),
               self.staff)
     self.assertEqual('instructor',
                      get_user_role(self.instructor, self.course_key))
    def test_remove_user_from_course_group(self):
        """
        Tests removing user from course group (happy path).
        """
        add_users(self.global_admin, CourseInstructorRole(self.course_key), self.creator)
        add_users(self.global_admin, CourseStaffRole(self.course_key), self.creator)

        add_users(self.creator, CourseStaffRole(self.course_key), self.staff)
        self.assertTrue(user_has_role(self.staff, CourseStaffRole(self.course_key)))

        remove_users(self.creator, CourseStaffRole(self.course_key), self.staff)
        self.assertFalse(user_has_role(self.staff, CourseStaffRole(self.course_key)))

        add_users(self.creator, CourseAssistantRole(self.course_key), self.assistant)
        self.assertTrue(user_has_role(self.assistant, CourseAssistantRole(self.course_key)))

        remove_users(self.creator, CourseAssistantRole(self.course_key), self.assistant)
        self.assertFalse(user_has_role(self.assistant, CourseAssistantRole(self.course_key)))

        remove_users(self.creator, CourseInstructorRole(self.course_key), self.creator)
        self.assertFalse(user_has_role(self.creator, CourseInstructorRole(self.course_key)))
    def test_remove_master_course_staff_from_ccx(self):
        """
        Test remove staff of master course to ccx course
        """
        staff = self.make_staff()
        self.assertTrue(CourseStaffRole(self.course.id).has_user(staff))

        # adding instructor to master course.
        instructor = self.make_instructor()
        self.assertTrue(
            CourseInstructorRole(self.course.id).has_user(instructor))

        add_master_course_staff_to_ccx(self.course,
                                       self.ccx_locator,
                                       self.ccx.display_name,
                                       send_email=False)

        list_staff_master_course = list_with_level(self.course, 'staff')
        list_instructor_master_course = list_with_level(
            self.course, 'instructor')

        with ccx_course(self.ccx_locator) as course_ccx:
            list_staff_ccx_course = list_with_level(course_ccx, 'staff')
            self.assertEqual(len(list_staff_master_course),
                             len(list_staff_ccx_course))
            self.assertEqual(list_staff_master_course[0].email,
                             list_staff_ccx_course[0].email)

            list_instructor_ccx_course = list_with_level(
                course_ccx, 'instructor')
            self.assertEqual(len(list_instructor_ccx_course),
                             len(list_instructor_master_course))
            self.assertEqual(list_instructor_ccx_course[0].email,
                             list_instructor_master_course[0].email)

            # assert that role of staff and instructors of master course removed from ccx.
            remove_master_course_staff_from_ccx(self.course,
                                                self.ccx_locator,
                                                self.ccx.display_name,
                                                send_email=False)
            list_staff_ccx_course = list_with_level(course_ccx, 'staff')
            self.assertNotEqual(len(list_staff_master_course),
                                len(list_staff_ccx_course))

            list_instructor_ccx_course = list_with_level(
                course_ccx, 'instructor')
            self.assertNotEqual(len(list_instructor_ccx_course),
                                len(list_instructor_master_course))

            for user in list_staff_master_course:
                self.assertNotIn(user, list_staff_ccx_course)
            for user in list_instructor_master_course:
                self.assertNotIn(user, list_instructor_ccx_course)
Exemple #7
0
 def test_detail_post(self):
     resp = self.client.post(
         self.detail_url,
         data={"role": ""},
     )
     self.assertEqual(resp.status_code, 204)
     # reload user from DB
     ext_user = User.objects.get(email=self.ext_user.email)
     # no content: should not be in any roles
     self.assertFalse(auth.user_has_role(ext_user, CourseStaffRole(self.course.id)))
     self.assertFalse(auth.user_has_role(ext_user, CourseInstructorRole(self.course.id)))
     self.assert_not_enrolled()
Exemple #8
0
    def handle(self, *args, **options):
        "Execute the command"
        if len(args) != 2:
            raise CommandError("clone requires 2 arguments: <source-course_id> <dest-course_id>")

        source_course_id = self.course_key_from_arg(args[0])
        dest_course_id = self.course_key_from_arg(args[1])

        mstore = modulestore()

        print("Cloning course {0} to {1}".format(source_course_id, dest_course_id))

        with mstore.bulk_operations(dest_course_id):
            if mstore.clone_course(source_course_id, dest_course_id, ModuleStoreEnum.UserID.mgmt_command):
                print("copying User permissions...")
                # purposely avoids auth.add_user b/c it doesn't have a caller to authorize
                CourseInstructorRole(dest_course_id).add_users(
                    *CourseInstructorRole(source_course_id).users_with_role()
                )
                CourseStaffRole(dest_course_id).add_users(
                    *CourseStaffRole(source_course_id).users_with_role()
                )
Exemple #9
0
    def test_get_access_roles(self):
        """
            Test get access roles in course (staff and instructor)
        """
        roles = views.get_access_roles(text_type(self.course.id))
        self.assertEqual(len(roles), 1)

        # Add instructor user to the course
        instructor = UserFactory.create(password="******")
        role = CourseInstructorRole(self.course.id)
        role.add_users(instructor)
        roles = views.get_access_roles(text_type(self.course.id))
        self.assertEqual(len(roles), 2)
Exemple #10
0
def try_remove_instructor(request, locator, user):
    # remove all roles in this course from this user: but fail if the user
    # is the last instructor in the course team
    instructors = CourseInstructorRole(locator)
    if instructors.has_user(user):
        if instructors.users_with_role().count() == 1:
            msg = {
                "error":
                _("You may not remove the last instructor from a course")
            }
            raise CannotOrphanCourse(msg)
        else:
            auth.remove_users(request.user, instructors, user)
Exemple #11
0
def administrative_accesses_to_course_for_user(user, course_key):
    """
    Returns types of access a user have for given course.
    """
    global_staff = GlobalStaff().has_user(user)

    staff_access = (CourseStaffRole(course_key).has_user(user)
                    or OrgStaffRole(course_key.org).has_user(user))

    instructor_access = (CourseInstructorRole(course_key).has_user(user)
                         or OrgInstructorRole(course_key.org).has_user(user))

    return global_staff, staff_access, instructor_access
Exemple #12
0
    def handle(self, *args, **options):
        """
        Execute the command
        """

        source_course_id = CourseKey.from_string(options['source_course_id'])
        dest_course_id = CourseKey.from_string(options['dest_course_id'])

        mstore = modulestore()

        print("Cloning course {0} to {1}".format(source_course_id,
                                                 dest_course_id))

        with mstore.bulk_operations(dest_course_id):
            if mstore.clone_course(source_course_id, dest_course_id,
                                   ModuleStoreEnum.UserID.mgmt_command):
                print("copying User permissions...")
                # purposely avoids auth.add_user b/c it doesn't have a caller to authorize
                CourseInstructorRole(dest_course_id).add_users(
                    *CourseInstructorRole(source_course_id).users_with_role())
                CourseStaffRole(dest_course_id).add_users(
                    *CourseStaffRole(source_course_id).users_with_role())
Exemple #13
0
 def test_remove_user_from_course_group_permission_denied(self):
     """
     Verifies PermissionDenied if caller of remove_user_from_course_group is not instructor role.
     """
     add_users(self.global_admin, CourseInstructorRole(self.course_key),
               self.creator)
     another_staff = User.objects.create_user(
         'another', '*****@*****.**', 'foo')
     add_users(self.global_admin, CourseStaffRole(self.course_key),
               self.creator, self.staff, another_staff)
     with self.assertRaises(PermissionDenied):
         remove_users(self.staff, CourseStaffRole(self.course_key),
                      another_staff)
    def test_import_in_existing_course(self):
        """
        Check that course is imported successfully in existing course and users have their access roles
        """
        # Create a non_staff user and add it to course staff only
        __, nonstaff_user = self.create_non_staff_authed_user_client(authenticate=False)
        auth.add_users(self.user, CourseStaffRole(self.course.id), nonstaff_user)

        course = self.store.get_course(self.course.id)
        self.assertIsNotNone(course)
        display_name_before_import = course.display_name

        # Check that global staff user can import course
        with open(self.good_tar) as gtar:
            args = {"name": self.good_tar, "course-data": [gtar]}
            resp = self.client.post(self.url, args)
        self.assertEquals(resp.status_code, 200)

        course = self.store.get_course(self.course.id)
        self.assertIsNotNone(course)
        display_name_after_import = course.display_name

        # Check that course display name have changed after import
        self.assertNotEqual(display_name_before_import, display_name_after_import)

        # Now check that non_staff user has his same role
        self.assertFalse(CourseInstructorRole(self.course.id).has_user(nonstaff_user))
        self.assertTrue(CourseStaffRole(self.course.id).has_user(nonstaff_user))

        # Now course staff user can also successfully import course
        self.client.login(username=nonstaff_user.username, password='******')
        with open(self.good_tar) as gtar:
            args = {"name": self.good_tar, "course-data": [gtar]}
            resp = self.client.post(self.url, args)
        self.assertEquals(resp.status_code, 200)

        # Now check that non_staff user has his same role
        self.assertFalse(CourseInstructorRole(self.course.id).has_user(nonstaff_user))
        self.assertTrue(CourseStaffRole(self.course.id).has_user(nonstaff_user))
Exemple #15
0
 def test_add_user_to_course_group_permission_denied(self):
     """
     Verifies PermissionDenied if caller of add_user_to_course_group is not instructor role.
     """
     add_users(self.global_admin, CourseInstructorRole(self.course_key),
               self.creator)
     add_users(self.global_admin, CourseStaffRole(self.course_key),
               self.creator)
     with self.assertRaises(PermissionDenied):
         add_users(self.staff, CourseStaffRole(self.course_key), self.staff)
     with self.assertRaises(PermissionDenied):
         add_users(self.assistant, CourseAssistantRole(self.course_key),
                   self.assistant)
Exemple #16
0
    def has_object_permission(self, request, view, obj):
        if (hasattr(request, 'user') and
                # either the user is a staff or instructor of the master course
            (hasattr(obj, 'id') and
             (CourseInstructorRole(obj.id).has_user(request.user)
              or CourseStaffRole(obj.id).has_user(request.user))) or
                # or it is a safe method and the user is a coach on the course object
            (request.method in permissions.SAFE_METHODS
             and hasattr(obj, 'coach') and obj.coach == request.user)):
            return True

        return super(IsCourseStaffInstructorOrUserInUrlOrStaff,
                     self).has_permission(request, view)
Exemple #17
0
 def test_detail_post_instructor(self):
     resp = self.client.post(
         self.detail_url,
         data=json.dumps({"role": "instructor"}),
         content_type="application/json",
         HTTP_ACCEPT="application/json",
     )
     self.assertEqual(resp.status_code, 204)
     # reload user from DB
     ext_user = User.objects.get(email=self.ext_user.email)
     self.assertTrue(auth.has_access(ext_user, CourseInstructorRole(self.course.id)))
     self.assertFalse(CourseStaffRole(self.course.id).has_user(ext_user))
     self.assert_enrolled()
Exemple #18
0
def ccx_students_enrolling_center(action, identifiers, email_students, course_key, email_params, coach):
    """
    Function to enroll or unenroll/revoke students.

    Arguments:
        action (str): type of action to perform (Enroll, Unenroll/revoke)
        identifiers (list): list of students username/email
        email_students (bool): Flag to send an email to students
        course_key (CCXLocator): a CCX course key
        email_params (dict): dictionary of settings for the email to be sent
        coach (User): ccx coach

    Returns:
        list: list of error
    """
    errors = []

    if action == 'Enroll':
        ccx_course_overview = CourseOverview.get_from_id(course_key)
        course_locator = course_key.to_course_locator()
        staff = CourseStaffRole(course_locator).users_with_role()
        admins = CourseInstructorRole(course_locator).users_with_role()

        for identifier in identifiers:
            must_enroll = False
            try:
                email, student = get_valid_student_with_email(identifier)
                if student:
                    must_enroll = student in staff or student in admins or student == coach
            except CCXUserValidationException as exp:
                log.info("%s", exp)
                errors.append("{0}".format(exp))
                continue

            if CourseEnrollment.objects.is_course_full(ccx_course_overview) and not must_enroll:
                error = _('The course is full: the limit is {max_student_enrollments_allowed}').format(
                    max_student_enrollments_allowed=ccx_course_overview.max_student_enrollments_allowed)
                log.info("%s", error)
                errors.append(error)
                break
            enroll_email(course_key, email, auto_enroll=True, email_students=email_students, email_params=email_params)
    elif action == 'Unenroll' or action == 'revoke':
        for identifier in identifiers:
            try:
                email, __ = get_valid_student_with_email(identifier)
            except CCXUserValidationException as exp:
                log.info("%s", exp)
                errors.append("{0}".format(exp))
                continue
            unenroll_email(course_key, email, email_students=email_students, email_params=email_params)
    return errors
Exemple #19
0
    def has_object_permission(self, request, view, obj):
        # Added to allow staff users to delete courses.
        if hasattr(request, 'user') and request.user.is_staff:
            return True

        return (
            hasattr(request, 'user') and
            # either the user is a staff or instructor of the master course
            (hasattr(obj, 'course_id') and
             (CourseInstructorRole(obj.course_id).has_user(request.user)
              or CourseStaffRole(obj.course_id).has_user(request.user))) or
            # or it is a safe method and the user is a coach on the course object
            (request.method in permissions.SAFE_METHODS
             and hasattr(obj, 'coach') and obj.coach == request.user))
Exemple #20
0
def _has_access_to_location(user, location, access_level, course_context):
    '''
    Returns True if the given user has access_level (= staff or
    instructor) access to a location.  For now this is equivalent to
    having staff / instructor access to the course location.course.

    This means that user is in the staff_* group or instructor_* group, or is an overall admin.

    TODO (vshnayder): this needs to be changed to allow per-course_id permissions, not per-course
    (e.g. staff in 2012 is different from 2013, but maybe some people always have access)

    course is a string: the course field of the location being accessed.
    location = location
    access_level = string, either "staff" or "instructor"
    '''
    if user is None or (not user.is_authenticated()):
        debug("Deny: no user or anon user")
        return False

    if is_masquerading_as_student(user):
        return False

    if GlobalStaff().has_user(user):
        debug("Allow: user.is_staff")
        return True

    if access_level not in ('staff', 'instructor'):
        log.debug(
            "Error in access._has_access_to_location access_level=%s unknown",
            access_level)
        debug("Deny: unknown access level")
        return False

    staff_access = (CourseStaffRole(location, course_context).has_user(user)
                    or OrgStaffRole(location).has_user(user))

    if staff_access and access_level == 'staff':
        debug("Allow: user has course staff access")
        return True

    instructor_access = (CourseInstructorRole(location,
                                              course_context).has_user(user)
                         or OrgInstructorRole(location).has_user(user))

    if instructor_access and access_level in ('staff', 'instructor'):
        debug("Allow: user has course instructor access")
        return True

    debug("Deny: user did not have correct access")
    return False
Exemple #21
0
    def test_detail_post_staff_other_inst(self):
        auth.add_users(self.user, CourseInstructorRole(self.course.id),
                       self.user)

        resp = self.client.post(
            self.detail_url,
            data=json.dumps({"role": "staff"}),
            content_type="application/json",
            HTTP_ACCEPT="application/json",
        )
        self.assertEqual(resp.status_code, 204)
        # reload user from DB
        ext_user = User.objects.get(email=self.ext_user.email)
        self.assertTrue(
            auth.user_has_role(ext_user, CourseStaffRole(self.course.id)))
        self.assertFalse(
            auth.user_has_role(ext_user, CourseInstructorRole(self.course.id)))
        self.assert_enrolled()
        # check that other user is unchanged
        user = User.objects.get(email=self.user.email)
        self.assertTrue(
            auth.user_has_role(user, CourseInstructorRole(self.course.id)))
        self.assertFalse(CourseStaffRole(self.course.id).has_user(user))
Exemple #22
0
def _get_recipient_querysets(user_id, to_option, course_id, custom_to_addr):
    """
    Returns a list of query sets of email recipients corresponding to the
    requested `to_option` category.

    `to_option` is either SEND_TO_MYSELF, SEND_TO_STAFF, or SEND_TO_ALL.

    Recipients who are in more than one category (e.g. enrolled in the course
    and are staff or self) will be properly deduped.
    """
    if to_option not in TO_OPTIONS:
        log.error("Unexpected bulk email TO_OPTION found: %s", to_option)
        raise Exception("Unexpected bulk email TO_OPTION found: {0}".format(to_option))

    if to_option == SEND_TO_MYSELF:
        user = User.objects.filter(id=user_id)
        return [use_read_replica_if_available(user)]
    else:
        staff_qset = CourseStaffRole(course_id).users_with_role()
        instructor_qset = CourseInstructorRole(course_id).users_with_role()
        staff_instructor_qset = (staff_qset | instructor_qset).distinct()
        if to_option == SEND_TO_STAFF:
            return [use_read_replica_if_available(staff_instructor_qset)]

        if to_option == SEND_TO_ALL:
            # We also require students to have activated their accounts to
            # provide verification that the provided email address is valid.
            enrollment_qset = User.objects.filter(
                is_active=True,
                courseenrollment__course_id=course_id,
                courseenrollment__is_active=True
            )

            # to avoid duplicates, we only want to email unenrolled course staff
            # members here
            unenrolled_staff_qset = staff_instructor_qset.exclude(
                courseenrollment__course_id=course_id, courseenrollment__is_active=True
            )

            # use read_replica if available
            recipient_qsets = [
                use_read_replica_if_available(unenrolled_staff_qset),
                use_read_replica_if_available(enrollment_qset),
            ]
            return recipient_qsets

        if to_option == SEND_TO_CUSTOM:
            custom_to_addr = split_emails_or_throw_error(custom_to_addr)
            user = User.objects.filter(email__in=custom_to_addr)
            return [use_read_replica_if_available(user)]
Exemple #23
0
    def test_org_and_course_roles(self):
        """
        Test that Org and course roles don't interfere with course roles or vice versa
        """
        OrgInstructorRole(self.course_key.org).add_users(self.student)
        CourseInstructorRole(self.course_key).add_users(self.student)
        self.assertTrue(
            OrgInstructorRole(self.course_key.org).has_user(self.student),
            "Student doesn't have access to {}".format(unicode(self.course_key.org))
        )
        self.assertTrue(
            CourseInstructorRole(self.course_key).has_user(self.student),
            "Student doesn't have access to {}".format(unicode(self.course_key))
        )

        # remove access and confirm
        OrgInstructorRole(self.course_key.org).remove_users(self.student)
        self.assertFalse(
            OrgInstructorRole(self.course_key.org).has_user(self.student),
            "Student still has access to {}".format(self.course_key.org)
        )
        self.assertTrue(
            CourseInstructorRole(self.course_key).has_user(self.student),
            "Student doesn't have access to {}".format(unicode(self.course_key))
        )

        # ok now keep org role and get rid of course one
        OrgInstructorRole(self.course_key.org).add_users(self.student)
        CourseInstructorRole(self.course_key).remove_users(self.student)
        self.assertTrue(
            OrgInstructorRole(self.course_key.org).has_user(self.student),
            "Student lost has access to {}".format(self.course_key.org)
        )
        self.assertFalse(
            CourseInstructorRole(self.course_key).has_user(self.student),
            "Student doesn't have access to {}".format(unicode(self.course_key))
        )
Exemple #24
0
 def setUp(self):
     super().setUp()
     self.store = modulestore()
     # Create a modulestore course
     course = CourseFactory.create(modulestore=self.store,
                                   user_id=self.user.id)
     CourseInstructorRole(course.id).add_users(self.user)
     # Add a "Source from Library" block to the course
     self.source_block = ItemFactory.create(category="library_sourced",
                                            parent=course,
                                            parent_location=course.location,
                                            user_id=self.user.id,
                                            modulestore=self.store)
     self.submit_url = '/xblock/{0}/handler/submit_studio_edits'.format(
         self.source_block.scope_ids.usage_id)
    def test_remove_master_course_staff_from_ccx_no_email(self):
        """
        Test remove role of staff of master course on ccx course without
        sending enrollment email.
        """
        staff = self.make_staff()
        self.assertTrue(CourseStaffRole(self.course.id).has_user(staff))

        # adding instructor to master course.
        instructor = self.make_instructor()
        self.assertTrue(CourseInstructorRole(self.course.id).has_user(instructor))
        outbox = self.get_outbox()
        self.assertEqual(len(outbox), 0)
        remove_master_course_staff_from_ccx(self.course, self.ccx_locator, self.ccx.display_name, send_email=False)
        self.assertEqual(len(outbox), 0)
    def handle(self, *args, **options):
        "Execute the command"
        if len(args) != 2:
            raise CommandError("clone requires 2 arguments: <source-course_id> <dest-course_id>")

        source_course_id = self.course_key_from_arg(args[0])
        dest_course_id = self.course_key_from_arg(args[1])

        mstore = modulestore('direct')
        cstore = contentstore()

        mstore.ignore_write_events_on_courses.add(dest_course_id)

        print("Cloning course {0} to {1}".format(source_course_id, dest_course_id))

        if clone_course(mstore, cstore, source_course_id, dest_course_id):
            print("copying User permissions...")
            # purposely avoids auth.add_user b/c it doesn't have a caller to authorize
            CourseInstructorRole(dest_course_id).add_users(
                *CourseInstructorRole(source_course_id).users_with_role()
            )
            CourseStaffRole(dest_course_id).add_users(
                *CourseStaffRole(source_course_id).users_with_role()
            )
    def test_get_course_list_with_invalid_course_location(self, store):
        """
        Test getting courses with invalid course location (course deleted from modulestore).
        """
        with self.store.default_store(store):
            course_key = self.store.make_course_key('Org', 'Course', 'Run')
            self._create_course_with_access_groups(course_key, self.user, store)

        # get courses through iterating all courses
        courses_iter, __ = _accessible_courses_iter_for_tests(self.request)
        courses_list = list(courses_iter)
        self.assertEqual(len(courses_list), 1)

        courses_summary_iter, __ = _accessible_courses_summary_iter(self.request)
        courses_summary_list = list(courses_summary_iter)

        # Verify fetched accessible courses list is a list of CourseSummery instances and only one course
        # is returned
        self.assertTrue(all(isinstance(course, CourseSummary) for course in courses_summary_list))
        self.assertEqual(len(courses_summary_list), 1)

        # get courses by reversing group name formats
        courses_list_by_groups, __ = _accessible_courses_list_from_groups(self.request)
        self.assertEqual(len(courses_list_by_groups), 1)

        course_keys_in_course_list = [course.id for course in courses_list]
        course_keys_in_courses_list_by_groups = [course.id for course in courses_list_by_groups]
        # check course lists have same courses
        self.assertEqual(course_keys_in_course_list, course_keys_in_courses_list_by_groups)
        # now delete this course and re-add user to instructor group of this course
        delete_course(course_key, self.user.id)

        CourseInstructorRole(course_key).add_users(self.user)

        # Get courses through iterating all courses
        courses_iter, __ = _accessible_courses_iter_for_tests(self.request)

        # Get course summaries by iterating all courses
        courses_summary_iter, __ = _accessible_courses_summary_iter(self.request)

        # Get courses by reversing group name formats
        courses_list_by_groups, __ = _accessible_courses_list_from_groups(self.request)

        # Test that course list returns no course
        self.assertEqual(
            [len(list(courses_iter)), len(courses_list_by_groups), len(list(courses_summary_iter))],
            [0, 0, 0]
        )
Exemple #28
0
    def get(self, request):
        """Displays course Enrollment and staffing course statistics"""

        if not request.user.is_staff:
            raise Http404
        data = []

        courses = self.get_courses()

        for (cdir, course) in courses.items():  # pylint: disable=unused-variable
            datum = [course.display_name, course.id]
            datum += [
                CourseEnrollment.objects.filter(course_id=course.id).count()
            ]
            datum += [
                CourseStaffRole(course.location).users_with_role().count()
            ]
            datum += [
                ','.join([
                    x.username for x in CourseInstructorRole(
                        course.location).users_with_role()
                ])
            ]
            data.append(datum)

        datatable = dict(header=[
            _('Course Name'),
            _('course_id'),
            _('# enrolled'),
            _('# staff'),
            _('instructors')
        ],
                         title=_('Enrollment information for all courses'),
                         data=data)
        context = {
            'datatable':
            datatable,
            'msg':
            self.msg,
            'djangopid':
            os.getpid(),
            'modeflag': {
                'staffing': 'active-section'
            },
            'edx_platform_version':
            getattr(settings, 'EDX_PLATFORM_VERSION_STRING', ''),
        }
        return render_to_response(self.template_name, context)
Exemple #29
0
 def setUp(self):
     super(TestGradeUcursosView, self).setUp()
     self.grade_factory = CourseGradeFactory()
     with patch('student.models.cc.User.save'):
         # staff user
         self.client_instructor = Client()
         self.client_student = Client()
         self.client_anonymous = Client()
         self.user_instructor = UserFactory(
             username='******',
             password='******',
             email='*****@*****.**',
             is_staff=True)
         role = CourseInstructorRole(self.course.id)
         role.add_users(self.user_instructor)
         self.client_instructor.login(
             username='******', password='******')
         self.student = UserFactory(
             username='******',
             password='******',
             email='*****@*****.**')
         self.student_2 = UserFactory(
             username='******',
             password='******',
             email='*****@*****.**')
         # Enroll the student in the course
         CourseEnrollmentFactory(
             user=self.student, course_id=self.course.id, mode='honor')
         CourseEnrollmentFactory(
             user=self.student_2, course_id=self.course.id, mode='honor')
         self.client_student.login(
             username='******', password='******')
         # Create and Enroll data researcher user
         self.data_researcher_user = UserFactory(
             username='******',
             password='******',
             email='*****@*****.**')
         CourseEnrollmentFactory(
             user=self.data_researcher_user,
             course_id=self.course.id, mode='audit')
         CourseAccessRoleFactory(
             course_id=self.course.id,
             user=self.data_researcher_user,
             role='data_researcher',
             org=self.course.id.org
         )
         self.client_data_researcher = Client()
         self.assertTrue(self.client_data_researcher.login(username='******', password='******'))
Exemple #30
0
def get_user_role(user, course_id):
    """
    What type of access: staff or instructor does this user have in Studio?

    No code should use this for access control, only to quickly serialize the type of access
    where this code knows that Instructor trumps Staff and assumes the user has one or the other.

    This will not return student role because its purpose for using in Studio.

    :param course_id: the course_id of the course we're interested in
    """
    # afaik, this is only used in lti
    if auth.user_has_role(user, CourseInstructorRole(course_id)):
        return 'instructor'
    else:
        return 'staff'