BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Flask blog app tutorial 2 : Sign-In / Sign-Out

Python-Flask.png




Bookmark and Share





bogotobogo.com site search:



Note

In the previous part of this series, we implemented the user registration. In this page, we'll be implementing the sign-in and sign-out.

Here are the files we'll be using in this tutorial part-2:

tree-p2.png

They are available from FlaskApp/p2







Sign-In : templates/signin.html

Let's create a signin.html file under templates folder:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Python Flask Bucket List App</title>
   
    <link href="//getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="//getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="/static/css/signup.css" rel="stylesheet">
    <script src="/static/js/jquery-3.1.1.js"></script>
    <script src="/static/js/signUp.js"></script>
   
  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation" ><a href="/">Home</a></li>
            <li role="presentation" class="active"><a href="#">Sign In</a></li>
            <li role="presentation" ><a href="/showSignUp">Sign Up</a></li>
          </ul>
        </nav>
        <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ >
      </div>

      <div class="jumbotron">
        <h1>Blog App</h1>
        <form class="form-signin" action="/validateLogin" method="post">
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>
        
        <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      </form>
      </div>

      <footer class="footer">
        <p>©etaman.com 2017</p>
      </footer>

    </div>
  </body>
</html>




Sign-In : app.py

We need to add a new route for the sign-in interface:

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

And with index.html:

...
<div class="header">
    <nav>
        <ul class="nav nav-pills pull-right">
            <li role="presentation" class="active"><a href="#">Home</a>
            </li>
            <li role="presentation"><a href="/showSignin">Sign In</a>
            </li>
            <li role="presentation"><a href="/showSignUp">Sign Up</a>
            </li>
        </ul>
    </nav>
    <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
</div>
...

Also, in signup.html:

<div class="header">
<nav>
  <ul class="nav nav-pills pull-right">
    <li role="presentation" ><a href="/">Home</a></li>
    <li role="presentation"><a href="/showSignin">Sign In</a></li>
    <li role="presentation" class="active"><a href="#">Sign Up</a></li>
  </ul>
</nav>
<img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ >
</div>

ShowSignIn.png



Creating a Stored Procedure for validation

Now, we need to create function to validate the user login. At Sign-In, we'll post the input for the email address and password to the validation function.

To validate a user, we need a MySQL stored procedure. So, let's create it:

mysql> use FlaskBlogApp;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> DELIMITER $$
mysql> CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_validateLogin`(
    -> IN p_username VARCHAR(20)
    -> )
    -> BEGIN
    ->     select * from blog_user where user_username = p_username;
    -> END$$
Query OK, 0 rows affected (0.26 sec)

mysql> DELIMITER ;

mysql> SHOW PROCEDURE STATUS WHERE db = 'FlaskBlogApp';
+--------------+------------------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db           | Name             | Type      | Definer        | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+--------------+------------------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| FlaskBlogApp | sp_createUser    | PROCEDURE | root@localhost | 2016-12-02 21:50:34 | 2016-12-02 21:50:34 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_validateLogin | PROCEDURE | root@localhost | 2016-12-03 11:09:38 | 2016-12-03 11:09:38 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+--------------+------------------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
2 rows in set (0.01 sec)

We'll get the user details based on the username from the MySQL database using sp_validateLogin. Once we have the hashed password we'll validate it against the password entered by the user.





User-Validation

Let's create a method for the user validation which we'll call when the user submits the form:

@app.route('/validateLogin',methods=['POST'])
def validateLogin():
    try:
        _username = request.form['inputEmail']
        _password = request.form['inputPassword']
               
        # connect to mysql
        con = mysql.connect()
        cursor = con.cursor()
        cursor.callproc('sp_validateLogin',(_username,))
        data = cursor.fetchall()

        if len(data) > 0:
            if check_password_hash(str(data[0][3]),_password):
                session['user'] = data[0][0]
                return redirect('/userHome')
            else:
                return render_template('error.html',error = 'Wrong Email address or Password.')
        else:
            return render_template('error.html',error = 'Wrong Email address or Password.')          

    except Exception as e:
        return render_template('error.html',error = str(e))
    finally:
        cursor.close()
        con.close()

In the above code, we read the posted email address and password into _username and _password. Now we need to call the sp_validateLogin procedure with the parameter _username. So, create a MySQL connection inside the validateLogin() method.

con = mysql.connect()
cursor = con.cursor()
cursor.callproc('sp_validateLogin',(_username,))
data = cursor.fetchall()

As we can see from the snippet, we create the connection and then a cursor using the con connection. Using the cursor, call the MySQL stored procedure (sp_validateLogin). After that we get the fetched records from the cursor.

If the data has some records (len(data) > 0), we'll match the retrieved password against the password entered by the user:

if len(data) > 0:
   if check_password_hash(str(data[0][3]),_password):
      session['user'] = data[0][0]
      return redirect('/userHome')
   else:
      return render_template('error.html',error = 'Wrong Email address or Password.')
else:
   return render_template('error.html',error = 'Wrong Email address or Password.')

In the code above, we call check_password_hash() to check if the returned hash password matches the password entered by the user. If all is good then we'll redirect the user to userHome.html. And if there is any error, we'll display error.html with the error message.





templates/userHome.html

Here is the templates/userHome.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Python Flask Bucket List App</title>
   
    <link href="//getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="//getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="/static/css/signup.css" rel="stylesheet">
    <script src="/static/js/jquery-3.1.1.js"></script>
      
  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation" class="active"><a href="/logout">Logout</a></li>
          </ul>
        </nav>
        <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ >
      </div>

      <div class="jumbotron">
        <h1>Welcome Home !!</h1>
       
      </div>      

      <footer class="footer">
        <p>©etaman.com 2017</p>
      </footer>

    </div>
  </body>
</html>




templates/error.html

Here is the error page, error.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Unauthorized Access:: Flask Blog App</title>
  
    <link href="//getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="//getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="/static/css/signup.css" rel="stylesheet">
       
  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
           <ul class="nav nav-pills pull-right">
            <li role="presentation" class="active"><a href="#">Home</a></li>
            <li role="presentation"><a href="/showSignin">Sign In</a></li>
 	    <li role="presentation"><a href="/showSignUp">Sign Up</a></li>
          </ul>
        </nav>
        <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ >
      </div>

      <div class="jumbotron">
        <h1>{{error}}</h1>        
      </div>
      
      <footer class="footer">
        <p>©etaman.com 2017</p>
      </footer>

    </div>
  </body>
</html>

Inside error.html we have an element as the following:

<h1>{{error}}</h1>

The value for the variable error can be passed from the render_template() and can be set dynamically.

When the user signed-in successfully, the user should be redirected to the user's home page, so we need to create a route called /userHome in app.py:

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





Home page after sign in

Let's restart the server, then click on the "Sign In" button in the home page. On successful user validation, we should have a page as shown below:

WelcomeHomeAfterSignIn.png

If we type wrong email or passoword, we get the following error page:

WrongEmailAddressOrPassword.png



Logout

In order to implement the logout functionality, we need to do the following two things:

  1. make the session variable user null.
  2. redirect the user to the main page.

Let's create a new route and method for logout() in app.py:

@app.route('/logout')
def logout():
    session.pop('user', None)
    return redirect('/')

After signed in, click on the "Logout" button in user home and we get the following user's home page after logged out:

AfterLogOut.png



app.py

Here is the app.py file:

from flask import Flask, render_template, json, request, redirect, session
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

mysql = MySQL()
app = Flask(__name__)
app.secret_key = 'spooky action at a distance-Einstein'

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'khong'
app.config['MYSQL_DATABASE_PASSWORD'] = 'khong'
app.config['MYSQL_DATABASE_DB'] = 'FlaskBlogApp'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

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

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

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

@app.route('/userHome')
def userHome():
    if session.get('user'):
        return render_template('userHome.html')
    else:
        return render_template('error.html',error = 'Unauthorized Access')

@app.route('/logout')
def logout():
    session.pop('user', None)
    return redirect('/')

@app.route('/validateLogin',methods=['POST'])
def validateLogin():
    try:
        _username = request.form['inputEmail']
        _password = request.form['inputPassword']
               
        # connect to mysql
        con = mysql.connect()
        cursor = con.cursor()
        cursor.callproc('sp_validateLogin',(_username,))
        data = cursor.fetchall()

        if len(data) > 0:
            if check_password_hash(str(data[0][3]),_password):
                session['user'] = data[0][0]
                return redirect('/userHome')
            else:
                return render_template('error.html',error = 'Wrong Email address or Password.')
        else:
            return render_template('error.html',error = 'Wrong Email address or Password.')          

    except Exception as e:
        return render_template('error.html',error = str(e))
    finally:
        cursor.close()
        con.close()

@app.route('/signUp',methods=['POST','GET'])
def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:
            
            # All Good, let's call MySQL
            
            conn = mysql.connect()
            cursor = conn.cursor()
            _hashed_password = generate_password_hash(_password)
            cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
            data = cursor.fetchall()

            if len(data) is 0:
                conn.commit()
                return json.dumps({'message':'User created successfully !'})
            else:
                return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'Enter the required fields'})

    except Exception as e:
        return json.dumps({'error':str(e)})
    finally:
        cursor.close() 
        conn.close()

if __name__ == "__main__":
    app.run(port=5000)









Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong








Flask



Deploying Flask Hello World App with Apache WSGI on Ubuntu 14

Flask Micro blog "Admin App" with Postgresql

Flask "Blog App" with MongoDB - Part 1 (Local via Flask server)

Flask "Blog App" with MongoDB on Ubuntu 14 - Part 2 (Local Apache WSGI)

Flask "Blog App" with MongoDB on CentOS 7 - Part 3 (Production Apache WSGI )

Flask word count app 1 with PostgreSQL and Flask-SQLAlchemy

Flask word count app 2 via BeautifulSoup, and Natural Language Toolkit (NLTK) with Gunicorn/PM2/Apache

Flask word count app 3 with Redis task queue

Flask word count app 4 with AngularJS polling the back-end

Flask word count app 5 with AngularJS front-end updates and submit error handling

Flask word count app 0 - Errors and Fixes

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

Flask AJAX with jQuery

Flask blog app with Dashboard 1 - SignUp page

Flask blog app with Dashboard 2 - Sign-In / Sign-Out

Flask blog app with Dashboard 3 - Adding blog post item

Flask blog app with Dashboard 4 - Update / Delete

Flask blog app with Dashboard 5 - Uploading an image

Flask blog app with Dashboard 6 - Dash board

Flask blog app with Dashboard 7 - Like button

Flask blog app with Dashboard 8 - Deploy

Flask blog app with Dashboard - Appendix (tables and mysql stored procedures/functions

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master