示例#1
0
def remove_role(request):
    data = json_from_request(request)

    expected_keys = ["user_id", "role_id"]
    check_keys(expected_keys, data)

    user = get_user_by_id(data['user_id'],
                          custom_not_found_error=CustomError(
                              409, message="Invalid user_id."))

    role = get_role_by_id(data['role_id'],
                          custom_not_found_error=CustomError(
                              409, message="Invalid role_id."))

    #  Check the user has the role
    if data['role_id'] not in [r.id for r in user.roles]:
        raise CustomError(
            409,
            message="User with id: {} does not have role with id: {}".format(
                data['user_id'], data['role_id']))

    user.roles.remove(role)

    db.session.add(user)
    db.session.commit()

    # Return success status
    return jsonify({'success': True}), 200
示例#2
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
示例#3
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
示例#4
0
def remove_permission(request):
    data = json_from_request(request)

    expected_keys = ["user_id"]
    check_keys(expected_keys, data)

    if "permission_id" not in data.keys() and "all" not in data.keys():
        raise MissingKeyError("permission_id or all")

    # Check user specified is in the correct school
    user = get_record_by_id(data['user_id'], User, CustomError(409, message="Invalid user_id."))

    if "all" in data.keys() and data['all'] is True:
        user.permissions = []
    else:
        #  Check the permission specified is in the correct school
        permission = get_permission_by_id(data['permission_id'], CustomError(409, message="Invalid permission_id."))

        #  Check the user has the permission
        if permission.id not in [p.id for p in user.permissions]:
            raise CustomError(
                409,
                message="User with id: {} does not have permission with id: {}".format(data['user_id'],
                                                                                       data['permission_id'])
            )

        user.permissions.remove(permission)

    db.session.add(user)
    db.session.commit()

    # Return success status
    return jsonify({'success': True}), 200
示例#5
0
def role_create(request):
    # Create a new role
    data = json_from_request(request)

    expected_keys = ["name", "permissions"]
    check_keys(expected_keys, data)

    #  Check name not in use
    if Role.query.filter_by(name=data['name'],
                            school_id=g.user.school_id).first() is not None:
        raise FieldInUseError("name")

    # Check all permissions are valid
    permissions = Permission.query.filter(
        Permission.id.in_(data['permissions']),
        Permission.school_id == g.user.school_id)

    if permissions.count() != len(data['permissions']):
        raise CustomError(409, message="Invalid Permission.")

    role = Role(name=data['name'], school_id=g.user.school_id)
    [role.permissions.append(p) for p in permissions]
    db.session.add(role)
    db.session.commit()

    return jsonify({'success': True, 'role': role.to_dict()}), 201
示例#6
0
def grant_role(request):
    data = json_from_request(request)

    expected_keys = ["user_id", "role_id"]
    check_keys(expected_keys, data)

    user = get_user_by_id(data['user_id'],
                          custom_not_found_error=CustomError(
                              409, message="Invalid user_id"))

    role = get_role_by_id(data['role_id'],
                          custom_not_found_error=CustomError(
                              409, message="Invalid role_id"))

    # Check that the user does not have the permission
    for inner_role in user.roles:
        if inner_role.id == data['role_id']:
            raise CustomError(
                409,
                message="User with id: {} already has role with id: {}".format(
                    data['user_id'], data['role_id']))

    user.roles.append(role)

    db.session.add(user)
    db.session.commit()

    # Return success status
    return jsonify({'success': True}), 201
示例#7
0
def create_subject_view(request):
    data = json_from_request(request)
    expected_keys = ["name"]
    check_keys(expected_keys, data)

    subject = create_subject(data['name'], g.user.school_id)

    return jsonify({'success': True, 'subject': subject.to_dict()}), 201
示例#8
0
def signup_school(request):
    # Fetch JSON data from request
    data = json_from_request(request)

    # List of keys we expect to see in JSON
    expected_keys = [
        "school_name", "first_name", "last_name", "password", "username",
        "email"
    ]

    # Checks keys are present in JSON and throws error if not which is automatically caught and converted into a error message
    check_keys(expected_keys, data)

    # Checks values for keys are not blank
    check_values_not_blank(expected_keys, data)

    # Create school object with user's data
    school = School(school_name=data['school_name'])

    # Add school to db
    db.session.add(school)
    db.session.commit()

    # Create user
    # Check email not already in use
    if User.query.filter_by(email=data['email']).first() is not None:
        raise FieldInUseError("email")

    # Check username is not already in use
    if User.query.filter_by(username=data['username']).first() is not None:
        raise FieldInUseError("username")

    # Create user
    user = User(first_name=data['first_name'],
                last_name=data['last_name'],
                email=data['email'],
                password=data['password'],
                username=data['username'],
                school_id=school.id)

    # Add user to db
    db.session.add(user)
    db.session.commit()

    # Create permissions
    for permission in Permission.default_permissions(school.id):
        db.session.add(permission)
    db.session.commit()

    #  Assign user to admin permissions
    permission = Permission.query.filter_by(name="Administrator",
                                            school_id=school.id).first()
    user.permissions.append(permission)
    db.session.add(user)
    db.session.commit()

    # Return success message as JSON
    return jsonify({'success': True})
示例#9
0
def create_form(request):
    expected_keys = ["name"]
    data = json_from_request(request)
    check_keys(expected_keys, data)

    #  Validate name
    if Form.query.filter_by(name=data['name']).first() is not None:
        raise FieldInUseError("name")

    form = Form(name=data['name'], school_id=g.user.school_id)
    db.session.add(form)
    db.session.commit()
    return jsonify({'success': True, 'form': form.to_dict()}), 201
示例#10
0
def permission_create(request):
    """Create a Permission from a POST request."""
    data = json_from_request(request)
    expected_keys = ["name", "description"]
    check_keys(expected_keys, data)

    # Check name not in use by school
    if Permission.query.filter_by(name=data['name'], school_id=g.user.school_id).first() is not None:
        raise FieldInUseError("name")

    permission = Permission(name=data['name'], description=data['description'], school_id=g.user.school_id)
    db.session.add(permission)
    db.session.commit()

    return jsonify({'success': True, 'permission': permission.to_dict()}), 201
示例#11
0
def create_week(request):
    expected_keys = [
        'name'
    ]
    json_data = json_from_request(request)
    check_keys(expected_keys, json_data)

    week = Week(
        name=json_data['name'],
        school_id=g.user.school_id
    )

    db.session.add(week)
    db.session.commit()

    return jsonify(week.to_dict()), 201
示例#12
0
def create_school(request):
    # This may not longer be needed and should be removed
    data = json_from_request(request)

    expected_keys = ["name"]
    check_keys(expected_keys, data)

    if School.query.filter_by(name=data['name']).first() is not None:
        raise FieldInUseError("name")

    school = School(school_name=data['name'])

    db.session.add(school)
    db.session.commit()

    return jsonify({'success': True, 'school': school.to_dict()}), 201
示例#13
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
示例#14
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
示例#15
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})
示例#16
0
def lesson_create(request):
    # Parse JSON from request
    data = json_from_request(request)

    # Check JSON has keys needed
    expected_keys = ['name', 'subject_id']
    check_keys(expected_keys=expected_keys, data=data)

    # Validate subject_id
    subject = get_record_by_id(data['subject_id'],
                               Subject,
                               custom_not_found_error=CustomError(
                                   409, message="Invalid subject_id."))

    # Validate name
    validate_lesson_name(data['name'], g.user.school_id)

    # Create lesson
    lesson = Lesson(name=data['name'],
                    school_id=g.user.school_id,
                    subject_id=subject.id)

    # Add teachers (if supplied)
    if 'teacher_ids' in data.keys():
        add_teachers(data['teacher_ids'], lesson)

    # Add students (if supplied)
    if 'student_ids' in data.keys():
        add_students(data['student_ids'], lesson)

    db.session.add(lesson)
    db.session.commit()

    return jsonify({
        'success':
        True,
        'lesson':
        lesson.to_dict(nest_teachers=True, nest_students=True)
    }), 201
示例#17
0
def user_create(request):
    #  Decode the JSON data
    data = json_from_request(request)

    # Validate data
    expected_keys = [
        "first_name", "last_name", "password", "username", "email"
    ]
    check_keys(expected_keys, data)
    check_values_not_blank(expected_keys, data)

    if User.query.filter_by(email=data['email']).first() is not None:
        raise FieldInUseError("email")

    if User.query.filter_by(username=data['username'],
                            school_id=g.user.school_id).first() is not None:
        raise FieldInUseError("username")

    # Create user
    user = User(first_name=data['first_name'],
                last_name=data['last_name'],
                email=data['email'],
                password=data['password'],
                username=data['username'],
                school_id=g.user.school_id)

    if "form_id" in data.keys():
        # Validate form id
        form = get_record_by_id(data["form_id"],
                                Form,
                                custom_not_found_error=CustomError(
                                    409, message="Invalid form_id."))
        user.form_id = form.id

    db.session.add(user)
    db.session.commit()

    return jsonify({"success": True, "user": user.to_dict()}), 201
示例#18
0
def grant_permission(request):
    data = json_from_request(request)

    expected_keys = ["user_id", "permission_id"]
    check_keys(expected_keys, data)

    # Check user specified is in the correct school
    user = get_record_by_id(data['user_id'], User, CustomError(409, message="Invalid user_id."))

    #  Check the permission specified is in the correct school
    permission = get_permission_by_id(data['permission_id'], CustomError(409, message="Invalid permission_id."))

    # Check user does not have the permission
    for p in user.permissions:
        if p.id == data['permission_id']:
            raise CustomError(409, message="User with id: {} already has permission with id: {}".format(
                data['user_id'], data['permission_id']))

    user.permissions.append(permission)
    db.session.add(user)
    db.session.commit()

    # Return success status
    return jsonify({'success': True}), 201