Flask – Simple Auth (mysql.connector)

app.py :

from flask import Flask, render_template, request, redirect, url_for, session, flash
import hashlib
import mysql.connector

app = Flask(__name__)

app.config['SECRET_KEY'] = 'SecretXXX'
app.config['DEBUG'] = True

db = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="db_name"
)

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

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']
        address = request.form['address']
        password_hash = hashlib.md5(password.encode())

        cursor = db.cursor()
        sql = "SELECT * FROM users WHERE email = %s"
        val = (email,)
        cursor.execute(sql, val)
        account = cursor.fetchone()

        if account:
            flash('Email already exists!')
            return redirect(url_for('register'))
        else:
            sql = "INSERT INTO users (name, email, password, address) VALUES (%s, %s, %s, %s)"
            val = (name, email, password_hash.hexdigest(), address)
            cursor.execute(sql, val)
            db.commit()
            return redirect(url_for('index'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        email = request.form['email']
        password = request.form['password']
        password_hash = hashlib.md5(password.encode())

        cursor = db.cursor()
        cursor.execute('SELECT * FROM users WHERE email = %s AND password = %s', (email, password_hash.hexdigest()))
        account = cursor.fetchone()

        if account:
            #return 'Berhasil Login'
            session['loggedin'] = True
            session['id'] = account[0]
            # Redirect to home page
            return redirect(url_for('home'))
        else:
            #return 'Gagal Login'
            flash('Your login is failed !')
            return redirect(url_for('login'))

@app.route('/logout')
def logout():
    session.pop('loggedin', None)
    session.pop('id', None)
    return redirect(url_for('index'))

@app.route('/home')
def home():
    # Check if user is loggedin
    if 'loggedin' in session:

        id = session['id']
        cursor = db.cursor()
        cursor.execute('SELECT * FROM users')
        data = list(cursor.fetchall())
        return render_template('home.html', id=id, data=data)

    return redirect(url_for('login'))



if __name__ == '__main__':
    app.run()

# set FLASK_APP=app.py
# set FLASK_ENV=development
# flask run

Leave a Reply

Your email address will not be published. Required fields are marked *