def inject_current_user():
    user = get_current_user()
    if not user:
        custom_settings = json.loads(session.get("custom_settings", "{}"))
    else:
        custom_settings = user.get_custom_settings()

    return dict(current_user=get_current_user(),
                custom_settings=custom_settings)
Exemplo n.º 2
0
def view(course_slug, lesson_slug, segment_slug, institute=""):
    """
    Retrieves and displays a particular course, with the specified lesson
    and segment set to be active.
    """

    segment = datamodels.find_segment_by_slugs(course_slug, lesson_slug,
                                               segment_slug)
    if not segment:
        return abort(404)

    course = datamodels.get_course_by_slug(course_slug)
    lesson = datamodels.get_lesson_by_slugs(course_slug, lesson_slug)
    data = {
        "students":
        get_students_progress(lesson.course),
        "active_lesson":
        lesson,
        "active_segment":
        segment,
        "survey_individual_responses":
        get_survey_individual_responses(segment),
        "survey_response":
        get_survey_response_for_student(get_current_user(), segment, session),
        "course_progress":
        get_course_progress(lesson.course),
        "course":
        course,
        "form":
        AjaxCSRFTokenForm(),
    }
    return render_template("course.html", **data)
Exemplo n.º 3
0
def enroll(course_slug, institute=""):
    """
    Enroll a user into a course.
    """
    course = datamodels.get_course_by_slug(course_slug)
    if course is None:
        return abort(404)

    course_code = request.form.get("course_code", "")

    if (course.visibility == "code"
            and course_code.lower() != course.course_code.lower()):
        flash("Wrong course code")
        return redirect("/course/{}".format(course.slug))

    user = get_current_user()
    if course.guest_access and not user:  # Guest access for not log in user
        sess = session.get("enrollments", "[]")
        data = json.loads(sess)
        if course.id in data:
            return redirect(course.lessons[0].permalink)
        else:
            data.append(course.id)
            session["enrollments"] = json.dumps(data)
    elif not course.guest_access and not user:
        return redirect("/login")
    else:
        course.enroll(user)

    flash("You are now enrolled in {}".format(course.title))
    return redirect(course.lessons[0].permalink)
Exemplo n.º 4
0
def get_segment_object(segment_id):
    """ Returns a partial JSON dump of a Lesson Segment by ID. """

    current_user = get_current_user()

    ext = None
    if segment_id.endswith(".json"):
        ext = "json"
        segment_id = segment_id.split(".")[0]
    active_segment = datamodels.get_segment(segment_id)
    if active_segment is None:
        raise "Segment not found: %s".format(segment_id)

    course = active_segment.lesson.course
    barrier = find_segment_barrier(current_user, course)
    teaches_course = current_user.teaches(course) if current_user else False

    ordered_segments = list(
        course.get_ordered_segments(show_hidden=teaches_course))
    locked_segments = ([
        ordered_segments[i].id
        for i in range(ordered_segments.index(barrier), len(ordered_segments))
    ] if barrier else [])

    if not current_user:
        anon_progress = json.loads(session.get("anon_progress", "{}"))
    else:
        anon_progress = {}

    if active_segment.type == datamodels.SegmentType.text:
        html = render_template("partials/segments/_text.html",
                               active_segment=active_segment)
    elif active_segment.type == datamodels.SegmentType.survey:
        html = render_template(
            "partials/segments/survey/index.html",
            active_segment=active_segment,
            survey_response=get_survey_response_for_student(
                current_user, active_segment, session),
            survey_individual_responses=get_survey_individual_responses(
                active_segment),
            course=course,
        )
    else:
        html = ""

    data = {
        "active_segment": active_segment,
        "segment_type": active_segment.type.name,
        "locked": active_segment.locked(current_user, anon_progress),
        "barrier_id": barrier.id if barrier else None,
        "barrier_type": barrier.barrier.name if barrier else None,
        "locked_segments": locked_segments,
        "html": html,
    }
    if ext == "json":
        data["active_segment"] = {"external_id": active_segment.external_id}
        return json.dumps(data)
    return render_template("partials/course/_active_segment.html", **data)
Exemplo n.º 5
0
def code(institute=""):
    error = None
    if request.method == "POST":
        c = datamodels.get_course_by_code(request.form["course_code"])
        user = get_current_user()
        if c is None or c.draft and not (user and user.teaches(c)):
            error = "Course not found."
        else:
            return redirect(c.permalink)
    if request.method == "GET" or error:
        data = {"errors": [error], "form": LoginForm()}
        return render_template("code.html", **data)
Exemplo n.º 6
0
def view(resource_id, institute=""):
    """
    Proxy for resource links which logs access then redirects the user.
    """
    resource = datamodels.Resource.find_by_id(resource_id)
    if resource is None:
        abort(404)
    user = get_current_user()
    if user is not None:
        resource.log_user_view(user)
    else:
        resource.log_anonymous_view()
    return redirect(resource.url)
Exemplo n.º 7
0
def get_survey_stats(segment_id, institute=""):
    segment = datamodels.Segment.find_by_id(segment_id)

    if not segment or segment.type != datamodels.SegmentType.survey:
        return jsonify({"message": "No such survey."}), 400

    user = get_current_user()
    course = segment.lesson.course
    if not user.teaches(course):
        return jsonify(
            {"message": "You don't have permission to view this page."}), 403

    return jsonify(get_survey_statistics(segment))
Exemplo n.º 8
0
def view(slug, institute=""):
    """
    Retrieves and displays a course based on course slug.
    """

    course = datamodels.get_course_by_slug(slug)
    user = get_current_user()
    if course is None or course.draft and not (user and user.teaches(course)):
        return redirect("/404")
    elif course.draft and len(course.lessons) == 0:
        return redirect("/course/{}/edit".format(course.slug))
    return render_template(
        "course_intro.html",
        course=course,
        form=LoginForm(),
        number_of_resources=course.number_of_resources,
    )
Exemplo n.º 9
0
def submit_segment_survey(institute=""):
    """
    Handle submitting survey by a student.
    """
    segment_id = request.form.get("segment_id", 0)
    segment = datamodels.Segment.find_by_id(segment_id)

    if not segment or segment.type != datamodels.SegmentType.survey:
        return jsonify({"message": "No such survey."}), 400

    free_text = request.form.get("free_text", "")
    chosen_answer = request.form.get("question_id", "")

    survey_response = datamodels.SegmentSurveyResponse(survey=segment)
    user = get_current_user()

    try:
        survey_response_data = survey_response.validate_data(
            free_text=free_text, chosen_answer=chosen_answer)
    except ValueError as e:
        return jsonify({"message": str(e)}), 400

    if user:
        try:
            survey_response.save_response_for_user(user)
            segment.save_user_progress(user, 100)
        except ValueError:
            return jsonify(
                {"message": "You have already answered this question"}), 400
    else:
        data = get_session_data(session, "anon_surveys")
        data[segment_id] = survey_response_data
        set_session_data(session, "anon_surveys", data)

        data = get_session_data(session, "anon_progress")
        data[segment_id] = 100
        set_session_data(session, "anon_progress", data)
        db = datamodels.get_session()
        db.rollback()

    return jsonify({"message": "Survey response saved"})
Exemplo n.º 10
0
def set_user_setting(institute=""):
    form = CustomSettingForm(request.form)
    user = get_current_user()
    if form.validate():
        key = form.key.data
        value = form.value.data
        if key not in datamodels.CUSTOM_SETTINGS_KEYS:
            return jsonify({"message":
                            "There is no such setting available"}), 400
        if user:
            datamodels.CustomSetting.set_setting(key, value, user)
        else:
            custom_settings = get_session_data(session, "custom_settings")
            custom_settings[key] = value
            set_session_data(session, "custom_settings", custom_settings)
        return jsonify({"key": key, "value": value})
    else:
        if "csrf_token" in form.errors:
            msg = "CSRF token missing"
        else:
            msg = "Both key and value must be provided"
        return jsonify({"message": msg}), 400
Exemplo n.º 11
0
def get_user_settings(institute=""):
    user = get_current_user()
    if user:
        return jsonify(user.get_custom_settings())
    else:
        return get_session_data(session, "custom_settings")