article

Wednesday, November 11, 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

MongoDB Compass Download https://www.mongodb.com/try/download/compass

create a file called app.py

ModuleNotFoundError: No module named 'flask_mongoengine'

install module flask_mongoengine
(venv) C:\flaskmyproject>pip install flask-mongoengine

create database table
table name user
name = StringField
email = StringField
password = StringField
reg_date = DateTimeField

app.py
#app.py
from flask import Flask, render_template, request, json, redirect, session
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

app = Flask(__name__)
app.secret_key = "caircocoders-ednalan-2020"

app.config['MONGODB_SETTINGS'] = {
    'db': 'dbmongocrud',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)

class User(db.Document):
    name = db.StringField()
    email = db.StringField()
    password = db.StringField()
    reg_date = db.DateTimeField(datetime.now)
	
@app.route('/')
def main():
    return render_template('index.html')
	
@app.route('/signUp',methods=['POST','GET'])
def signUp():	
    today = datetime.today()	
    #print(today)
    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)
            users = User.objects(email=_email).first()
            if not users:
                usersave = User(name=_name, email=_email, password=_hashed_password, reg_date=today)
                usersave.save()
                msg =  '{ "html":"ok"}'
                msghtml = json.loads(msg)
                return msghtml["html"]
            else:
                msg =  '{ "html":"

A user with this email address already exists

"}' msghtml = json.loads(msg) return msghtml["html"] 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'] # Get user by username users = User.objects(email=_username).count() print(users) # result 1 if users > 0: # Get stored hash user_rs = User.objects(email=_username).first() password = user_rs['password'] print(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) else: error = 'Username not found' return render_template('signin.html', error=error) return render_template('signin.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('/') if __name__ == '__main__': app.run(debug=True)
templates/signup.html
//templates/signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask MongoDB Login Register logout with Jquery ajax 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>Python Flask MongoDB Login Register logout with Jquery ajax 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>
<style>
#message h3 {
	border:1px #a81b2f solid;padding:5px;
}
</style>	
  </body>
</html>
templates/signin.html
//templates/signin.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask MongoDB Login Register logout with Jquery ajax 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>Python Flask MongoDB Login Register logout with Jquery ajax and password hash</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>
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>

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>
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); alert(response)
				$('#message').html(response);
				if(response == 'ok'){
					window.location.href = '/login';
				}
            },
            error: function(error) {
                console.log(error);
				$('#message').html(error);
            }
        });
    });
});

Related Post