article

Tuesday, January 26, 2021

Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session

Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session

--
-- Table structure for table `admin_login`
--

CREATE TABLE `admin_login` (
  `admin_id` int(11) NOT NULL,
  `admin_name` varchar(250) NOT NULL,
  `admin_password` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `admin_login`
--

INSERT INTO `admin_login` (`admin_id`, `admin_name`, `admin_password`) VALUES
(1, 'admin', 'pbkdf2:sha256:150000$FXLDgm3a$bd46f6b7b44124a523f9566d03bf110ba2ebf28bfd3522faeddd56eabebcb7f5');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `admin_login`
--
ALTER TABLE `admin_login`
  ADD PRIMARY KEY (`admin_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `admin_login`
--
ALTER TABLE `admin_login`
  MODIFY `admin_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

app.py
#app.py
from flask import Flask, render_template, request, jsonify, flash, 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"
        
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)

@app.route('/')
def index():
    hash = generate_password_hash('cairocoders')
    check_hash = check_password_hash(hash, 'cairocoders')   
    return render_template('index.html', hash=hash, check_hash=check_hash)

@app.route("/action",methods=["POST","GET"])
def action(): 
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print(username)
        print(password)
        result = cur.execute("SELECT * FROM admin_login WHERE admin_name = %s ", [username])
        print(result)
        if result > 0:
            data = cur.fetchone()
            rs_password = data['admin_password']
            print(rs_password)
            if check_password_hash(rs_password, password):
                session['logged_in'] = True
                session['username'] = username
                msg = 'success'
            else:
               msg = 'No-data'
        else:
            msg = 'No-data'    
    return jsonify(msg)   

@app.route('/logout')
def logout():
    session.clear()
    return redirect('/')

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>  
 <html>  
<head>  
<title>Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session</title>  
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>  
<body>  
<div class="container" style="width:700px;">  
                <h3 align="center">Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session</h3><br />  
                <br />  
                <br />  
                <!--<p>hash : {{ hash }}</p>
                <p>hash : {{ check_hash }}</p> -->
                <br />  
                <br />  
                <br />  
                {% if session.logged_in %}
                <div align="center">  
                     <h1>Welcome - {{session.username}}</h1><br />  
                     <a href="/logout">Logout</a>  
                </div>  
                {% else %}  
                <div align="center">  
                     <a data-target="#myModal" role="button" class="btn btn-warning" data-toggle="modal"><span class="glyphicon glyphicon-hand-up"></span>Login</a>
                </div>  
                {% endif %} 
           </div>  
           <br />  
		   	
 <div id="myModal" class="modal fade">  
      <div class="modal-dialog">  
   <!-- Modal content-->  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">×</button>  
                     <h4 class="modal-title">Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session</h4>  
                </div>  
                <div class="modal-body">  
                     <label>Username</label>  
                     <input type="text" name="username" id="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" id="password" class="form-control" />  
                     <br />  
                     <button type="button" name="login_button" id="login_button" class="btn btn-warning">Login</button>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#login_button').click(function(){  
           var username = $('#username').val();  
           var password = $('#password').val();  
           if(username != '' && password != '')  
           {  
                $.ajax({  
                     url:"/action",  
                     method:"POST",  
                     data: {username:username, password:password},  
                     success:function(data)  
                     {  
                          alert(data);  
                          if(data == 'No-data')  
                          {  
                               alert("Invalid Email Or Password!");  
                          }  
                          else  
                          {  
                               $('#loginModal').hide();  
                               location.reload();  
                          }  
                     }  
                });  
           }  
           else  
           {  
                alert("Both Fields are required");  
           }  
      });    
 });  
 </script>   
      </body>  
 </html>  

Related Post