Exemplo n.º 1
0
def check_sudo(user):
    sudo_mode = flask.request.cookies.get("sudo_mode")
    if sudo_mode == None or read_cookie(sudo_mode) == None:
        return False

    if user != read_cookie(sudo_mode):
        return False

    return True
Exemplo n.º 2
0
def logout():
    referrer = flask.request.referrer

    try:
        referrer.index("/logout")
    except ValueError:
        pass
    else:
        referrer = "/"

    cookie = flask.request.cookies.get("session")
    if cookie == None:
        return flask.redirect(referrer)

    user_id = read_cookie(cookie)
    if user_id == None:
        return flask.redirect(referrer)

    cnx = get_pg_connection()

    response = flask.make_response(flask.redirect(referrer))
    response.set_cookie("session", "", expires=0)
    response.set_cookie("sudo_mode", "", expires=0)
    write_log("logout", user_id, {"success": True})
    return response
Exemplo n.º 3
0
def render_template(template, **kwargs):
    args = {
        "title": "How do your end up here?",
        "body": "How do your end up here?"
    }

    try:
        cookie = read_cookie(flask.request.cookies["session"])
    except KeyError:
        cookie = None

    try:
        sudo_mode = read_cookie(flask.request.cookies["sudo_mode"])
    except KeyError:
        sudo_mode = None    

    try:
        cnx = get_pg_connection()
        cursor = cnx.cursor()
        cursor.execute('SELECT name, category_id FROM category ORDER BY category_id')
        categories = list(cursor)

        cursor = cnx.cursor()
        cursor.execute('SELECT nick, email, admin FROM users WHERE user_id = %s', (cookie, ))

        result = cursor.fetchone()

        if result:
            user, avatar, admin = result
            avatar = hashlib.md5(avatar.strip().lower().encode("utf8")).hexdigest()
        else:
            user, avatar, admin = None, None, None

    finally:
        cnx.close()

    kwargs["categories"] = categories
    kwargs["user"] = user
    kwargs["avatar"] = avatar
    kwargs["user_id"] = cookie
    kwargs["admin"] = admin
    kwargs["sudo"] = sudo_mode

    return flask.render_template(template, **kwargs)
Exemplo n.º 4
0
def drafts(order, page):
    try:
        user = read_cookie(flask.request.cookies["session"])
    except:
        user = None

    if user == None:
        return flask.redirect("/")

    return list_threads(order, int(page), author=user, draft=True)
Exemplo n.º 5
0
def new_thread():
    now = datetime.datetime.now()

    try:
        userid = read_cookie(flask.request.cookies["session"])
    except KeyError:
        flask.abort(401)

    if userid == None:
        flask.abort(401)

    try:
        title = flask.request.form["title"]
        category = flask.request.form["category"]
        renderer = flask.request.form["renderer"]
        content = flask.request.form["content"]
        is_draft = bool(int(flask.request.form["draft"]))
    except KeyError:
        flask.abort(400)

    thread_id = str(uuid.uuid4()).replace('-', '')
    post_id = str(uuid.uuid4()).replace('-', '')
    post_content_id = str(uuid.uuid4()).replace('-', '')

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()
        cursor.execute(
            "INSERT INTO thread VALUES ("
            "%s, %s, %s, %s, %s, FALSE, %s )",
            (thread_id, userid, category, now, title, bool(is_draft)))

        cursor.execute(
            "INSERT INTO post VALUES ("
            "%s, %s, %s, %s, FALSE, %s, %s)",
            (post_id, userid, thread_id, now, now, post_content_id))

        cursor.execute(
            "INSERT INTO post_content VALUES ("
            "%s, %s, %s, %s, %s)",
            (post_content_id, post_id, renderer, content, now))
        cnx.commit()
        write_log("new_thread", userid, {
            "success": True,
            "id": thread_id,
            "title": title
        })
    finally:
        cnx.close()

    return flask.redirect("/thread/view/" + thread_id)
Exemplo n.º 6
0
def check_permission():
    session = flask.request.cookies.get("session")
    if session == None or read_cookie(session) == None:
        write_log("dashboard_access", "", {"success": False})
        flask.abort(401)

    user = read_cookie(session)

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()
        cursor.execute(
            "SELECT * FROM users WHERE user_id = %s AND admin = TRUE",
            (user, ))
        result = (cursor.fetchone() != None)
    finally:
        cnx.close()

    if not result:
        write_log("dashboard_access", user, {"success": False})
        flask.abort(401)

    return user
Exemplo n.º 7
0
def deleted_post(post_id):
    user = flask.request.cookies.get("session")
    if user != None and read_cookie(user) != None:
        user = read_cookie(user)

    cnx = get_pg_connection()
    try:
        if user:
            cursor = cnx.cursor()
            cursor.execute("SELECT admin FROM users WHERE user_id = %s",
                           (user, ))
            admin, = cursor.fetchone()
        else:
            admin = False

        if not admin:
            flask.abort(404)

        cursor = cnx.cursor()
        cursor.execute(
            "select post.post_id, users.nick, post.author, "
            "LOWER(MD5(TRIM(LOWER(users.email)))), "
            "post_content.content, post_content.datetime, post_content.renderer FROM post, users, post_content "
            "WHERE post.author = users.user_id "
            "AND post.content = post_content.content_id "
            "AND post.post_id = %s", (post_id, ))
        posts = cursor.fetchall()
    finally:
        cnx.close()
        return render_template("post.tmpl",
                               posts=posts,
                               page=1,
                               post_per_page=1,
                               total_pages=1,
                               render_content=render_content,
                               title="被删除的回复")
Exemplo n.º 8
0
def reply():
    now = datetime.datetime.now()

    try:
        userid = read_cookie(flask.request.cookies["session"])
    except KeyError:
        flask.abort(401)

    if userid == None:
        flask.abort(401)

    try:
        renderer = flask.request.form["renderer"]
        content = flask.request.form["content"]
        thread_id = flask.request.form["thread_id"]
    except KeyError:
        flask.abort(400)

    post_id = str(uuid.uuid4()).replace('-', '')
    post_content_id = str(uuid.uuid4()).replace('-', '')

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()
        cursor.execute(
            "INSERT INTO post VALUES ("
            "%s, %s, %s, %s, FALSE, %s, %s)",
            (post_id, userid, thread_id, now, now, post_content_id))
        cursor.execute(
            "INSERT INTO post_content VALUES ("
            "%s, %s, %s, %s, %s)",
            (post_content_id, post_id, renderer, content, now))
        cnx.commit()
        write_log("new_reply", userid, {
            "success": True,
            "post_id": post_id,
            "content_id": post_content_id
        })
    finally:
        cnx.close()

    return flask.redirect(flask.request.referrer)
Exemplo n.º 9
0
def list_threads(order, page, category=None, author=None, draft=False):
    order_sql = {
        'publish': 'publish_datetime',
        'reply': 'reply_count',
        'last_modified': 'last_modified',
        'random': 'RAND()'
    }

    category_sql = "AND thread.category = %s" if category else ''
    author_sql = "AND thread.author = %s" if author else ''

    try:
        sudo_mode = read_cookie(flask.request.cookies["sudo_mode"])
    except KeyError:
        sudo_mode = None

    hidden = bool(sudo_mode)

    query = (
        "SELECT thread.thread_id, thread.title, thread.datetime AS publish_datetime, "
        "users.nick, MAX(post.last_modified) AS last_modified, "
        "(SELECT COUNT(*) FROM post WHERE post.thread = thread.thread_id) AS reply_count FROM thread, post, users "
        "WHERE thread.hidden = FALSE "
        "AND post.thread = thread.thread_id "
        "AND users.user_id = thread.author "
        "AND thread.draft = %s {} {} "
        "GROUP BY thread.thread_id, users.nick "
        "ORDER BY {} DESC "
        "LIMIT {} "
        "OFFSET %s ").format(category_sql, author_sql, order_sql[order],
                             config["paginator"]["thread_per_page"])
    page_query = "SELECT COUNT(*) FROM thread WHERE hidden = FALSE AND draft = %s {} {}".format(
        category_sql, author_sql)
    category_query = "SELECT name FROM category WHERE category_id = %s"

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()
        page_cursor = cnx.cursor()

        if category:
            category_cursor = cnx.cursor()

            if author:
                cursor.execute(
                    query,
                    (draft, category, author,
                     (page - 1) * config["paginator"]["thread_per_page"]))
            else:
                cursor.execute(
                    query,
                    (draft, category,
                     (page - 1) * config["paginator"]["thread_per_page"]))

            if author:
                page_cursor.execute(page_query, (draft, category, author))
            else:
                page_cursor.execute(page_query, (
                    draft,
                    category,
                ))

            category_cursor.execute(category_query, (category, ))

            category_name, = category_cursor.fetchone()

            title = "分类: " + category_name

        else:
            if author:
                cursor.execute(
                    query,
                    (draft, author,
                     (page - 1) * config["paginator"]["thread_per_page"]))
            else:
                cursor.execute(
                    query,
                    (draft,
                     (page - 1) * config["paginator"]["thread_per_page"]))

            if author:
                page_cursor.execute(page_query, (draft, author))
            else:
                page_cursor.execute(page_query, (draft, ))

            title = "主页"

        total_pages, = page_cursor.fetchone()
        total_pages = int((total_pages - 1) /
                          config["paginator"]["thread_per_page"] + 1)

        if draft:
            baseurl = "/drafts"
        elif category:
            baseurl = "/category/{}/{}".format(category, order)
        else:
            baseurl = "/index/" + order

        ret = render_template('list.tmpl',
                              cursor=cursor,
                              title=title,
                              page=page,
                              total_pages=total_pages,
                              order=order,
                              baseurl=baseurl)
    finally:
        cnx.close()

    return ret
Exemplo n.º 10
0
def edit(edit_type, target_id):
    try:
        user = read_cookie(flask.request.cookies["session"])
    except:
        user = None

    if user == None:
        flask.abort(401)

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()

        if edit_type == 'thread':
            cursor.execute(
                "SELECT thread.title, thread.category, thread.draft, users.admin FROM thread, users "
                "WHERE thread.thread_id = %s AND users.user_id = %s AND (thread.author = users.user_id OR users.admin = TRUE)",
                (target_id, user))
            title, category, is_draft, _ = cursor.fetchone()

            cursor.execute(
                "SELECT post.post_id, users.admin FROM post, users "
                "WHERE post.thread = %s AND users.user_id = %s AND (post.author = users.user_id OR users.admin = TRUE) "
                "ORDER BY datetime LIMIT 1 OFFSET 0", (target_id, user))
            post_id = cursor.fetchone()
            if not post_id:
                flask.abort(404)
            post_id = post_id[0]
        else:
            post_id = target_id
    except:
        cnx.close()
        raise

    try:
        cursor = cnx.cursor()
        cursor.execute(
            "SELECT content, renderer FROM post_content WHERE post = %s ORDER BY datetime DESC LIMIT 1 OFFSET 0",
            (post_id, ))
        content, renderer = cursor.fetchone()
    finally:
        cnx.close()

    kwargs = {
        "renderer": renderer,
        "referrer": flask.request.referrer,
        "content": content,
        "post_id": post_id
    }

    if edit_type == "thread":
        print(title)
        kwargs["type"] = "edit_thread"
        kwargs["title"] = "编辑主题:" + title
        kwargs["current_category_id"] = category
        kwargs["draft"] = is_draft
        kwargs["thread_id"] = target_id
    else:
        kwargs["type"] = "edit_post"
        kwargs["title"] = "编辑回复"

    return render_template("edit.tmpl", **kwargs)
Exemplo n.º 11
0
def post(thread, page):
    user = flask.request.cookies.get("session")
    if user != None and read_cookie(user) != None:
        user = read_cookie(user)

    cnx = get_pg_connection()
    try:
        if user:
            cursor = cnx.cursor()
            cursor.execute("SELECT admin FROM users WHERE user_id = %s",
                           (user, ))
            admin, = cursor.fetchone()
        else:
            admin = False

        cursor = cnx.cursor()
        cursor.execute("SELECT title FROM thread WHERE thread_id = %s",
                       (thread, ))
        title = cursor.fetchone()[0]

        cursor = cnx.cursor()
        cursor.execute("SELECT COUNT(*) FROM post WHERE thread = %s",
                       (thread, ))
        post_count = cursor.fetchone()[0]

        cursor = cnx.cursor()
        cursor.execute("SELECT hidden FROM thread WHERE thread_id = %s",
                       (thread, ))
        hidden, = cursor.fetchone()

        if hidden and not admin:
            flask.abort(404)

        query = (
            "SELECT post.post_id, users.nick, post.author, "
            "LOWER(MD5(TRIM(LOWER(users.email)))), "
            "post_content.content, post_content.datetime, post_content.renderer FROM post, users, thread, post_content "
            "WHERE post.thread = %s AND post.hidden = FALSE "
            "AND post.thread = thread.thread_id "
            "AND post.author = users.user_id "
            "AND post.content = post_content.content_id "
            "ORDER BY post.datetime LIMIT {} OFFSET %s".format(
                config["paginator"]["post_per_page"]))
        cursor = cnx.cursor()
        cursor.execute(
            query,
            (thread, int(
                (int(page) - 1) * config["paginator"]["post_per_page"])))
        posts = list(cursor)

        cursor = cnx.cursor()
        cursor.execute("SELECT thread.author FROM thread WHERE thread_id = %s",
                       (thread, ))
        thread_author_id = cursor.fetchone()[0]

    finally:
        cnx.close()

    total_pages = int((post_count - 1) / config["paginator"]["post_per_page"] +
                      1)
    return render_template("post.tmpl",
                           posts=posts,
                           thread_hidden=hidden,
                           page=int(page),
                           total_pages=total_pages,
                           thread_author_id=thread_author_id,
                           baseurl="/thread/view/{}".format(thread),
                           post_per_page=config["paginator"]["post_per_page"],
                           render_content=render_content,
                           title=title,
                           thread_id=thread)
Exemplo n.º 12
0
def userinfo():
    try:
        user = read_cookie(flask.request.cookies["session"])
    except KeyError:
        return flask.redirect("/")

    if not user:
        flask.redirect("/")

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()
        cursor.execute(
            'SELECT name, email, nick, salt FROM users WHERE user_id = %s',
            (user, ))
        name, email, nick, salt = cursor.fetchone()
    finally:
        cnx.close()

    if flask.request.method == "GET":
        return render_template("userinfo.tmpl",
                               error=False,
                               name=name,
                               email=email,
                               nick=nick,
                               title="User Info")
    else:
        try:
            new_email = flask.request.form["email"]
            new_nick = flask.request.form["nick"]
            old_password = flask.request.form["old_password"]
            new_password = flask.request.form["new_password"]
        except:
            return flask.abort(400)

        if new_password != "":
            cnx = get_pg_connection()
            cursor = cnx.cursor()
            try:
                hashed_old_password = hashlib.sha256(
                    (old_password + salt).encode()).hexdigest().upper()
                cursor.execute(
                    "SELECT user_id FROM users WHERE user_id = %s AND password = %s",
                    (user, hashed_old_password))
                if not cursor.fetchone():
                    cnx.close()
                    write_log("update_userinfo", user, {
                        "success": False,
                        "reason": "wrong password"
                    })
                    return render_template("userinfo.tmpl",
                                           error=True,
                                           name=name,
                                           email=email,
                                           nick=nick,
                                           title="User Info")
            except:
                cnx.close()
                raise

            salt = crypt.mksalt(crypt.METHOD_SHA256)
            hashed_password = hashlib.sha256(
                (new_password + salt).encode()).hexdigest().upper()
        else:
            hashed_password = None

        cnx = get_pg_connection()
        try:
            cursor = cnx.cursor()
            if hashed_password:
                cursor.execute(
                    "UPDATE users SET email = %s, nick = %s, password = %s, salt = %s WHERE user_id = %s",
                    (new_email, new_nick, hashed_password, salt, user))
            else:
                cursor.execute(
                    "UPDATE users SET email = %s, nick = %s WHERE user_id = %s",
                    (new_email, new_nick, user))
            cnx.commit()
        finally:
            cnx.close()

        log_data = {
            "success": True,
            "nick": [nick, new_nick],
            "email": [email, new_email],
            "password_changed": new_password != ""
        }
        write_log("update_userinfo", user, log_data)
        return flask.redirect("/userinfo")
Exemplo n.º 13
0
def edit(edit_type):
    try:
        renderer = flask.request.form["renderer"]
        content = flask.request.form["content"]
        referrer = flask.request.form["referrer"]
        post_id = flask.request.form["post_id"]
    except KeyError:
        flask.abort(400)

    user = read_cookie(flask.request.cookies["session"])

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()
        cursor.execute(
            "SELECT post.author, users.admin, post.content FROM post, users "
            "WHERE post.post_id = %s AND users.user_id = %s "
            "AND (post.author = users.user_id OR users.admin = TRUE)",
            (post_id, user))
        post_ret = cursor.fetchone()

        if not post_ret:
            cnx.close()
            flask.abort(401)

        _, _, old_content_id = post_ret
    except:
        cnx.close()
        raise

    if edit_type == "thread":
        try:
            thread_id = flask.request.form["thread_id"]
            title = flask.request.form["title"]
            category = flask.request.form["category"]
            is_draft = bool(int(flask.request.form["draft"]))
        except KeyError:
            flask.abort(400)

        cnx = get_pg_connection()
        try:
            cursor = cnx.cursor()
            cursor.execute(
                "SELECT title, category, draft FROM thread "
                "WHERE thread_id = %s", (thread_id, ))
            old_title, old_category, old_draft = cursor.fetchone()
        except TypeError:
            flask.abort(400)

    new_content_id = str(uuid.uuid4()).replace('-', '')

    cnx = get_pg_connection()
    try:
        cursor = cnx.cursor()
        cursor.execute(
            "INSERT INTO post_content VALUES ("
            "%s, %s, %s, %s, NOW())",
            (new_content_id, post_id, renderer, content))

        cursor.execute(
            "UPDATE post SET content = %s, last_modified = NOW() WHERE post_id = %s",
            (new_content_id, post_id))

        if edit_type == "thread":
            cursor.execute(
                "UPDATE thread SET title = %s, category = %s, draft = %s "
                "WHERE thread_id = %s", (title, category, is_draft, thread_id))
        cnx.commit()
    except:
        traceback.print_exc()

    finally:
        cnx.close()

    log_data = {
        "success": True,
        "post_id": post_id,
        "type": edit_type,
        "rev": [old_content_id, new_content_id]
    }

    if edit_type == "thread":
        log_data["thread"] = {
            "title": [old_title, title],
            "category": [old_category, category],
            "draft": [old_draft, is_draft]
        }

    write_log("edit", user, log_data)
    return flask.redirect(referrer)