Ejemplo n.º 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"))
Ejemplo n.º 2
0
def disable(username):
    "Disable the given user account."
    user = get_user(username=username)
    if user is None:
        return utils.error("No such user.")
    if user["username"] == flask.g.current_user["username"]:
        return utils.error("You cannot disable yourself.")
    with UserSaver(user) as saver:
        saver.set_status(constants.DISABLED)
    utils.get_logger().info(f"disabled user {username}")
    return flask.redirect(flask.url_for(".display", username=username))
Ejemplo n.º 3
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"))
Ejemplo n.º 4
0
def do_login(username, password):
    """Set the session cookie if successful login.
    Raise ValueError if some problem.
    """
    user = get_user(username=username)
    if user is None: raise ValueError
    if not check_password_hash(user["password"], password):
        raise ValueError
    if user["status"] != constants.ENABLED:
        raise ValueError
    flask.session["username"] = user["username"]
    flask.session.permanent = True
    utils.get_logger().info(f"logged in {user['username']}")
Ejemplo n.º 5
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"))
Ejemplo n.º 6
0
def create_admin_user():
    """Check if an admin user is specified by settings.
    If it is, and it has not been created, create it.
    """
    flask.g.db = utils.get_db()
    config = flask.current_app.config
    if not (config["ADMIN_USERNAME"] and config["ADMIN_EMAIL"]
            and config["ADMIN_PASSWORD"]):
        utils.get_logger().info("ADMIN account not specified in settings.")
        return
    if get_user(username=config["ADMIN_USERNAME"]):
        utils.get_logger().info(f"Admin user '{config['ADMIN_USERNAME']}'"
                                " exists already.")
        return
    with UserSaver() as saver:
        saver.set_username(config["ADMIN_USERNAME"])
        saver.set_email(config["ADMIN_EMAIL"])
        saver.set_password(config["ADMIN_PASSWORD"])
        saver.set_role(constants.ADMIN)
        saver.set_status(constants.ENABLED)
    utils.get_logger().info(
        f"Admin user '{config['ADMIN_USERNAME']}' created.")
Ejemplo n.º 7
0
def logout():
    "Logout from the user account."
    username = flask.session.pop("username", None)
    if username:
        utils.get_logger().info(f"logged out {username}")
    return flask.redirect(flask.url_for("home"))