Python Flask Mysqldb Simple Login & Register

April 01, 2018
Dalam membuat aplikasi client-server pasti terdapat user-authentication didalamnya baik digunakan untuk pengunjung maupun admin.

Kali ini saya akan berbagi bagaimana cara membuat user registration dan login dengan database MySQL. Pastikan kamu sudah menginstall flask-mysqldb

pip install python-mysqldb

Membuat database users pada mysql





CREATE DATABASE flaskdb;
CREATE TABLE users ( id smallint unsigned not null auto_increment, name varchar(20) not null, email varchar(20) not null, name password(20) not null, primary key (id) );

Membuat folder templates pada project

Membuat Python Flask MySQL Registration

Membuat layout.html dalam folder templates

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{% block title %} {% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Flask User Auth</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>
<a href="/">Home</a>
</li>
{% if session['name'] %}
<li>
<a href="/logout">Logout</a>
</li>
{% else %}
<li>
<a href="/login">Login</a>
</li>
<li>
<a href="/register">Register</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>

{% block content %} {% endblock %}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

Penjelasan kode program
{% block title %} {% endblock %}
Block untuk title setiap halaman yang mengekstends layout.html

{% if session['name'] %}
Pengecekan session (apakah user login / tidak), jika user sudah login maka tampilkan menu logout, jika belum makan tampilkan menu login dan register


{% block content %} {% endblock %}
Block untuk content setiap halaman yang mengekstends layout.html

Membuat home.html dalam folder templates

{% extends 'layout.html' %}

{% block title %} Home {% endblock %}

{% block content %}
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
Home page
{% if session['name'] %}
Welcome {{ session['name'] }}
{% else %}
Not login
{% endif %}
</div>
</div>
</div>
{% endblock %}

Penjelasan kode program
{% extends 'layout.html' %}
Extends ke layout.html

{% block title %} Home {% endblock %}
Block title untuk penamaan judul halaman

{% block content %}
Block content untuk konten body halaman

{% if session['name'] %}
Pengecekan session (user login), jika terdapat session makan tampilkan welcome nama user jika tidak tampilkan Not Login


Membuat Register.html dalam folder templates

{% extends 'layout.html' %}

{% block title %} Register {% endblock %}

{% block content %}
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="/register" method="POST">
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label>Email:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" name="password">
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}

Membuat app.py: route home dan register





#app.py

from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL,MySQLdb
import bcrypt

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)

@app.route('/')
def home():
    return render_template("home.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'].encode('utf-8')
        hash_password = bcrypt.hashpw(password, bcrypt.gensalt())

        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(name,email,hash_password,))
        mysql.connection.commit()
        session['name'] = request.form['name']
        session['email'] = request.form['email']
        return redirect(url_for('home'))

if __name__ == '__main__':
    app.secret_key = "^A%DJAJU^JJ123"
    app.run(debug=True)


Penjelasan kode program
from flask import Flask, render_template, request, redirect, url_for, session
Mengimport library Flask

from flask_mysqldb import MySQL,MySQLdb
Mengimport library mysqldb untuk koneksi ke database mysql

import bcrypt
Mengimport library bcrypt untuk enkripsi password

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
Konfigurasi flask dan mysql

@app.route('/')
def home():
    return render_template("home.html")
Membuat route / untuk home.html

@app.route('/register', methods=["GET", "POST"])
def register():
Membuat route register dan def register halaman dan aksi penambahan user pada database

if request.method == 'GET':
Jika request method pada route register adalah GET maka tampilkan halaman register.html jika tidak (POST) maka lakukan aksi penambahan user pada database mysql

name = request.form['name']
email = request.form['email']
Mendapatkan data nama dan email yang diisi oleh user pada form register.html

password = request.form['password'].encode('utf-8')
hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
Mendapatkan data password yang diisi oleh user pada form register.html, sebelum dienkripsi password terlebih dahulu dibuah fotmatnya menjadi UTF-8 kemudian dienkripsi menggunakan bcrypt.hashpw

 cur = mysql.connection.cursor()
 cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(name,email,hash_password,))
 mysql.connection.commit()
Membuka koneksi ke mysql kemudian mengeksekusi query INSERT

session['name'] = request.form['name']
session['email'] = request.form['email']
Setelah melakukan penambahan data pada tabel selanjutnya membuat session user

return redirect(url_for('home'))
Meredirect user ke halaman home.html

app.secret_key = "^A%DJAJU^JJ123"
Secret key untuk keamanan enkripsi menggunakan bcrypt (silahkan ganti sesuai keiinginan anda)


Membuat Python Flask Login Authentication

Membuat login.html dalam folder templates

{% extends 'layout.html' %}

{% block title %} Login {% endblock %}

{% block content %}
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="/login" method="POST">
<div class="form-group">
<label>Email:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" name="password">
</div>
<div class="form-group">
<button class="btn btn-primary">Login</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}


Membuat route login pada app.py





@app.route('/login',methods=["GET","POST"])
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password'].encode('utf-8')

        curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        curl.execute("SELECT * FROM users WHERE email=%s",(email,))
        user = curl.fetchone()
        curl.close()

        if len(user) > 0:
            if bcrypt.hashpw(password, user["password"].encode('utf-8')) == user["password"].encode('utf-8'):
                session['name'] = user['name']
                session['email'] = user['email']
                return render_template("home.html")
            else:
                return "Error password and email not match"
        else:
            return "Error user not found"
    else:
        return render_template("login.html")


Penjelasan kode program
@app.route('/login',methods=["GET","POST"])
def login():
Membuat route login dan def login dengan method GET dan POST

if request.method == 'POST':
Pengecekan method, jika method yang digunakan adalah POST maka lakukan aksi login jika bukan maka tampilkan halaman login.html


email = request.form['email']
password = request.form['password'].encode('utf-8')
Mendapatkan data email dan password dari form login pada login.html

curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
Membuka koneksi ke mysql

curl.execute("SELECT * FROM users WHERE email=%s",(email,))
Mengeksekusi query SELECT

user = curl.fetchone()
Mendapatkan data hasil query dan menampungnya kedalam variabel user

curl.close()
Menutup koneksi mysql

if len(user) > 0:
Jika jumlah data hasil query lebih dari 1 maka lakukan aksi selajutnya (pengecekan password form dengan password pada tabel), jika tidak maka tampilkan error "Error user not found"

if bcrypt.hashpw(password, user["password"].encode('utf-8')) == user["password"].encode('utf-8'):
Jika data password pada form sama dengan password pada tabel maka buat session login, jika tidak maka tampilkan error "Error password and email not match"

session['name'] = user['name']
session['email'] = user['email']
Membuat session login user

return render_template("home.html")
Meredirect user ke halaman home setelah proses login selesai / berhasil

Membuat route logout

@app.route('/logout')
def logout():
    session.clear()
    return render_template("home.html")


Penjelasan kode program
    session.clear()
Membersihkan session pada browser


Flask mysql user authentication
Flask mysql user authentication

Script lengkap app.py
#app.py

from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL,MySQLdb
import bcrypt

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)

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

@app.route('/login',methods=["GET","POST"])
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password'].encode('utf-8')

        curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        curl.execute("SELECT * FROM users WHERE email=%s",(email,))
        user = curl.fetchone()
        curl.close()

        if len(user) > 0:
            if bcrypt.hashpw(password, user["password"].encode('utf-8')) == user["password"].encode('utf-8'):
                session['name'] = user['name']
                session['email'] = user['email']
                return render_template("home.html")
            else:
                return "Error password and email not match"
        else:
            return "Error user not found"
    else:
        return render_template("login.html")

@app.route('/logout', methods=["GET", "POST"])
def logout():
    session.clear()
    return render_template("home.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'].encode('utf-8')
        hash_password = bcrypt.hashpw(password, bcrypt.gensalt())

        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(name,email,hash_password,))
        mysql.connection.commit()
        session['name'] = request.form['name']
        session['email'] = request.form['email']
        return redirect(url_for('home'))

if __name__ == '__main__':
    app.secret_key = "^A%DJAJU^JJ123"
    app.run(debug=True)


Video Tutorial Python Flask Login & Register MYSQL database


2 comments:

Powered by Blogger.