Exemple #1
0
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        db = get_db()
        error = []

        cur = db.execute(
            """SELECT "id", "password" FROM "user" WHERE "username" = :user;""",
            {"user": username})
        user = cur.fetchone()
        cur.close()

        if user is None:
            error.append("User '{:s}' does not exist.".format(username))
        elif not check_password_hash(user["password"], password):
            error.append("Bad password for user '{:s}'.".format(username))
        else:
            session.clear()
            session["user_id"] = user["id"]
            return redirect(url_for("index"))

        flash("\n".join(error))

    return render_template("auth/login.html")
Exemple #2
0
def load_authed_user():
    user_id = session.get("user_id")

    if user_id is None:
        g.user = None
        g.groups = []
    else:
        cur = get_db().cursor()

        g.user = cur.execute(
            """SELECT "id", "username" FROM "user" WHERE "id" = :uid;""", {
                "uid": user_id
            }).fetchone()

        g.groups = [
            r["groupname"] for r in cur.execute(
                """
SELECT "groupname"
FROM "group", "user_in_group" uig
WHERE 1
    AND "id" = uig."group_id"
    AND uig."user_id" = :uid
;
            """, {
                    "uid": user_id
                }).fetchall()
        ]

        cur.close()
Exemple #3
0
def authorize_user(user):
    if g.user is None:
        return False
    else:
        if isinstance(user, (list, tuple)):
            return any(authorize_user(u) for u in user)

        authed = False
        if user[0] == '@':
            cur = get_db().execute(
                """
SELECT
    g."id"
FROM
    "group" g,
    "user_in_group" uig
WHERE 1
    AND g."groupname" = :group
    AND uig."user_id" = :uid
    AND g."id" = uig."group_id"
;
                """, {
                    "group": user[1:],
                    "uid": g.user["id"]
                })
            if cur.fetchone() is not None:
                authed = True
            cur.close()
        elif user == g.user["username"]:
            authed = True

        return authed
Exemple #4
0
def delete(id):
    #    get_post(id)
    db = get_db()
    db.execute("""DELETE FROM "post" WHERE "id" = :pid;""", {
        "pid": id
    }).close()
    db.commit()
    return redirect(url_for("blog.index"))
Exemple #5
0
def get_files(id):
    cur = get_db().cursor()
    files = [BlogFile(
        join_path(current_app.config["UPLOAD_FOLDER"], row["filename"]),
        counter=row["counter"],
        id=row["id"]
    ) for row in cur.execute(
        """SELECT "id", "filename", "counter" FROM "file" WHERE "post_id" = :pid;""",
        {"pid": id}
    )]
    cur.close()
    return files
Exemple #6
0
def download(fid):
    cur = get_db().execute("""SELECT "filename" FROM "file" WHERE "id" = :fid;""", {"fid": fid})
    res = cur.fetchone()
    cur.close()
    
    if res is None:
        abort(404, "There is no file with id {:d}.".format(fid))
    else:
        filename = join_path(current_app.config["UPLOAD_FOLDER"], res["filename"])
        if isfile(filename):
            return send_file(filename, as_attachment=True)
        else:
            abort(404, "The file '{:s}' could not be found.".format(filename))
Exemple #7
0
def index():
    db = get_db()

    cur = db.execute("""
SELECT
    "id",
    "title",
    "body",
    "ref_date"
FROM "post"
ORDER BY "ref_date" DESC
;
        """)
    posts = cur.fetchall()
    cur.close()

    return render_template("blog/index.html", posts=posts)
Exemple #8
0
def update(id):
    if request.method == "POST":
        title = request.form["title"]
        body = request.form["body"]
        dt = request.form["date"]
        error = []

        if not title:
            error.append("The title must not be empty.")
        if date:
            try:
                dt = date.fromisoformat(dt)
            except ValueError:
                error.append(
                    "Date must be given as 'YYYY-MM-DD' or left empty.")
                dt = None

        if error:
            flash("\n".join(error))
        else:
            db = get_db()
            db.execute(
                """
                UPDATE "post"
                SET
                    "title" = :title,
                    "body" = :body,
                    "ref_date" = :date
                WHERE "id" = :pid;""", {
                    "title": title,
                    "body": body,
                    "date": dt.isoformat() if dt else None,
                    "pid": id
                }).close()
            db.commit()

            add_files(id, request.files.getlist("files"))

            return redirect(url_for(".show", id=id))

    return render_template("blog/update.html",
                           post=get_post(id),
                           files=get_files(id))
Exemple #9
0
def add_files(pid, files):
    db = get_db()
    cur = db.cursor()
    for file in files:
        if file.filename:
            try:
                fname = secure_filename(file.filename)
                file.save(join(current_app.config["UPLOAD_FOLDER"], fname))
                cur.execute(
                    """
INSERT INTO file ("filename", "post_id")
VALUES (:name, :id)
;
                    """, {
                        "id": pid,
                        "name": fname
                    })
                db.commit()
            except:
                flash("Failed to save file '{:s}'.".format(file.filename))
Exemple #10
0
def create_group_command(name):
    """Create new user group."""
    db = get_db()
    cur = db.execute("""SELECT "id" FROM "group" WHERE "groupname" = :name;""",
                     {"name": name})

    if cur.fetchone() is not None:
        echo("Group '{:s}' does already exist.".format(name))
        cur.close()
        return

    try:
        db.execute("""INSERT INTO "group" ("groupname") VALUES (:name);""", {
            "name": name
        }).close()
        db.commit()
    except SQLiteError as err:
        echo("Failed to create group '{:s}': {:s}".format(name, err.args[0]))
        return

    echo("Group '{:s}' created.".format(name))
Exemple #11
0
def create():
    if request.method == "POST":
        title = request.form["title"]
        body = request.form["body"]
        dt = request.form["date"]
        error = []

        if not title:
            error.append("Title must not be empty.")
        if date:
            try:
                dt = date.fromisoformat(dt)
            except ValueError:
                error.append(
                    "Date must be given as 'YYYY-MM-DD' or left empty.")
                dt = None

        if error:
            flash("\n".join(error))
        else:
            db = get_db()
            cur = db.execute(
                """
INSERT INTO "post" ("title", "body", "ref_date")
VALUES (:title, :body, :date);
                    """, {
                    "title": title,
                    "body": body,
                    "date": dt.isoformat() if dt else None
                })
            db.commit()
            pid = cur.lastrowid

            #            flash(len(request.files.getlist("files")))
            add_files(pid, request.files.getlist("files"))

            return redirect(url_for(".show", id=pid))

    return render_template("blog/create.html")
Exemple #12
0
def get_post(id):
    cur = get_db().cursor()

    post = cur.execute(
        """
SELECT
    "id",
    "title",
    "body",
    "ref_date"
FROM "post" p
WHERE "id" = :pid
;
        """, {
            "pid": id
        }).fetchone()

    cur.close()

    if post is None:
        abort(404, "There is no post with id {:d}".format(id))

    return post
Exemple #13
0
def create_user_command(name, group=None):
    """Create a new user."""
    db = get_db()
    cur = db.execute("BEGIN TRANSACTION;")

    if cur.execute("""SELECT "id" FROM "user" WHERE "username" = :name;""", {
            "name": name
    }).fetchone() is not None:
        echo("User '{:s}' does already exist.".format(name))
        cur.close()
        return

    if group is None:
        group_id = None
    else:
        group_res = cur.execute(
            """SELECT "id" FROM "group" WHERE "groupname" = :name;""", {
                "name": group
            }).fetchone()
        if group_res is None:
            if confirm("Group '{:s}' does not exist. Create it?".format(group),
                       default=True):
                try:
                    cur.execute(
                        """INSERT INTO "group" ("groupname") VALUES (:name);""",
                        {"name": group})
                except SQLiteError as err:
                    echo("Failed to create group '{:s}': {:s}".format(
                        group, err.args[0]))
                    cur.execute("ROLLBACK TRANSACTION;")
                    cur.close()
                    return
                group_id = cur.lastrowid
            else:
                echo("I did not create user '{:s}'.".format(name))
                cur.close()
                return
        else:
            group_id = group_res["id"]

    while True:
        password = prompt("Enter a password for user '{:s}'".format(name),
                          hide_input=True,
                          type=str)
        if len(password) > 5:
            break
        echo("Password not acceptable, too short.")

    try:
        cur.execute(
            """INSERT INTO "user" ("username", "password") VALUES (:name, :secret);""",
            {
                "name": name,
                "secret": generate_password_hash(password)
            })
        if group_id is not None:
            cur.execute(
                """INSERT INTO "user_in_group" ("user_id", "group_id") VALUES (:uid, :gid);""",
                {
                    "uid": cur.lastrowid,
                    "gid": group_id
                })
        cur.execute("COMMIT TRANSACTION;")
    except SQLiteError as err:
        echo("Failed to create user '{:s}': {:s}".format(name, err.args[0]))
        cur.execute("ROLLBACK TRANSACTION;")
        cur.close()
        return

    if group_id is None:
        echo("User '{:s}' created.".format(name))
    else:
        echo("User '{:s}' created as member of group '{:s}'.".format(
            name, group))