Esempio n. 1
0
def add_post():
    #Validate json
    try:
        validate(instance=request.json, schema=add_post_schema)
    except:
        return 'Bad request', 400

    db = get_db().cursor()

    #Check if thread exists
    db.execute('SELECT * FROM threads WHERE id=?',
               (request.json['thread_id'], ))
    if len(db.fetchall()) == 0:
        return jsonify({"error": "Thread doesn't exist"}), 400

    #Get author id
    db.execute('SELECT id FROM accounts WHERE name=?',
               (get_jwt_identity()['name'], ))
    user_id = db.fetchone()[0]

    db.execute(
        'INSERT INTO posts (thread_id, author_id, content, time_created) VALUES (?, ?, ?, ?)',
        (request.json['thread_id'], user_id, request.json['content'],
         int(time.time())))

    return jsonify({"success": True, "post_id": db.lastrowid}), 200
Esempio n. 2
0
def get_thread(thread_id):
    db = get_db().cursor()

    db.execute('SELECT sub_cat_id, author_id, title, threads.time_created, content, name, is_admin FROM threads JOIN accounts ON threads.author_id=accounts.id WHERE threads.id=?', (thread_id,))
    thread = list(db.fetchone())

    if len(thread) == 0:
        return jsonify({"success": False}), 404

    threadObj = {
        "sub_cat_id": thread[0],
        "author_id": thread[1],
        "title": thread[2],
        "time_created": thread[3],
        "content": thread[4],
        "author_name": thread[5],
        "is_admin": thread[6] != 0
    }   

    db.execute('SELECT posts.id, posts.content, posts.time_created, accounts.name, is_admin FROM posts JOIN accounts ON author_id = accounts.id WHERE thread_id=?', (thread_id,))
    posts = list(db.fetchall())
    posts = list(map(lambda post: {"id": post[0], "content": post[1], "time_created": post[2], "author_name": post[3], "is_admin" : post[4] != 0}, posts))

    threadObj['posts'] = posts

    return jsonify({"thread": threadObj})
Esempio n. 3
0
def add_thread():
    #Validate json
    try:
        validate(instance=request.json, schema=add_thread_schema)
    except:
        return 'Bad request', 400

    db = get_db().cursor()

    #Check if sub_category exists
    db.execute('SELECT * FROM subcategories WHERE id=?',
               (request.json['sub_cat_id'], ))
    if len(db.fetchall()) == 0:
        return jsonify({"error": "Subcategory doesn't exist"})

    #Get author id
    db.execute('SELECT id FROM accounts WHERE name=?',
               (get_jwt_identity()['name'], ))
    user_id = db.fetchone()[0]

    db.execute(
        'INSERT INTO threads (sub_cat_id, author_id, title, time_created, content) VALUES (?, ?, ?, ?, ?)',
        (request.json['sub_cat_id'], user_id, request.json['title'],
         (int(time.time())), request.json['content']))
    return ({"success": True, "thread_id": db.lastrowid})
Esempio n. 4
0
def get_categories():
    db = get_db().cursor()

    db.execute('SELECT * FROM categories')
    categories = list(db.fetchall())

    db.execute('SELECT * FROM subcategories')
    subcategories = list(db.fetchall())

    formatted_categories = []

    for category in categories:
        cat = {
            "id": category[0],
            "name": category[1],
            "desc": category[2]
        }
        subcs = list(filter(lambda subc: subc[1] == cat['id'], subcategories))
        subcs = list(map(lambda subc: {"id": subc[0], "name": subc[2], "desc": subc[3]}, subcs))

        cat['subcategories'] = subcs

        formatted_categories.append(cat)

    return jsonify({'categories': formatted_categories})
Esempio n. 5
0
def login():
    if request.json is None:
        return 'Bad request', 400
    try:
        validate(instance=request.json, schema=login_schema)
    except:
        return 'Bad request', 400
    else:
        db = get_db().cursor()
        db.execute("SELECT id, mail, time_created, password FROM accounts WHERE name=?", (request.json['name'],))

        users = db.fetchall()
        if len(users) == 0:
            db.close()
            return jsonify({"error": "No user found"}), 401

        for user in users:
            if check_password_hash(user[3], request.json['password']):
                db.close()
                user = {
                    "logged": True,
                    "name": request.json['name'],
                    "id": user[0],
                    "mail": user[1],
                    "time_created" : user[2]
                }
        
                expires = datetime.timedelta(days=365)
                access_token = create_access_token(identity=user, expires_delta=expires)

                return jsonify(access_token=access_token), 200
    return jsonify({"error": "Wrong password"}), 401
Esempio n. 6
0
def add_category():
    try:
        validate(instance=request.json, schema=add_category_schema)
    except:
        return 'Bad request', 400

    db = get_db().cursor()
    db.execute('INSERT INTO categories (name, desc) VALUES (?, ?)',
               (request.json['name'], request.json['desc']))

    return jsonify({'success': True})
Esempio n. 7
0
def remove_post():
    try:
        validate(instance=request.json, schema=remove_post_schema)
    except:
        return 'Bad request', 400
    else:
        db = get_db().cursor()

        db.execute('DELETE FROM posts WHERE id=?', request.json['id'])

        return jsonify({'success': True})
Esempio n. 8
0
    def wrapper(*args, **kwargs):
        if 'name' not in session:
            return '', 401

        db = get_db().cursor()
        db.execute("SELECT is_admin FROM accounts WHERE name=?",
                   session['name'])

        is_admin = db.fetchone()[0]

        if is_admin == 0:
            return '', 401

        if request.json is None:
            return '', 400

        return func(*args, **kwargs)
Esempio n. 9
0
def get_subcategory(subcategory):
    db = get_db().cursor()

    db.execute('SELECT * FROM subcategories WHERE id=?', (subcategory,))
    
    subcategoryObj = db.fetchone()
    if subcategoryObj is None:
        return jsonify({error: "Subcategory doesn't exist."}), 404

    subcategoryObj = {
        'name': subcategoryObj[2],
        'desc' : subcategoryObj[3]
    }

    db.execute('SELECT threads.id, threads.title, threads.time_created, threads.content, accounts.name, is_admin FROM threads JOIN accounts ON threads.author_id = accounts.id WHERE sub_cat_id=? ', (subcategory,))
    threads = list(db.fetchall())

    threads = list(map(lambda thread: {"id" : thread[0], "title" : thread[1], "time_created" : thread[2], "content" : thread[3] ,"author_name" : thread[4], "is_admin": thread[5] != 0}, threads))

    subcategoryObj['threads'] = threads

    return jsonify({"subcategory": subcategoryObj})
Esempio n. 10
0
def register():
    if request.json is None:
        return 'Bad request', 400
    try:
        validate(instance=request.json, schema=register_schema)
    except:
        return 'Bad request', 400
    else:
        db = get_db().cursor()

        db.execute("SELECT * FROM accounts WHERE name=? OR mail=?", (request.json['name'], request.json['mail']))
        
        # User already exists
        fetched_users = db.fetchall()
        if len(fetched_users) != 0:
            db.close()
            return jsonify({"error": "User already exists"}), 400

        db.execute('INSERT INTO accounts (name, mail, time_created, password) VALUES (?, ?, ?, ?);', (request.json['name'], request.json['mail'], str(int(time.time())), generate_password_hash(request.json['password'])))


        db.execute("SELECT id, mail, time_created FROM accounts WHERE name=?", (request.json['name'],))
        user = db.fetchone()

        db.close()
        user = {
            "logged": True,
            "name": request.json['name'],
            "id": user[0],
            "mail": user[1],
            "time_created" : user[2]
        }

        expires = datetime.timedelta(days=365)
        access_token = create_access_token(identity=user, expires_delta=expires)

        db.close()
        return jsonify(success=True, access_token=access_token), 200