Beispiel #1
0
def submit_essay(request, essay_id):
    # Check essay if valid
    essay = get_record_by_id(essay_id, Essay, check_school_id=False)
    if essay.lesson.school_id != g.user.school_id:
        raise UnauthorizedError()

    top_level_expected_keys = ["content"]
    json_data = json_from_request(request)
    check_keys(top_level_expected_keys, json_data)

    #  Validate lesson
    lesson = get_record_by_id(essay.lesson.id, Lesson)
    if g.user.id not in [t.id for t in lesson.students]:
        raise UnauthorizedError()

    submission = EssaySubmission(
        essay.id,
        g.user.id,
        datetime.datetime.now(),  #  TODO: Deal with timezones
        json_data['content'])

    db.session.add(submission)
    db.session.commit()

    return jsonify({'success': True}), 201
Beispiel #2
0
def subject_individual_view(subject_id):
    if request.method == 'GET':
        return subject_detail_view(request, subject_id=subject_id)
    if request.method == 'DELETE':
        if g.user.has_permissions({'Administrator'}):
            return subject_delete_view(request, subject_id)
        raise UnauthorizedError()
    if request.method == 'PUT':
        if g.user.has_permissions({'Administrator'}):
            return subject_update_view(request, subject_id)
        raise UnauthorizedError()
Beispiel #3
0
def lesson_detail_view(lesson_id):
    if request.method == 'GET':
        return lesson_detail(request, lesson_id=lesson_id)

    if request.method == 'PUT':
        if g.user.has_permissions({'Administrator'}):
            return lesson_update(request, lesson_id=lesson_id)
        raise UnauthorizedError()

    if request.method == 'DELETE':
        if g.user.has_permissions({'Administrator'}):
            return lesson_delete(request, lesson_id=lesson_id)
        raise UnauthorizedError()
Beispiel #4
0
def essay_detail(request, essay_id):
    # Check essay if valid
    essay = get_record_by_id(essay_id, Essay, check_school_id=False)
    if essay.lesson.school_id != g.user.school_id:
        raise UnauthorizedError()

    return jsonify({'success': True, 'essay': essay.to_dict()})
Beispiel #5
0
def lesson_list_or_create_view():
    if request.method == "POST":
        if g.user.has_permissions({'Administrator'}):
            return lesson_create(request)
        raise UnauthorizedError()
    if request.method == "GET":
        return lesson_listing(request)
Beispiel #6
0
def quiz_detail(request, quiz_id):
    # Check essay if valid
    quiz = get_record_by_id(quiz_id, Quiz, check_school_id=False)
    if quiz.lesson.school_id != g.user.school_id:
        raise UnauthorizedError()

    return jsonify({'success': True, 'quiz': quiz.to_dict()})
Beispiel #7
0
def comment_create_view(request):
    """Creates a Comment object from a HTTP request."""

    # Keys which need to in JSON from request
    top_level_expected_keys = [
        "submission_id",
        "text",
    ]

    # Get JSON from request and check keys are present
    json_data = json_from_request(request)
    check_keys(top_level_expected_keys, json_data)

    #  Fetch submission
    submission = get_record_by_id(json_data['submission_id'],
                                  Submission,
                                  check_school_id=False)

    # Check user teaches the lesson that submission they are commenting on
    if g.user.id not in [t.id for t in submission.homework.lesson.teachers]:
        raise UnauthorizedError()

    # Create comment
    comment = Comment(submission.id, json_data['text'], g.user.id)
    db.session.add(comment)
    db.session.commit()

    return jsonify({"success": True, "comment": comment.to_dict()}), 201
Beispiel #8
0
def comment_delete_view(request, comment_id):
    """Delete Comment based on id."""
    comment = get_record_by_id(comment_id, Comment, check_school_id=False)
    if comment.user.school_id != g.user.school_id:
        raise UnauthorizedError()
    db.session.delete(comment)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Deleted.'})
Beispiel #9
0
def comment_detail_view(request, comment_id):
    """Fetch Comment based on id from request."""
    comment = get_record_by_id(comment_id, Comment, check_school_id=False)
    if comment.user.school_id != g.user.school_id:
        raise UnauthorizedError()
    return jsonify({
        'success': True,
        'comment': comment.to_dict(nest_user=True)
    })
Beispiel #10
0
def view_quiz_submission(submission_id):
    if not (g.user.has_permissions({'Teacher'})
            or g.user.has_permissions({'Student'})):
        raise UnauthorizedError()

    submission = get_record_by_id(submission_id,
                                  QuizSubmission,
                                  check_school_id=False)
    if submission.homework.lesson.school_id != g.user.school_id:
        raise UnauthorizedError()

    return jsonify({
        'success':
        True,
        'submission':
        submission.to_dict(nest_user=True,
                           nest_homework=True,
                           nest_comments=True)
    })
Beispiel #11
0
def list_submissions(homework_id):
    homework = get_record_by_id(homework_id, Homework, check_school_id=False)
    if homework.lesson.school_id != g.user.school_id:
        raise UnauthorizedError()
    submissions = Submission.query.filter_by(homework_id=homework.id).all()
    return jsonify({
        'success':
        True,
        'submissions': [s.to_dict(nest_user=True) for s in submissions]
    })
Beispiel #12
0
        def decorated(*args, **kwargs):

            authorization = auth.get_auth()

            if request.method != 'OPTIONS':
                user_id = auth.authenticate(authorization, None)
                if not any(
                    [verify_auth_group(user_id, group) for group in groups]):
                    raise UnauthorizedError(scheme=auth.scheme,
                                            realm=auth.realm)

            return func(*args, **kwargs)
Beispiel #13
0
def get_role_by_id(role_id, custom_not_found_error=None):
    #  Check the role specified is in the correct school
    role = Role.query.filter_by(id=role_id).first()
    if role is None:
        if custom_not_found_error:
            raise custom_not_found_error

        raise NotFoundError()

    if role.school_id != g.user.school_id:
        raise UnauthorizedError()
    return role
Beispiel #14
0
def submit_quiz(request, quiz_id):
    # Check quiz is valid
    quiz = get_record_by_id(quiz_id, Quiz, check_school_id=False)
    if quiz.lesson.school_id != g.user.school_id:
        raise UnauthorizedError()

    json_data = json_from_request(request)
    expected_top_keys = ['answers']
    expected_inner_keys = ['question_id', 'answer']

    check_keys(expected_top_keys, json_data)

    #  Validate lesson
    lesson = get_record_by_id(quiz.lesson.id, Lesson)
    if g.user.id not in [t.id for t in lesson.students]:
        raise UnauthorizedError()

    question_ids = [question.id for question in quiz.questions]

    submission = QuizSubmission(
        homework_id=quiz.id,
        user_id=g.user.id,
        datetime_submitted=datetime.datetime.now()  # TODO: Deal with timezones
    )

    for answer in json_data['answers']:
        check_keys(expected_inner_keys, answer)
        question = get_record_by_id(answer['question_id'],
                                    Question,
                                    check_school_id=False)
        if question.id not in question_ids:
            raise UnauthorizedError()

        answer = QuizAnswer(answer['answer'], submission.id, question.id)
        submission.answers.append(answer)

    submission.mark()
    db.session.add(submission)
    db.session.commit()
    return jsonify({'score': submission.total_score})
Beispiel #15
0
def create_quiz(request):
    top_level_expected_keys = [
        "lesson_id", "title", "description", "date_due", "questions"
    ]
    json_data = json_from_request(request)
    check_keys(top_level_expected_keys, json_data)

    # Validate lesson
    lesson = get_record_by_id(json_data['lesson_id'], Lesson)
    if g.user.id not in [t.id for t in lesson.teachers]:
        raise UnauthorizedError()

    # Validate date
    date_due_string = json_data['date_due']
    try:
        date_due = datetime.datetime.strptime(date_due_string,
                                              "%d/%m/%Y").date()
    except ValueError:
        raise CustomError(409,
                          message="Invalid date_due: {}.".format(
                              json_data['date_due']))

    quiz = Quiz(lesson_id=json_data['lesson_id'],
                title=json_data['title'],
                description=json_data['description'],
                date_due=date_due,
                number_of_questions=len(json_data['questions']))

    db.session.add(quiz)
    db.session.commit()

    for question_object in json_data['questions']:
        if 'answer' and 'question_text' not in question_object.keys():
            raise CustomError(
                409,
                message=
                "Invalid object in questions array. Make sure it has a question and a answer."
            )
        question = Question(quiz.id, question_object['question_text'],
                            question_object['answer'])
        db.session.add(question)
        quiz.questions.append(question)

    db.session.add(quiz)
    db.session.commit()
    return jsonify(quiz.to_dict()), 201
Beispiel #16
0
def comment_update_view(request, comment_id):
    """Update Comment based on id."""
    # Get comment
    comment = get_record_by_id(comment_id, Comment)

    # Validate that user has permission
    if comment.user_id != g.user.id:
        raise UnauthorizedError()

    # Get JSON data
    data = json_from_request(request)

    # If text in data, then update the text
    if 'text' in data.keys():
        comment.name = data['text']

    db.session.add(comment)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Updated.'})
Beispiel #17
0
def create_essay(request):
    """Function to create an essay from request."""
    # List of keys needed to create an Essay
    top_level_expected_keys = [
        "lesson_id",
        "title",
        "description",
        "date_due",
    ]

    # Extract JSON from request and check keys are present
    json_data = json_from_request(request)
    check_keys(top_level_expected_keys, json_data)

    # Validate lesson
    lesson = get_record_by_id(json_data['lesson_id'], Lesson)
    if g.user.id not in [t.id for t in lesson.teachers]:
        raise UnauthorizedError()

    # Validate date
    date_due_string = json_data['date_due']
    try:
        date_due = datetime.datetime.strptime(date_due_string,
                                              "%d/%m/%Y").date()
    except ValueError:
        raise CustomError(409,
                          message="Invalid date_due: {}.".format(
                              json_data['date_due']))

    # Create Essay
    essay = Essay(
        lesson_id=json_data['lesson_id'],
        title=json_data['title'],
        description=json_data['description'],
        date_due=date_due,
    )

    db.session.add(essay)
    db.session.commit()

    return jsonify(essay.to_dict()), 201