article

Friday, October 23, 2020

Flask Login using flask_login module with flask_wtf and remember me and check_password_hash

Login Flask using flask_login module with flask_wtf and remember me and check_password_hash

Database Table

CREATE TABLE user (

id INTEGER PRIMARY KEY AUTOINCREMENT,

username VARCHAR (64),

email VARCHAR (120),

password_hash VARCHAR (128)

);


install module flask_login module

ModuleNotFoundError: No module named 'flask_login' = (venv) C:\flaskmyproject>pip install flask_login


install flask_sqlalchemy module

ModuleNotFoundError: No module named 'flask_sqlalchemy' = (venv) C:\flaskmyproject>pip install Flask-SQLAlchemy


install flask_wtf module

pip install Flask-WTF


app.py



#app.py
from flask import Flask, render_template, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy 
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
#ModuleNotFoundError: No module named 'flask_sqlalchemy' = (venv) C:\flaskmyproject>pip install Flask-SQLAlchemy
#ModuleNotFoundError: No module named 'flask_login' = (venv) C:\flaskmyproject>pip install flask_login
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
from werkzeug.security import generate_password_hash, check_password_hash

#import sqlite3
 
app = Flask(__name__)
#conn = sqlite3.connect('flask_login.db')
#print("Opened database successfully");

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flask_login.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
 
    def __repr__(self):
        return ''.format(self.username)  
   
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
 
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
	
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@login_manager.unauthorized_handler
def unauthorized_callback():
    return redirect('/login')
	
@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('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)
	
@app.route('/home')
@login_required
def home():
    return 'The current user is ' + current_user.username 	

@app.route('/profile')
@login_required
def profile():
    return render_template('profile.html')
	
@app.route('/logout')
@login_required
def logout():
    logout_user()
    return 'You are now logged out!'
	
if __name__ == '__main__':
 app.run(debug=True)
 
templates/login.html
//templates/login.html
<html lang="en">
<head>
<title>Login</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <div id="login">
        <h3 class="text-center text-white pt-5">Login Flask using flask_login module with flask_wtf and remember me and check_password_hash</h3>
        <div class="container">
            <div id="login-row" class="row justify-content-center align-items-center">
                <div id="login-column" class="col-md-6">
                    <div id="login-box" class="col-md-12">
			<form id="login-form" class="form" action="" method="post" novalidate>
					{{ form.hidden_tag() }}
					<div class="form-group">
						{{ form.username.label }}<br>
						{{ form.username(size=32, class_="form-control") }}
						{% for error in form.username.errors %}
						<span style="color: red;">[{{ error }}]</span>
						{% endfor %}
					</div>
					<div class="form-group">
						{{ form.password.label }}<br>
						{{ form.password(size=32, class_="form-control") }}
						{% for error in form.password.errors %}
						<span style="color: red;">[{{ error }}]</span>
						{% endfor %}
					</div>
					<p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
					<p>{{ form.submit(class_="btn btn-success") }}</p>
			</form>
				</div>
                </div>
            </div>
        </div>
    </div>
<style>
body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8;
}
#login .container #login-row #login-column #login-box {
  margin-top: 120px;
  max-width: 600px;
  height: 350px;
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form #register-link {
  margin-top: -85px;
}
</style>
  </body>
</html>
templates/index.html
//templates/index.html
<html lang="en">
    <head>
        <meta charset="utf-8">
		<title>Index</title>
    </head>
    <body>
<div>
    <a href="{{ url_for('index') }}">Home</a>
    {% if current_user.is_anonymous %}
    <a href="{{ url_for('login') }}">Login</a>
    {% else %}
    <a href="{{ url_for('logout') }}">Logout</a>
    {% endif %}
</div>
<h1>Hi, {{ current_user.username }}!</h1>
<p>password hash, {{ hash }}</p>
<p>check password hash, {{ check_hash }}</p>
    </body>
</html>
templates/profile.html
//templates/profile.html
<html lang="en">
    <head>
        <meta charset="utf-8">
		<title>profile</title>
    </head>
    <body>
<div>
    <a href="{{ url_for('index') }}">Home</a>
    {% if current_user.is_anonymous %}
    <a href="{{ url_for('login') }}">Login</a>
    {% else %}
    <a href="{{ url_for('logout') }}">Logout</a>
    {% endif %}
</div>
<h1>Hi, {{ current_user.username }}!</h1>
    </body>
</html>

Related Post