def add_to_section(request):
    try:
        canvas_course_id = request.LTI['custom_canvas_course_id']
        post_data = json.loads(request.body)
        section_id = post_data['section_id']
        users_to_add = post_data['users_to_add']
    except KeyError:
        message = "Missing post parameters to add users to section_id %s" % request.body
        logger.exception(message)
        return JsonResponse({'success': False, 'message': message}, status=500)

    failed_users = []
    for user in users_to_add:
        try:
            canvas_api_enrollments.enroll_user_sections(
                SDK_CONTEXT,
                section_id,
                user['enrollment_user_id'],
                enrollment_type=user['enrollment_type'],
                enrollment_role_id=user['enrollment_role_id'],
                enrollment_enrollment_state='active'
            )
        except (KeyError, CanvasAPIError):
            logger.exception("Failed to add user to section %s %s", section_id, json.dumps(user))
            failed_users.append(user)
    canvas_api_helper_courses.delete_cache(canvas_course_id=canvas_course_id)
    canvas_api_helper_enrollments.delete_cache(canvas_course_id)
    canvas_api_helper_sections.delete_cache(canvas_course_id)
    canvas_api_helper_sections.delete_section_cache(section_id)

    return JsonResponse({
        'added': len(users_to_add) - len(failed_users),
        'failed': failed_users
    })
Exemplo n.º 2
0
def add_to_section(request):
    try:
        canvas_course_id = request.LTI['custom_canvas_course_id']
        post_data = json.loads(request.body)
        section_id = post_data['section_id']
        users_to_add = post_data['users_to_add']
    except KeyError:
        message = "Missing post parameters to add users to section_id %s" % request.body
        logger.exception(message)
        return JsonResponse({'success': False, 'message': message}, status=500)

    failed_users = []
    for user in users_to_add:
        try:
            canvas_api_enrollments.enroll_user_sections(
                SDK_CONTEXT,
                section_id,
                user['enrollment_user_id'],
                enrollment_type=user['enrollment_type'],
                enrollment_role_id=user['enrollment_role_id'],
                enrollment_enrollment_state='active'
            )
        except (KeyError, CanvasAPIError):
            logger.exception("Failed to add user to section %s %s", section_id, json.dumps(user))
            failed_users.append(user)
    canvas_api_helper_courses.delete_cache(canvas_course_id=canvas_course_id)
    canvas_api_helper_enrollments.delete_cache(canvas_course_id)
    canvas_api_helper_sections.delete_cache(canvas_course_id)
    canvas_api_helper_sections.delete_section_cache(section_id)

    return JsonResponse({
        'added': len(users_to_add) - len(failed_users),
        'failed': failed_users
    })
def enroll_creator_in_new_course(sis_course_id, user_id):
    """
    Silently enroll instructor / creator to the new course so it can be accessed immediately

        :param sis_course_id: newly created Canvas course's SIS course ID to enroll course creator
        :type sis_course_id: string
        :param user_id: The user ID of the creator/instructor to enroll in the course
        :type user_id: string - Canvas user ID or SIS user ID prefixed with 'sis_user_id:'
        :return: Canvas enrollment information (response of enrollment request)
        :rtype: json-encoded content of response
        :raises: NoCanvasUserToEnroll
    """

    # check if user exists in Canvas before enrolling
    logger.debug("Checking for user_id=%s" % user_id)

    get_user_response = get_user_profile(request_ctx=SDK_CONTEXT, user_id=user_id)

    logger.debug("--> response: %s" % get_user_response.json())

    if get_user_response.status_code == 200:
        # user was found; we may have found user using sis_user_id, so make sure we note canvas_user_id from response
        user_data = get_user_response.json()
        canvas_user_id = str(user_data['id'])
        sis_user_id = str(user_data['sis_user_id'])
    else:
        # Could not find user matching sis_user_id
        logger.debug("No user found with user_id=%s" % user_id)
        raise NoCanvasUserToEnroll(user_id)

    # Assumptions:
    # 1. the course creator should be enrolled in a section with sis_section_id equal to the SIS course ID
    # 2. the course creator should be enrolled according to the the registrar's feed recorded in CourseManger.
    #  default to Teacher if a role is not found

    enrollment_type = 'TeacherEnrollment'

    # Check for the specific  role from the course staff table
    try:
        user_staff_record = CourseStaff.objects.get(
            course_instance_id=sis_course_id,
            user_id=sis_user_id)
        role_id = user_staff_record.role_id
        logger.debug('CourseStaff role_id =%s' % role_id)

        # Fetch the canvas role information from user role table.
        enrollment_role_record = UserRole.objects.get(role_id=role_id)
        enrollment_role = enrollment_role_record.canvas_role
        logger.info('Attempting to add user to course with role=%s ' % enrollment_role)

        current_user_enrollment_result = enroll_user_sections(request_ctx=SDK_CONTEXT,
                                                              section_id='sis_section_id:%s' % sis_course_id,
                                                              enrollment_user_id=canvas_user_id,
                                                              enrollment_type=enrollment_type,
                                                              enrollment_role=enrollment_role,
                                                              enrollment_enrollment_state='active')

    except Exception as exception:
        logger.exception('Exception in getting custom role information for '
                         'sis_course_id=%s and user_id=%s' % (sis_course_id, sis_user_id))

        # If there is a failure in fetching role information, default to adding the user as Teacher
        current_user_enrollment_result = enroll_user_sections(request_ctx=SDK_CONTEXT,
                                                              section_id='sis_section_id:%s' % sis_course_id,
                                                              enrollment_user_id=canvas_user_id,
                                                              enrollment_type=enrollment_type,
                                                              enrollment_enrollment_state='active')

    logger.debug("Enroll user response: %s" % current_user_enrollment_result.json())
    return current_user_enrollment_result.json()
def enroll_creator_in_new_course(sis_course_id, user_id):
    """
    Silently enroll instructor / creator to the new course so it can be accessed immediately

        :param sis_course_id: newly created Canvas course's SIS course ID to enroll course creator
        :type sis_course_id: string
        :param user_id: The user ID of the creator/instructor to enroll in the course
        :type user_id: string - Canvas user ID or SIS user ID prefixed with 'sis_user_id:'
        :return: Canvas enrollment information (response of enrollment request)
        :rtype: json-encoded content of response
        :raises: NoCanvasUserToEnroll
    """

    # check if user exists in Canvas before enrolling
    logger.debug("Checking for user_id=%s" % user_id)

    get_user_response = get_user_profile(request_ctx=SDK_CONTEXT, user_id=user_id)

    logger.debug("--> response: %s" % get_user_response.json())

    if get_user_response.status_code == 200:
        # user was found; we may have found user using sis_user_id, so make sure we note canvas_user_id from response
        user_data = get_user_response.json()
        canvas_user_id = str(user_data['id'])
        sis_user_id = str(user_data['sis_user_id'])
    else:
        # Could not find user matching sis_user_id
        logger.debug("No user found with user_id=%s" % user_id)
        raise NoCanvasUserToEnroll(user_id)

    # Assumptions:
    # 1. the course creator should be enrolled in a section with sis_section_id equal to the SIS course ID
    # 2. the course creator should be enrolled according to the the registrar's feed recorded in CourseManger.
    #  default to Teacher if a role is not found

    enrollment_type = 'TeacherEnrollment'

    # Check for the specific  role from the course staff table
    try:
        user_staff_record = CourseStaff.objects.get(
            course_instance_id=sis_course_id,
            user_id=sis_user_id)
        role_id = user_staff_record.role_id
        logger.debug('CourseStaff role_id =%s' % role_id)

        # Fetch the canvas role information from user role table.
        enrollment_role_record = UserRole.objects.get(role_id=role_id)
        enrollment_role = enrollment_role_record.canvas_role
        logger.info('Attempting to add user to course with role=%s ' % enrollment_role)

        current_user_enrollment_result = enroll_user_sections(request_ctx=SDK_CONTEXT,
                                                              section_id='sis_section_id:%s' % sis_course_id,
                                                              enrollment_user_id=canvas_user_id,
                                                              enrollment_type=enrollment_type,
                                                              enrollment_role=enrollment_role,
                                                              enrollment_enrollment_state='active')

    except Exception as exception:
        logger.exception('Exception in getting custom role information for '
                         'sis_course_id=%s and user_id=%s' % (sis_course_id, sis_user_id))

        # If there is a failure in fetching role information, default to adding the user as Teacher
        current_user_enrollment_result = enroll_user_sections(request_ctx=SDK_CONTEXT,
                                                              section_id='sis_section_id:%s' % sis_course_id,
                                                              enrollment_user_id=canvas_user_id,
                                                              enrollment_type=enrollment_type,
                                                              enrollment_enrollment_state='active')

    logger.debug("Enroll user response: %s" % current_user_enrollment_result.json())
    return current_user_enrollment_result.json()