def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
def get_extensions(check_author=True):
    all_extensions = get_db().execute(
        'SELECT e.id, ext_title, ext_description, ext_url, ext_headers, ext_payload, ext_background_colour, ext_image, created, author_id, username'
        ' FROM extensions e JOIN user u ON e.author_id = u.id'
        ' WHERE e.author_id = ?',
        (g.user['id'],)
    ).fetchall()
    return all_extensions
def tableau_extension(id):
    extension = get_extension(id)
    if request.method == 'POST':
        response = extension_maker.execute(extension)
        db = get_db()
        db.execute(
            'INSERT INTO executed_extensions (author_id, extension_id, extension_status_code, extension_headers) VALUES (?,?,?,?)',
            (g.user['id'], id, response['status_code'], response['headers'])
        )
        db.commit()
        return redirect(url_for('ext.tableau_extension', id=id, reload=True))
    return render_template('ext/tableau_extension.html', extension=extension)
def delete(id):
    get_extension(id)
    db = get_db()
    db.execute('DELETE FROM extensions WHERE id = ?', (id,))
    db.commit()
    db.execute(
        'INSERT INTO executed_extensions (author_id, extension_id, comment)'
        ' VALUES (?, ?, ?)',
        (g.user['id'], id, 'Extension deleted')
    )
    db.commit()
    return redirect(url_for('ext.extensions'))
def create():
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        url = request.form['url']
        headers = request.form['headers']
        payload = request.form['payload']
        background_colour = request.form['background_colour']
        image = request.form['image']
        error = None

        if not title:
            error = 'Title is required.'
        if not description:
            error = 'Description is required.'
        if not url:
            error = 'Url is required.'

        if error is not None:
            flash(error, 'error')
        else:
            db = get_db()
            db.execute(
                'INSERT INTO extensions (ext_title, ext_description, ext_url, ext_headers, ext_payload, ext_background_colour, ext_image, author_id)'
                ' VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
                (title, description, url, headers, payload, background_colour, image, g.user['id'])
            )
            last_input = get_db().execute(
                'SELECT id from extensions WHERE ext_title = ? and author_id = ? ORDER BY created DESC',
                (title, g.user['id'],)
            ).fetchone()
            db.execute(
                'INSERT INTO executed_extensions (author_id, extension_id, comment)'
                ' VALUES (?, ?, ?)',
                (g.user['id'], last_input['id'], 'Extension added to database')
            )
            db.commit()
            return redirect(url_for('ext.extensions'))

    return render_template('ext/create.html')
def get_extension_log(id, check_author=True):
    extension_log = get_db().execute(
        'SELECT * FROM executed_extensions WHERE extension_id = ?',
        (id,)
    ).fetchall()

    if extension_log is None:
        abort(404, "Extension id {0} doesn't exist.".format(id))

    for log in extension_log:
        if check_author and log['author_id'] != g.user['id']:
            abort(403)

    return extension_log
def get_extension(id, check_author=True):
    extension = get_db().execute(
        'SELECT e.id, ext_title, ext_description, ext_url, ext_headers, ext_payload, ext_background_colour, ext_image, created, author_id, username'
        ' FROM extensions e JOIN user u ON e.author_id = u.id'
        ' WHERE e.id = ?',
        (id,)
    ).fetchone()

    if extension is None:
        abort(404, "Extension id {0} doesn't exist.".format(id))

    if check_author and extension['author_id'] != g.user['id']:
        abort(403)

    return extension
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        user = db.execute('SELECT * FROM user WHERE username = ?',
                          (username, )).fetchone()

        if user is None:
            error = 'Incorrect username.'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect password.'

        if error is None:
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('ext.extensions'))

        flash(error, 'error')

    return render_template('auth/login.html')
def update(id):
    extension = get_extension(id)

    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        url = request.form['url']
        headers = request.form['headers']
        payload = request.form['payload']
        background_colour = request.form['background_colour']
        image = request.form['image']
        error = None

        if not title:
            error = 'Title is required.'
        if not description:
            error = 'Description is required.'
        if not url:
            error = 'Url is required.'

        if error is not None:
            flash(error, 'error')
        else:
            db = get_db()
            db.execute(
                'UPDATE extensions SET ext_title = ?, ext_description = ?, ext_url = ?, ext_headers = ?, ext_payload = ?, '
                'ext_background_colour = ?, ext_image = ? WHERE id = ?',
                (title, description, url, headers, payload, background_colour, image, id)
            )
            db.commit()
            db.execute(
                'INSERT INTO executed_extensions (author_id, extension_id, comment)'
                ' VALUES (?, ?, ?)',
                (g.user['id'], id, 'Extension updated')
            )
            db.commit()
            return redirect(url_for('ext.extensions'))

    return render_template('ext/update.html', extension=extension)
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif db.execute('SELECT id FROM user WHERE username = ?',
                        (username, )).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute('INSERT INTO user (username, password) VALUES (?, ?)',
                       (username, generate_password_hash(password)))
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error, 'error')

    return render_template('auth/register.html')
def traffic():
    traffic_all = get_db().execute(
        'SELECT * FROM executed_extensions').fetchall()
    return render_template('temp.html', traffic_all=traffic_all)