from flask import Flask, flash, request, render_template
import sqlite3

app = Flask(__name__)
app.secret_key = 'secret_key'


def db_connection():
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    return c


@app.route('/')
def index():
    return render_template('login.html')


@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']

    # Vulnerable code with SQL injection vulnerability
    query = "SELECT * FROM users WHERE username = '%s' AND password = '%s'" \
        % (username, password)

    # YOU CAN ALSO WRITE IT LIKE THIS:
    # query = "SELECT * FROM users WHERE username='" + username + "' AND \
    # password='" + password + "'"

    try:
        c = db_connection()
        c.execute(query)
        user = c.fetchone()

        if user:
            login_failed = False
            return render_template('profile.html')
        else:
            login_failed = True
            return render_template('login.html', login_failed=login_failed)
    except sqlite3.Error as e:
        flash(f"{e}")
        return render_template('login.html', error=e)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
