Ejemplo n.º 1
0
def submit_essay(request, essay_id):
    # Check essay if valid
    essay = get_record_by_id(essay_id, Essay, check_school_id=False)

    # Validate lesson
    resp = services.lesson.get("lessons/lesson/{}".format(essay.lesson_id),
                               headers=g.user.headers_dict(),
                               params={'nest-students': True})

    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if 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)

    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
Ejemplo n.º 2
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)
    # Validate lesson
    resp = services.lesson.get("lessons/lesson/{}".format(
        submission.homework.lesson_id),
                               headers=g.user.headers_dict(),
                               params={'nest-students': True})

    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if 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)
    })
Ejemplo n.º 3
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()
Ejemplo n.º 4
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()
Ejemplo n.º 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)
Ejemplo n.º 6
0
def submit_quiz(request, quiz_id):
    # Check quiz is valid
    quiz = get_record_by_id(quiz_id, Quiz, check_school_id=False)
    #  Validate lesson
    resp = services.lesson.get("lessons/lesson/{}".format(quiz.lesson_id),
                               headers=g.user.headers_dict(),
                               params={'nest-students': True})
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if 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)

    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})
Ejemplo n.º 7
0
def user_listing_or_create_view():
    """Route to create User from a POST request."""
    if request.method == "GET":
        return user_listing(request)

    if request.method == "POST":
        if g.user.has_permissions({'Administrator'}):
            return user_create(request)
        raise UnauthorizedError()
Ejemplo n.º 8
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
    resp = services.lesson.get("lessons/lesson/{}".format(
        json_data['lesson_id']),
                               headers=g.user.headers_dict(),
                               params={'nest-teachers': True})
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['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
Ejemplo n.º 9
0
def get_user_by_id(user_id, custom_not_found_error=None):
    # Check user specified is in the correct school
    user = User.query.filter_by(id=user_id).first()
    if user is None:
        if custom_not_found_error:
            raise custom_not_found_error

        raise NotFoundError()
    if user.school_id != g.user.school_id:
        raise UnauthorizedError()

    return user
Ejemplo n.º 10
0
def list_submissions(homework_id):
    homework = get_record_by_id(homework_id, Homework, check_school_id=False)

    resp = services.lesson.get('lessons/lesson/{}'.format(homework.lesson_id), headers=g.user.headers_dict())
    if resp.status_code != 200:
        raise CustomError(
            **resp.json()
        )

    if resp.json()['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]})
Ejemplo n.º 11
0
def get_permission_by_id(permission_id, custom_not_found_error=None):
    # Check permission exists
    permission = Permission.query.filter_by(id=permission_id).first()

    if permission is None:
        if custom_not_found_error is not None:
            raise custom_not_found_error

        raise NotFoundError()

    #  Check permission in correct school
    if permission.school_id != g.user.school_id:
        raise UnauthorizedError()
    return permission
Ejemplo n.º 12
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
    resp = services.lesson.get("lessons/lesson/{}".format(
        json_data['lesson_id']),
                               headers=g.user.headers_dict(),
                               params={'nest-teachers': True})
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['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
Ejemplo n.º 13
0
def quiz_detail(request, quiz_id):
    # Check quiz if valid
    quiz = get_record_by_id(quiz_id, Quiz, check_school_id=False)

    resp = services.lesson.get(
        "lessons/lesson/{}".format(quiz.lesson_id),
        headers=g.user.headers_dict(),
    )
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if lesson['school_id'] != g.user.school_id:
        raise UnauthorizedError()

    return jsonify({'success': True, 'quiz': quiz.to_dict()})
Ejemplo n.º 14
0
def essay_detail(request, essay_id):
    # Check essay if valid
    essay = get_record_by_id(essay_id, Essay, check_school_id=False)

    resp = services.lesson.get(
        "lessons/lesson/{}".format(essay.lesson_id),
        headers=g.user.headers_dict(),
    )
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if lesson['school_id'] != g.user.school_id:
        raise UnauthorizedError()

    return jsonify({'success': True, 'essay': essay.to_dict()})
Ejemplo n.º 15
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.'})
Ejemplo n.º 16
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)

    # Check user teaches the lesson that submission they are commenting on
    resp = services.lesson.get(
        "lessons/lesson/{}".format(comment.submission.homework.lesson_id),
        headers=g.user.headers_dict(),
    )
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if g.user.id != lesson['school_id']:
        raise UnauthorizedError()

    db.session.delete(comment)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Deleted.'})
Ejemplo n.º 17
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)

    # Check user teaches the lesson that submission they are commenting on
    resp = services.lesson.get(
        "lessons/lesson/{}".format(comment.submission.homework.lesson_id),
        headers=g.user.headers_dict(),
    )
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if g.user.id != lesson['school_id']:
        raise UnauthorizedError()

    return jsonify({
        'success': True,
        'comment': comment.to_dict(nest_user=True)
    })
Ejemplo n.º 18
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
    resp = services.lesson.get("lessons/lesson/{}".format(
        submission.homework.lesson_id),
                               headers=g.user.headers_dict(),
                               params={'nest-teachers': True})
    if resp.status_code != 200:
        raise CustomError(**resp.json())

    lesson = resp.json()['lesson']

    if g.user.id not in [t['id'] for t in 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