def generate_certificate(request, course_id): user = request.user course_key = locator.CourseLocator.from_string(course_id) course = modulestore().get_course(course_key) course_name = course.display_name course_end_date = '' if course.end: course_end_date = str(course.end.date()) course_short_desc = get_course_about_section(course, 'short_description') instructor_name = '' role = CourseInstructorRole(course_key) if role.users_with_role(): instructor_user = role.users_with_role()[0] instructor_name = UserProfile.objects.get(user=instructor_user).name cert = EdraakCertificate(course_name=course_name, course_id=course_id, user_profile_name=user.profile.name, course_org=course.org, course_end_date=course_end_date, course_desc=course_short_desc, instructor=instructor_name) cert.generate_and_save() return cert.temp_file
def delete_course_and_groups(course_id, commit=False): """ This deletes the courseware associated with a course_id as well as cleaning update_item the various user table stuff (groups, permissions, etc.) """ module_store = modulestore('direct') content_store = contentstore() org, course_num, _ = course_id.split("/") module_store.ignore_write_events_on_courses.append('{0}/{1}'.format( org, course_num)) loc = CourseDescriptor.id_to_location(course_id) if delete_course(module_store, content_store, loc, commit): print 'removing forums permissions and roles...' unseed_permissions_roles(course_id) print 'removing User permissions from course....' # in the django layer, we need to remove all the user permissions groups associated with this course if commit: try: staff_role = CourseStaffRole(loc) staff_role.remove_users(*staff_role.users_with_role()) instructor_role = CourseInstructorRole(loc) instructor_role.remove_users( *instructor_role.users_with_role()) except Exception as err: log.error( "Error in deleting course groups for {0}: {1}".format( loc, err))
def delete_course_and_groups(course_id, commit=False): """ This deletes the courseware associated with a course_id as well as cleaning update_item the various user table stuff (groups, permissions, etc.) """ module_store = modulestore('direct') content_store = contentstore() course_id_dict = Location.parse_course_id(course_id) module_store.ignore_write_events_on_courses.append('{org}/{course}'.format(**course_id_dict)) loc = CourseDescriptor.id_to_location(course_id) if delete_course(module_store, content_store, loc, commit): print 'removing User permissions from course....' # in the django layer, we need to remove all the user permissions groups associated with this course if commit: try: staff_role = CourseStaffRole(loc) staff_role.remove_users(*staff_role.users_with_role()) instructor_role = CourseInstructorRole(loc) instructor_role.remove_users(*instructor_role.users_with_role()) except Exception as err: log.error("Error in deleting course groups for {0}: {1}".format(loc, err)) # remove location of this course from loc_mapper and cache loc_mapper().delete_course_mapping(loc)
def remove_all_instructors(course_key): """ Removes all instructor and staff users from the given course. """ staff_role = CourseStaffRole(course_key) staff_role.remove_users(*staff_role.users_with_role()) instructor_role = CourseInstructorRole(course_key) instructor_role.remove_users(*instructor_role.users_with_role())
def make_instructor(self): """ create staff instructor """ instructor = AdminFactory.create(password="******") role = CourseInstructorRole(self.course.id) role.add_users(instructor) return instructor
def remove_all_instructors(course_key): """ Removes given user as instructor and staff to the given course, after verifying that the requesting_user has permission to do so. """ staff_role = CourseStaffRole(course_key) staff_role.remove_users(*staff_role.users_with_role()) instructor_role = CourseInstructorRole(course_key) instructor_role.remove_users(*instructor_role.users_with_role())
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)
def test_filter_by_roles_course_staff(self): """ Verify that course_ids are filtered by the provided roles. """ # Make this user a course staff user for the course. course_staff_user = self.create_user(username='******', is_staff=False) add_users(self.global_admin, CourseStaffRole(self.course.id), course_staff_user) # Create a second course, along with an instructor user for it. alternate_course = self.create_course(org='test') course_instructor_user = self.create_user(username='******', is_staff=False) add_users(self.global_admin, CourseInstructorRole(alternate_course.id), course_instructor_user) # Requesting the courses for which the course staff user is staff should return *only* the single course. self.setup_user(self.staff_user) filtered_response = self.verify_response( params={ 'username': course_staff_user.username, 'role': 'staff' }) self.assertEqual(len(filtered_response.data['results']), 1) self.assertTrue(filtered_response.data['results'][0].startswith( self.course.org)) # The course staff user does *not* have the course instructor role on any courses. filtered_response = self.verify_response( params={ 'username': course_staff_user.username, 'role': 'instructor' }) self.assertEqual(len(filtered_response.data['results']), 0) # The course instructor user only has the course instructor role on one course. filtered_response = self.verify_response( params={ 'username': course_instructor_user.username, 'role': 'instructor' }) self.assertEqual(len(filtered_response.data['results']), 1) self.assertTrue(filtered_response.data['results'][0].startswith( alternate_course.org)) # The course instructor user has the inferred course staff role on one course. self.setup_user(course_instructor_user) filtered_response = self.verify_response( params={ 'username': course_instructor_user.username, 'role': 'staff' }) self.assertEqual(len(filtered_response.data['results']), 1) self.assertTrue(filtered_response.data['results'][0].startswith( alternate_course.org))
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(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) # check course lists have same courses self.assertEqual(courses_list, 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(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])
def setUp(self): super(TestCoachDashboardSchedule, self).setUp() self.course = course = CourseFactory.create() # Create a course outline self.mooc_start = start = datetime.datetime( 2010, 5, 12, 2, 42, tzinfo=pytz.UTC ) self.mooc_due = due = datetime.datetime( 2010, 7, 7, 0, 0, tzinfo=pytz.UTC ) self.chapters = [ ItemFactory.create(start=start, parent=course) for _ in xrange(2) ] self.sequentials = flatten([ [ ItemFactory.create(parent=chapter) for _ in xrange(2) ] for chapter in self.chapters ]) self.verticals = flatten([ [ ItemFactory.create( start=start, due=due, parent=sequential, graded=True, format='Homework', category=u'vertical' ) for _ in xrange(2) ] for sequential in self.sequentials ]) # Trying to wrap the whole thing in a bulk operation fails because it # doesn't find the parents. But we can at least wrap this part... with self.store.bulk_operations(course.id, emit_signals=False): blocks = flatten([ # pylint: disable=unused-variable [ ItemFactory.create(parent=vertical) for _ in xrange(2) ] for vertical in self.verticals ]) # Create instructor account self.coach = UserFactory.create() # create an instance of modulestore self.mstore = modulestore() # Login with the instructor account self.client.login(username=self.coach.username, password="******") # adding staff to master course. staff = UserFactory() allow_access(self.course, staff, 'staff') self.assertTrue(CourseStaffRole(self.course.id).has_user(staff)) # adding instructor to master course. instructor = UserFactory() allow_access(self.course, instructor, 'instructor') self.assertTrue(CourseInstructorRole(self.course.id).has_user(instructor)) self.assertTrue(modulestore().has_course(self.course.id))
def delete_course_and_groups(course_id, user_id): """ This deletes the courseware associated with a course_id as well as cleaning update_item the various user table stuff (groups, permissions, etc.) """ module_store = modulestore() with module_store.bulk_write_operations(course_id): module_store.delete_course(course_id, user_id) print 'removing User permissions from course....' # in the django layer, we need to remove all the user permissions groups associated with this course try: staff_role = CourseStaffRole(course_id) staff_role.remove_users(*staff_role.users_with_role()) instructor_role = CourseInstructorRole(course_id) instructor_role.remove_users(*instructor_role.users_with_role()) except Exception as err: log.error("Error in deleting course groups for {0}: {1}".format(course_id, err))
def _has_course_staff_privileges(user, course_key): """ Returns True if the user is an admin for the course, else returns False """ if user.is_staff: return True if CourseStaffRole(course_key).has_user(user) or CourseInstructorRole( course_key).has_user(user): return True return False
def setup_course_user_roles(self, course): """ get course staff and instructor roles user """ instructor = UserFactory() CourseInstructorRole(course.id).add_users(instructor) staff = UserFactory() CourseStaffRole(course.id).add_users(staff) return instructor, staff
def test_get_user_role_instructor(self): """ Verifies if user is instructor. """ add_users(self.global_admin, CourseInstructorRole(self.location), self.instructor) self.assertEqual( 'instructor', get_user_role(self.instructor, self.location, self.location.course_id))
def test_add_user_to_course_group(self): """ Tests adding user to course group (happy path). """ # Create groups for a new course (and assign instructor role to the creator). self.assertFalse(user_has_role(self.creator, CourseInstructorRole(self.course_key))) add_users(self.global_admin, CourseInstructorRole(self.course_key), self.creator) add_users(self.global_admin, CourseStaffRole(self.course_key), self.creator) self.assertTrue(user_has_role(self.creator, CourseInstructorRole(self.course_key))) # Add another user to the staff role. self.assertFalse(user_has_role(self.staff, CourseStaffRole(self.course_key))) add_users(self.creator, CourseStaffRole(self.course_key), self.staff) self.assertTrue(user_has_role(self.staff, CourseStaffRole(self.course_key))) # Add another user to the TA role self.assertFalse(user_has_role(self.assistant, CourseAssistantRole(self.course_key))) add_users(self.creator, CourseAssistantRole(self.course_key), self.assistant) self.assertTrue(user_has_role(self.assistant, CourseAssistantRole(self.course_key)))
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)
def test_request_instructor_courses_with_claims(self): CourseInstructorRole(self.course_key).add_users(self.user) values = ['edX/toy/TT_2012_Fall', self.course_id, 'invalid_course_id'] claims = self.get_with_claim_value('course_instructor', 'instructor_courses', values) self.assertEqual(len(claims), 2) courses = claims['instructor_courses'] self.assertIn(self.course_id, courses) self.assertEqual(len(courses), 1)
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.has_access(ext_user, CourseStaffRole(self.course.id))) self.assertFalse(auth.has_access(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.has_access(user, CourseInstructorRole(self.course.id))) self.assertFalse(CourseStaffRole(self.course.id).has_user(user))
def has_object_permission(self, request, view, obj): 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))
def test_get_all_users(self): """ Test getting all authors for a course where their permissions run the gamut of allowed group types. """ # first check the course creator.has explicit access (don't use has_access as is_staff # will trump the actual test) self.assertTrue( CourseInstructorRole(self.course_key).has_user(self.user), "Didn't add creator as instructor.") users = copy.copy(self.users) # doesn't use role.users_with_role b/c it's verifying the roles.py behavior user_by_role = {} # add the misc users to the course in different groups for role in [CourseInstructorRole, CourseStaffRole]: user_by_role[role] = [] # pylint: disable=protected-access group = role(self.course_key) # NOTE: this loop breaks the roles.py abstraction by purposely assigning # users to one of each possible groupname in order to test that has_course_access # and remove_user work user = users.pop() group.add_users(user) user_by_role[role].append(user) self.assertTrue(has_course_access(user, self.course_key), "{} does not have access".format(user)) course_team_url = reverse_course_url('course_team_handler', self.course_key) response = self.client.get_html(course_team_url) for role in [CourseInstructorRole, CourseStaffRole]: for user in user_by_role[role]: self.assertContains(response, user.email) # test copying course permissions copy_course_key = SlashSeparatedCourseKey('copyu', 'copydept.mycourse', 'myrun') for role in [CourseInstructorRole, CourseStaffRole]: auth.add_users(self.user, role(copy_course_key), *role(self.course_key).users_with_role()) # verify access in copy course and verify that removal from source course w/ the various # groupnames works for role in [CourseInstructorRole, CourseStaffRole]: for user in user_by_role[role]: # forcefully decache the groups: premise is that any real request will not have # multiple objects repr the same user but this test somehow uses different instance # in above add_users call if hasattr(user, '_roles'): del user._roles self.assertTrue(has_course_access(user, copy_course_key), "{} no copy access".format(user)) auth.remove_users(self.user, role(self.course_key), user) self.assertFalse(has_course_access(user, self.course_key), "{} remove didn't work".format(user))
def test_remove_user_from_course_group(self): """ Tests removing user from course group (happy path). """ add_users(self.global_admin, CourseInstructorRole(self.location), self.creator) add_users(self.global_admin, CourseStaffRole(self.location), self.creator) add_users(self.creator, CourseStaffRole(self.location), self.staff) self.assertTrue(has_access(self.staff, CourseStaffRole(self.location))) remove_users(self.creator, CourseStaffRole(self.location), self.staff) self.assertFalse(has_access(self.staff, CourseStaffRole(self.location))) remove_users(self.creator, CourseInstructorRole(self.location), self.creator) self.assertFalse( has_access(self.creator, CourseInstructorRole(self.location)))
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) with self.assertRaises(PermissionDenied): remove_users(self.assistant, CourseAssistantRole(self.course_key), another_staff)
def test_block_views(self): # Create a blockstore content library library = self._create_library(slug="testlib1_preview", title="Test Library 1", description="Testing XBlocks") # Add content to the library html_block_id = self._add_block_to_library( library["id"], "html", "html_student_preview")["id"] self._set_library_block_olx(html_block_id, '<html>Student Preview Test</html>') # 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 source_block = ItemFactory.create(category="library_sourced", parent=course, parent_location=course.location, user_id=self.user.id, modulestore=self.store) # Check if author_view for empty block renders using the editor template html = source_block.render(AUTHOR_VIEW).content loader = ResourceLoader('xmodule.library_sourced_block') expected_html = loader.render_django_template( 'templates/library-sourced-block-author-view.html', {'save_url': handler_url(source_block, 'submit_studio_edits')}) self.assertEqual(expected_html, html) submit_studio_edits_url = '/xblock/{0}/handler/submit_studio_edits'.format( source_block.scope_ids.usage_id) post_data = { "values": { "source_block_id": html_block_id }, "defaults": ["display_name"] } # Import the html block from the library to the course self.client.post(submit_studio_edits_url, data=post_data, format='json') # Check if author_view for a configured block renders the children correctly # Use self.get_block_view for rendering these as mako templates are mocked to return repr of the template # instead of the rendered html res = self.get_block_view(source_block, AUTHOR_VIEW) self.assertNotIn('library-sourced-block-author-view.html', res) self.assertIn('studio_render_children_view.html', res) self.assertIn('Student Preview Test', res) # Check if student_view renders the children correctly res = self.get_block_view(source_block, STUDENT_VIEW) self.assertIn('Student Preview Test', res)
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'
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'
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.has_access(ext_user, CourseStaffRole(self.course.id))) self.assertFalse(auth.has_access(ext_user, CourseInstructorRole(self.course.id))) self.assert_not_enrolled()
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_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.has_access(ext_user, CourseStaffRole(self.course.id))) self.assertFalse(auth.has_access(ext_user, CourseInstructorRole(self.course.id))) self.assert_enrolled()
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)
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() )
def delete_course_and_groups(course_id, commit=False): """ This deletes the courseware associated with a course_id as well as cleaning update_item the various user table stuff (groups, permissions, etc.) """ module_store = modulestore('direct') content_store = contentstore() module_store.ignore_write_events_on_courses.add(course_id) if delete_course(module_store, content_store, course_id, commit): print 'removing User permissions from course....' # in the django layer, we need to remove all the user permissions groups associated with this course if commit: try: staff_role = CourseStaffRole(course_id) staff_role.remove_users(*staff_role.users_with_role()) instructor_role = CourseInstructorRole(course_id) instructor_role.remove_users(*instructor_role.users_with_role()) except Exception as err: log.error("Error in deleting course groups for {0}: {1}".format(course_id, err))
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())
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.user_has_role(ext_user, CourseInstructorRole(self.course.id))) self.assertFalse(CourseStaffRole(self.course.id).has_user(ext_user)) self.assert_enrolled()
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
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))
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