Beispiel #1
0
def password():
    "Set the password for a user account, and login user."
    if utils.http_GET():
        return flask.render_template(
            "user/password.html", username=flask.request.args.get("username"))

    elif utils.http_POST():
        try:
            try:
                username = flask.request.form.get("username") or ""
                if not username: raise ValueError
                user = get_user(username=username)
                if user is None: raise ValueError
                if am_admin_and_not_self(user):
                    pass  # No check for current password.
                else:
                    password = flask.request.form.get("current_password") or ""
                    if not check_password_hash(user["password"], password):
                        raise ValueError
            except ValueError:
                raise ValueError("No such user or wrong password.")
            password = flask.request.form.get("password")
            if password != flask.request.form.get("confirm_password"):
                raise ValueError("Wrong password entered; confirm failed.")
        except ValueError as error:
            return utils.error(error, flask.url_for(".password"))
        with UserSaver(user) as saver:
            saver.set_password(password)
        utils.get_logger().info(f"password user {user['username']}")
        if not flask.g.current_user:
            do_login(username, password)
        return flask.redirect(flask.url_for("home"))
Beispiel #2
0
def edit(username):
    "Edit the user display. Or delete the user."
    user = get_user(username=username)
    if user is None:
        return utils.error("No such user.")
    if not am_admin_or_self(user):
        return utils.error("Access not allowed.")

    if utils.http_GET():
        deletable = am_admin_and_not_self(user) and user["blobs_count"] == 0
        return flask.render_template("user/edit.html",
                                     user=user,
                                     change_role=am_admin_and_not_self(user),
                                     deletable=deletable)

    elif utils.http_POST():
        with UserSaver(user) as saver:
            if flask.g.am_admin:
                email = flask.request.form.get("email")
                if email != user["email"]:
                    saver.set_email(email)
                try:
                    quota = flask.request.form.get('quota') or None
                    if quota:
                        quota = int(quota)
                        if quota < 0: raise ValueError
                except (ValueError, TypeError):
                    pass
                else:
                    saver.set_quota(quota)
            if am_admin_and_not_self(user):
                saver.set_role(flask.request.form.get("role"))
            if flask.request.form.get("accesskey"):
                saver.set_accesskey()
        return flask.redirect(
            flask.url_for(".display", username=user["username"]))

    elif utils.http_DELETE():
        if user["blobs_count"] != 0:
            return utils.error("Cannot delete non-empty user account.")
        with flask.g.db:
            flask.g.db.execute("DELETE FROM logs WHERE iuid=?",
                               (user["iuid"], ))
            flask.g.db.execute(
                "DELETE FROM users "
                " WHERE username=? COLLATE NOCASE", (username, ))
        utils.flash_message(f"Deleted user {username}.")
        utils.get_logger().info(f"deleted user {username}")
        if flask.g.am_admin:
            return flask.redirect(flask.url_for(".all"))
        else:
            return flask.redirect(flask.url_for("home"))
Beispiel #3
0
def blob(filename):
    "Return the blob itself, or create or update an existing blob."
    if utils.http_GET() or utils.http_HEAD():
        data = get_blob_data(filename)
        if not data:
            # Just send error code; appropriate for programmatic use.
            flask.abort(http.client.NOT_FOUND)
        return flask.send_from_directory(
            flask.current_app.config["STORAGE_DIRPATH"], filename)

    elif utils.http_PUT():
        data = get_blob_data(filename)
        # Update an existing blob.
        if data:
            if not allow_update(data):
                flask.abort(http.client.UNAUTHORIZED)
            try:
                with BlobSaver(data) as saver:
                    saver.set_content(flask.request.data)
            except ValueError:
                flask.abort(http.client.BAD_REQUEST)
        # Cannot create a new blob unless logged in.
        elif not flask.g.current_user:
            flask.abort(http.client.UNAUTHORIZED)
        # Create a new blob; the filename is part of the URL.
        else:
            try:
                with BlobSaver() as saver:
                    saver["filename"] = filename
                    saver.set_content(flask.request.data)
                    saver["username"] = flask.g.current_user["username"]
            except ValueError:
                flask.abort(http.client.BAD_REQUEST)
        return flask.redirect(
            flask.url_for("blob.info", filename=saver["filename"]))

    elif utils.http_DELETE():
        data = get_blob_data(filename)
        if not data:
            # Just send error code; appropriate for programmatic use.
            flask.abort(http.client.NOT_FOUND)
        if not allow_delete(data):
            # Just send error code; appropriate for programmatic use.
            flask.abort(http.client.FORBIDDEN)
        delete_blob(data)
        utils.flash_message(f"Deleted blob {data['filename']}")
        return flask.redirect(
            flask.url_for("blobs.user", username=data["username"]))

    return flask.abort(http.client.METHOD_NOT_ALLOWED)
Beispiel #4
0
def rename(filename):
    data = get_blob_data(filename)
    if not data:
        return utils.error("No such blob.")
    if not allow_update(data):
        return utils.error("You may not rename the blob.")

    if utils.http_GET():
        return flask.render_template("blob/rename.html", data=data)

    elif utils.http_POST():
        try:
            with BlobSaver(data) as saver:
                saver.rename(flask.request.form.get("filename"))
        except ValueError as error:
            return utils.error(error)
        return flask.redirect(
            flask.url_for("blob.info", filename=saver["filename"]))
Beispiel #5
0
def upload():
    "Upload a new blob."
    if utils.http_GET():
        return flask.render_template("blob/upload.html")

    elif utils.http_POST():
        infile = flask.request.files.get("file")
        if not infile:
            return utils.error("No file provided.")
        if get_blob_data(infile.filename):
            return utils.error("Blob already exists; do update instead.")
        try:
            with BlobSaver() as saver:
                saver["filename"] = infile.filename
                saver["description"] = flask.request.form.get("description")
                saver["username"] = flask.g.current_user["username"]
                saver.set_content(infile.read())
        except ValueError as error:
            return utils.error(error)
        return flask.redirect(
            flask.url_for("blob.info", filename=saver["filename"]))
Beispiel #6
0
def update(filename):
    "Update the content and/or the description of a blob."
    data = get_blob_data(filename)
    if not data:
        return utils.error("No such blob.")
    if not allow_update(data):
        return utils.error("You may not update the blob.")

    if utils.http_GET():
        return flask.render_template("blob/update.html", data=data)

    elif utils.http_POST():
        try:
            with BlobSaver(data) as saver:
                saver["description"] = flask.request.form.get("description")
                infile = flask.request.files.get("file")
                if infile:
                    saver.set_content(infile.read())
        except ValueError as error:
            return utils.error(error)
        return flask.redirect(
            flask.url_for("blob.info", filename=saver["filename"]))
Beispiel #7
0
def description(filename):
    "Programmatic interface to the description for a blob."
    data = get_blob_data(filename)
    if not data:
        # Just send error code; appropriate for programmatic use.
        flask.abort(http.client.NOT_FOUND)

    if utils.http_GET() or utils.http_HEAD():
        response = flask.make_response(doc.get("description") or "")
        response.headers.set("Content-Type", "text/plain; charset=utf-8")
        return response

    elif utils.http_PUT():
        if not allow_update(data):
            flask.abort(http.client.FORBIDDEN)
        try:
            with BlobSaver(data) as saver:
                if flask.request.data:
                    saver["description"] = flask.request.data.decode('utf-8')
                else:
                    saver["description"] = None
        except ValueError:
            flask.abort(http.client.BAD_REQUEST)
        return flask.redirect(
            flask.url_for("blob.info", filename=saver["filename"]))

    elif utils.http_DELETE():
        if not allow_delete(data):
            flask.abort(http.client.FORBIDDEN)
        try:
            with BlobSaver(data) as saver:
                saver["description"] = None
        except ValueError:
            flask.abort(http.client.BAD_REQUEST)
        return flask.redirect(
            flask.url_for("blob.info", filename=saver["filename"]))

    return flask.abort(http.client.METHOD_NOT_ALLOWED)
Beispiel #8
0
def register():
    "Register a new user account."
    if utils.http_GET():
        return flask.render_template("user/register.html")

    elif utils.http_POST():
        try:
            with UserSaver() as saver:
                saver.set_username(flask.request.form.get("username"))
                saver.set_email(flask.request.form.get("email"))
                saver.set_role(constants.USER)
                saver.set_quota(flask.current_app.config["DEFAULT_QUOTA"])
                password = flask.request.form.get("password")
                confirm = flask.request.form.get("confirm_password")
                if password != confirm:
                    raise ValueError("Password confirmation failed.")
                saver.set_password(password)
                saver.set_status(constants.ENABLED)
            user = saver.doc
        except ValueError as error:
            return utils.error(error)
        utils.get_logger().info(f"registered user {user['username']}")
        return flask.redirect(flask.url_for("home"))
Beispiel #9
0
def copy(filename):
    data = get_blob_data(filename)
    if not data:
        return utils.error("No such blob.")

    if utils.http_GET():
        return flask.render_template("blob/copy.html", data=data)

    elif utils.http_POST():
        filepath = os.path.join(flask.current_app.config['STORAGE_DIRPATH'],
                                data["filename"])
        try:
            with open(filepath, "rb") as infile:
                content = infile.read()
            with BlobSaver() as saver:
                saver["filename"] = flask.request.form.get("filename")
                saver["description"] = flask.request.form.get("description")
                saver["username"] = flask.g.current_user["username"]
                saver.set_content(content)
        except ValueError as error:
            return utils.error(error)
        return flask.redirect(
            flask.url_for("blob.info", filename=saver["filename"]))
Beispiel #10
0
def login():
    """Login to a user account.
    Creates the admin user specified in the settings.json, if not done.
    """
    if utils.http_GET():
        return flask.render_template("user/login.html",
                                     next=flask.request.args.get("next"))
    elif utils.http_POST():
        username = flask.request.form.get("username")
        password = flask.request.form.get("password")
        try:
            if username and password:
                do_login(username, password)
            else:
                raise ValueError
            try:
                next = flask.request.form["next"]
            except KeyError:
                return flask.redirect(flask.url_for("home"))
            else:
                return flask.redirect(next)
        except ValueError:
            return utils.error(
                "Invalid user or password, or account disabled.")