Esempio n. 1
0
def account_type_required(account_type):
    """
    A decorator that can be applied to views to only allow access to users with
    certain account types.

    :param account_type: The account types that are allowed. May either be a
                         single string (meaning only one account type is
                         allowed) or a tuple, in which case any account type
                         within that tuple will be allowed access.

    """

    # We allow the user of this function to specify a string for account_type
    # signaling that only one type of user is allowed. The rest of the function
    # except account_type to be a tuple however, so convert it here.
    if isinstance(account_type, StringType):
        account_type = (account_type,)

    # Form a nicely formatted string that we will use to provide an error
    # message to the end-user if they try to access a restricted page.
    allowed = pretty_list(account_type, none_string="magical")

    def internal_decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if not current_user.is_authenticated() or current_user.account_type not in account_type:
                flash("Only %s users are permitted to access this page." % allowed, category="error")

                return current_app.login_manager.unauthorized()

            return func(*args, **kwargs)

        return decorated_view

    return internal_decorator
Esempio n. 2
0
def account_type_required(account_type):
    """
    A decorator that can be applied to views to only allow access to users with
    certain account types.

    :param account_type: The account types that are allowed. May either be a
                         single string (meaning only one account type is
                         allowed) or a tuple, in which case any account type
                         within that tuple will be allowed access.

    """

    # We allow the user of this function to specify a string for account_type
    # signaling that only one type of user is allowed. The rest of the function
    # except account_type to be a tuple however, so convert it here.
    if isinstance(account_type, StringType):
        account_type = (account_type, )

    # Form a nicely formatted string that we will use to provide an error
    # message to the end-user if they try to access a restricted page.
    allowed = pretty_list(account_type, none_string="magical")

    def internal_decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if not current_user.is_authenticated() or \
                    current_user.account_type not in account_type:
                flash("Only %s users are permitted to access this page." %
                      allowed,
                      category="error")

                return current_app.login_manager.unauthorized()

            return func(*args, **kwargs)

        return decorated_view

    return internal_decorator
Esempio n. 3
0
def upload_submission(assignment_id):
    # Figure out which assignment the user asked for.
    try:
        id = ObjectId(assignment_id)
        assignment = Assignment.objects.get(id = id)
    except (InvalidId, Assignment.DoesNotExist) as e:
        logger.info("Could not retrieve assignment: %s", str(e))

        abort(404)

    # Figure out where we should redirect the user to once we're done.
    redirect_to = request.args.get("next") or request.referrer

    if not is_url_on_site(app, redirect_to):
        # Default going back to the assignment screen
        redirect_to = url_for(
            "view_assignment",
            assignment_id = assignment_id
        )

    assignment.apply_personal_deadlines(current_user)

    # Check if the assignment's cutoff date has passed
    if assignment.due_cutoff and \
            assignment.due_cutoff < datetime.datetime.today():
        logger.info("Submission rejected, cutoff date has already passed.")

        flash(
            "The cutoff date has already passed, your submission was not "
            "accepted.", category = "error"
        )

        return redirect(redirect_to)

    form = SimpleArchiveForm()
    if not form.validate_on_submit():
        logger.info(
            "Submission rejected due to internal validation problem."
        )

        flash(
            "Submission rejected due to internal validation problem. Try "
            "again.", category = "error"
        )

        return redirect(redirect_to)

    if not [i for i in form.archive.entries if i.data.filename]:
        logger.info("Submission rejected. User did not submit any files.")

        flash("You did not submit any files.", category = "error")

        return redirect(redirect_to)

    new_submission = Submission(
        assignment = id,
        user = current_user.id,
        timestamp = datetime.datetime.now(),
        test_type = "final" if form.marked_as_final.data else "public",
        most_recent = True
    )
    new_submission.id = ObjectId()

    logger.info(str(new_submission.to_dict()))

    # Craft a unique directory path where we will store the new submission. We
    # are guarenteed an ObjectId is unique. However we are not guarenteed that
    # we will have the proper permissions and that we will be able to make the
    # directory thus this could error because of that.
    new_submission.testables = new_submission.getFilePath()
    os.makedirs(new_submission.testables)

    # Save each file the user uploaded into the submissions directory
    for i in form.archive.entries:
        if not i.data.filename:
            continue

        #  Figure out where we want to save the user's file
        file_path = os.path.join(
            new_submission.testables, secure_filename(i.data.filename)
        )

        # Do the actual saving
        i.data.save(file_path)

    new_submission.uploaded_filenames.extend(
        secure_filename(i.data.filename) for i in form.archive.entries
            if i.data.filename
    )

    logger.info(
        "Succesfully uploaded a new submission (id = %s) with files %s.",
        str(new_submission.id),
        str(new_submission.uploaded_filenames)
    )

    # The old "most_recent" submission is no longer the most recent.
    Submission.objects(
        user = current_user.email,
        assignment = id,
        most_recent = True
    ).update(
        multi = False,
        unset__most_recent = 1
    )

    if assignment.test_harness:
        new_submission.test_request_timestamp = datetime.datetime.now()
        logger.info("Sent test request to shepherd for %s" % \
                        str(new_submission.id))

    new_submission.save()

    # Tell shepherd to start running tests if there is a test_harness.
    if assignment.test_harness:
        send_test_request(config["PUBLIC_SOCKET"], new_submission.id)

    # Communicate to the next page what submission was just added.
    flash(str(new_submission.id), category = "new_submission")

    flash(
        "Successfully uploaded %s %s." %
            (
                plural_if("file", len(new_submission.uploaded_filenames)),
                pretty_list(new_submission.uploaded_filenames)
            ),
        category = "message"
    )

    # Everything seems to have gone well
    return redirect(redirect_to)
Esempio n. 4
0
        # Do the actual saving
        i.data.save(file_path)

    new_submission.uploaded_filenames.extend(
        secure_filename(i.data.filename) for i in form.archive.entries
        if i.data.filename)

    app.logger.debug(
        "%s succesfully uploaded a new submission (id = %s) with files %s.",
        current_user.email, str(new_submission.id),
        str(new_submission.uploaded_filenames))

    # The old "most_recent" submission is no longer the most recent.
    Submission.objects(assignment=id,
                       most_recent=True).update(multi=False,
                                                set__most_recent=False)

    new_submission.save()

    # Communicate to the next page what submission was just added.
    flash(new_submission.id, category="new_submission")

    flash("Successfully uploaded %s %s." %
          (plural_if("file", len(new_submission.uploaded_filenames)),
           pretty_list(new_submission.uploaded_filenames)),
          category="message")

    # Everything seems to have gone well
    return redirect(redirect_to)
Esempio n. 5
0
def upload_submission(assignment_id):
    # Figure out which assignment the user asked for.
    try:
        id = ObjectId(assignment_id)
        assignment = Assignment.objects.get(id=id)
    except (InvalidId, Assignment.DoesNotExist) as e:
        logger.info("Could not retrieve assignment: %s", str(e))

        abort(404)

    # Figure out where we should redirect the user to once we're done.
    redirect_to = request.args.get("next") or request.referrer

    if not is_url_on_site(app, redirect_to):
        # Default going back to the assignment screen
        redirect_to = url_for("view_assignment", assignment_id=assignment_id)

    assignment.apply_personal_deadlines(current_user)

    # Check if the assignment's cutoff date has passed
    if assignment.due_cutoff and \
            assignment.due_cutoff < datetime.datetime.today():
        logger.info("Submission rejected, cutoff date has already passed.")

        flash(
            "The cutoff date has already passed, your submission was not "
            "accepted.",
            category="error")

        return redirect(redirect_to)

    form = SimpleArchiveForm()
    if not form.validate_on_submit():
        logger.info("Submission rejected due to internal validation problem.")

        flash(
            "Submission rejected due to internal validation problem. Try "
            "again.",
            category="error")

        return redirect(redirect_to)

    if not [i for i in form.archive.entries if i.data.filename]:
        logger.info("Submission rejected. User did not submit any files.")

        flash("You did not submit any files.", category="error")

        return redirect(redirect_to)

    new_submission = Submission(
        assignment=id,
        user=current_user.id,
        timestamp=datetime.datetime.now(),
        test_type="final" if form.marked_as_final.data else "public",
        most_recent=True)
    new_submission.id = ObjectId()

    logger.info(str(new_submission.to_dict()))

    # Craft a unique directory path where we will store the new submission. We
    # are guarenteed an ObjectId is unique. However we are not guarenteed that
    # we will have the proper permissions and that we will be able to make the
    # directory thus this could error because of that.
    new_submission.testables = new_submission.getFilePath()
    os.makedirs(new_submission.testables)

    # Save each file the user uploaded into the submissions directory
    for i in form.archive.entries:
        if not i.data.filename:
            continue

        #  Figure out where we want to save the user's file
        file_path = os.path.join(new_submission.testables,
                                 secure_filename(i.data.filename))

        # Do the actual saving
        i.data.save(file_path)

    new_submission.uploaded_filenames.extend(
        secure_filename(i.data.filename) for i in form.archive.entries
        if i.data.filename)

    logger.info(
        "Succesfully uploaded a new submission (id = %s) with files %s.",
        str(new_submission.id), str(new_submission.uploaded_filenames))

    # The old "most_recent" submission is no longer the most recent.
    Submission.objects(user=current_user.email,
                       assignment=id,
                       most_recent=True).update(multi=False,
                                                unset__most_recent=1)

    if assignment.test_harness:
        new_submission.test_request_timestamp = datetime.datetime.now()
        logger.info("Sent test request to shepherd for %s" % \
                        str(new_submission.id))

    new_submission.save()

    # Tell shepherd to start running tests if there is a test_harness.
    if assignment.test_harness:
        send_test_request(config["PUBLIC_SOCKET"], new_submission.id)

    # Communicate to the next page what submission was just added.
    flash(str(new_submission.id), category="new_submission")

    flash("Successfully uploaded %s %s." %
          (plural_if("file", len(new_submission.uploaded_filenames)),
           pretty_list(new_submission.uploaded_filenames)),
          category="message")

    # Everything seems to have gone well
    return redirect(redirect_to)
Esempio n. 6
0
    app.logger.debug(
        "%s succesfully uploaded a new submission (id = %s) with files %s.",
        current_user.email,
        str(new_submission.id),
        str(new_submission.uploaded_filenames)
    )

    # The old "most_recent" submission is no longer the most recent.
    Submission.objects(assignment = id, most_recent = True).update(
        multi = False,
        set__most_recent = False
    )

    new_submission.save()
    
    # Communicate to the next page what submission was just added.
    flash(new_submission.id, category = "new_submission")

    flash(
        "Successfully uploaded %s %s." %
            (
                plural_if("file", len(new_submission.uploaded_filenames)),
                pretty_list(new_submission.uploaded_filenames)
            ),
        category = "message"
    )
    
    # Everything seems to have gone well
    return redirect(redirect_to)