article

Sunday, August 2, 2020

Python Flask Mysqldb Simple Login Register and Logout



Python Flask Mysqldb Simple Login Register and Logout

Database Table

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES
(1, 'Cairocoders', 'cairocoders@gmail.com', '$2b$12$7RXKIh40P94SdbmrKZH2V.UjbZoAMJ7tVfOQ4zc1nkGGC8ypaSyma');




app.py
 
#app.py
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
import bcrypt #pip install bcrypt https://pypi.org/project/bcrypt/

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan-2020"

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'))

@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')
def logout():
    session.clear()
    return render_template("home.html")
	
if __name__ == '__main__':
    app.run(debug=True)
templates/layout.html
//templates/layout.html
<!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>
templates/home.html
//templates/home.html
{% extends 'layout.html' %}
{% block title %} Home {% endblock %}
{% block content %}
<div class="container">
 <div class="row">
 <div class="col-md-6 col-md-offset-3"><h1>
Home page
{% if session['name'] %}
Welcome {{ session['name'] }}
{% else %}
Not login
{% endif %}</h1>
 </div>
 </div>
</div>
{% endblock %}
templates/register.html
//templates/register.html
{% 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 %}
templates/login.html
//templates/login.html
{% 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 %}

Related Post