article

Thursday, October 8, 2020

Python Flask MongoDB Login Register logout with Jquery ajax and password hash

 


Python Flask MongoDB Login Register logout with Jquery ajax and password hash

create a file called app.py

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;


 
#app.py
from flask import Flask, render_template, json, request, redirect, session
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.security import generate_password_hash, check_password_hash

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 main():
    return render_template('index.html')

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

@app.route('/logout')
def logout():
    session.pop('sessionusername', None)
    return redirect('/')
	
@app.route('/signUp',methods=['POST','GET'])
def signUp():
    if request.method == 'POST':
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']
        # validate the received values
        if _name and _email and _password:
            _hashed_password = generate_password_hash(_password)
            curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
            curl.execute("SELECT * FROM users WHERE email=%s",(_email,))
            user = curl.fetchone()
            #print(user)
            if user is None:		
                curl.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(_name,_email,_hashed_password,))
                mysql.connection.commit()
                curl.close()
                return json.dumps({'message':'User created successfully !'})
            else:
                return json.dumps({'html':'A user with this email address already exists'})
        else:
            msg =  '{ "html":"Enter the required fields"}'
            msghtml = json.loads(msg)
            return msghtml["html"]
    else:
        return render_template("signup.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Get Form Fields
        _username = request.form['inputEmail']
        _password = request.form['inputPassword']
  
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
  
        # Get user by username
        result = cur.execute("SELECT * FROM users WHERE email = %s", [_username])
  
        if result > 0:
            # Get stored hash
            data = cur.fetchone()
            password = data['password']
  
            # Compare Passwords 
            if check_password_hash(password, _password):
                # Passed
                session['sessionusername'] = _username
                return redirect('/userHome')
            else:
                error = 'Invalid login'
                return render_template('signin.html', error=error)
            # Close connection
            cur.close()
        else:
            error = 'Username not found'
            return render_template('signin.html', error=error)
  
    return render_template('signin.html')
         
if __name__ == '__main__':
    app.run(debug=True)
Home Page
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.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="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
        <div class="jumbotron">
            <h2>Login Register logout with Jquery ajax, json and MySQLdb and password hash</h2>
            <p class="lead"></p>
            <p><a class="btn btn-lg btn-success" href="signUp" role="button">Sign Up</a>
            </p>
        </div>
        <div class="row marketing">
            <div class="col-lg-6">
                <h4>Blog 1</h4>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
            <hr>
            <div class="col-lg-6">
                <h4>Blog 1</h4>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
        </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>
Sign Up page
templates/signup.html
//templates/signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.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" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h2>Login Register logout with Jquery ajax, json and MySQLdb and password hash</h2>
		<div id="message"></div>
        <form class="form-signin">
        <p><label for="inputName" class="sr-only">Name</label>
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus></p>
        <p><label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p>
        <p><label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p>
        <p><button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button></p>
      </form>
      </div>
      <footer class="footer">
         <p>©tutorial101.blogspot.com</p>
      </footer>
    </div>
  </body>
</html>
Jquery Ajax static/js/signUp.js
//static/js/signUp.js
$(function() {
    $('#btnSignUp').click(function() {
        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
				$('#message').html(response);
            },
            error: function(error) {
                console.log(error);
				$('#message').html(error);
            }
        });
    });
});
Login Page
templates/signin.html
//templates/signin.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.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="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h2>Login Register logout with Jquery ajax and json</h2>
		{% if error %}
		  <div class="alert alert-danger">{{error}}</div>
		{% endif %}
        <form class="form-signin" action="/login" method="post">
        <p><label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p>
        <p><label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p>
        
        <p><button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button></p>
      </form>
      </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
  </body>
</html>
Userhome page
templates/userHome.html
//templates/userHome.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.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="/userHome">Dashboard</a></li>
                    <li role="presentation"><a href="/logout">Log Out</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h1>Dashboard <small> Welcome {{session.sessionusername}}</small></h1>
      </div>      
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>
Error Page
templates/error.html
templates/error.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Unauthorized Access</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.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="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">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>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>

Related Post