Authentication
When working with the an admin side theme, authentication is amongst the most important thing, as you do not want to allow some random person to access you admin panel.
In this guide we will learn how the authentication has been implemented in the cuba theme.
Create a Model for user authentication.
To store the data of the users we will create a table that stores the information of the users.
Create User Model
from flask_login import UserMixin
from . import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer,primary_key = True)
username = db.Column(db.String(20),unique=True,nullable=False)
email = db.Column(db.String(120),unique=True,nullable=False)
password = db.Column(db.String(60),nullable=False)
isAdmin = db.Column(db.Boolean,default=False)
def __repr__(self):
return f"User('{self.username}','{self.email}')"
Notice that we have added a field isAdmin to differentiate super admins from other users.
Now run the following sequence of commands in python terminal, you can start python terminal by typing
python3 (if you are a linux user) or python (if you are a windows user) in your
terminal and pressing enter:
from cuba import db
db.create_all()
exit()
If you get any problem while creating the new table in the database, then try deleting the cuba.db and run the above sequence of command once again.
User Registration
Now that we have created user table in the database, we are now ready to enter new user in the table.
Registration form HTML code
<div class="login-card">
<form class="theme-form login-form theme-login-form" method="POST" action="/signUp">
<h4>Create your account</h4>
<p>Enter your personal details to create account</p>
<div class="form-group">
<label class="col-form-label pt-0">Username</label>
<input class="form-control" type="text" required="" name="username" placeholder="Username">
</div>
<div class="form-group">
<label class="col-form-label">Email Address</label>
<input class="form-control" type="email" required="" name="email" placeholder="Test@gmail.com">
</div>
<div class="form-group">
<label class="col-form-label">Password</label>
<div class="form-input position-relative">
<input class="form-control" type="password" name="password" required="" placeholder="*********">
<div class="show-hide"><span class="show"></span></div>
</div>
</div>
<div class="form-group mb-0">
<button class="btn btn-primary btn-block w-100" type="submit">Create Account</button>
</div>
<p class="mt-4 mb-0">Already have an account?<a class="ms-2" href="/login">Sign in</a></p>
</form>
</div>
Now we need to get the data in the backend and store it in the database. Below given code will do that for
us, you have to add it in auth.py file, as we will write all our authentication related code
here.
Registration python code
from flask import Blueprint,render_template,redirect,request,flash
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import login_user,logout_user,login_required
from .models import User
from cuba import db
@auth.route('/signUp')
def signUp():
return render_template('pages/others/authentication/sign-up-simple/sign-up.html')
@auth.route('/signUp',methods=['POST'])
def signUpPost():
email = request.form.get('email')
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if user:
flash('Email Already Exists')
return redirect('/signUp')
new_user = User(email=email,username = username,password = generate_password_hash(password, method="sha256"))
db.session.add(new_user)
db.session.commit()
return redirect('/login')
User Login
Now that we have registered the user, we need to make a login system to allow only the registered user to access the site.
User login Form HTML
<div class="login-main">
<form class="theme-form login-form theme-login-form w-100 p-0" method="post" action="/login">
<h4>Sign in to account</h4>
<p>Enter your email & password to login</p>
<div class="form-group">
<label class="col-form-label">Email Address</label>
<input class="form-control" type="email" required="" name="email" value="test@gmail.com"
placeholder="Test@gmail.com">
</div>
<div class="form-group">
<label class="col-form-label">Password</label>
<div class="form-input position-relative">
<input class="form-control" type="password" name="password" value="test@123" required=""
placeholder="*********">
<div class="show-hide"><span class="show"> </span></div>
</div>
</div>
<div class="form-group mb-0">
<div class="checkbox p-0">
<input id="checkbox1" type="checkbox" name="remember">
<label class="text-muted" for="checkbox1">Remember password</label>
</div>
<div class="text-end mt-3">
<button class="btn btn-primary btn-block w-100" type="submit">Sign in</button>
</div>
</div>
<h6 class="text-muted mt-4 or">Or Sign in with</h6>
<div class="social mt-4">
<div class="btn-showcase"><a class="btn btn-light" href="https://www.linkedin.com/login"
target="_blank"><i class="txt-linkedin" data-feather="linkedin"></i> LinkedIn </a><a
class="btn btn-light" href="https://twitter.com/login?lang=en" target="_blank"><i
class="txt-twitter" data-feather="twitter"></i>twitter</a><a class="btn btn-light"
href="https://www.facebook.com/" target="_blank"><i class="txt-fb"
data-feather="facebook"></i>facebook</a></div>
</div>
<p class="mt-4 mb-0 text-center">Don't have account?<a class="ms-2" href="/signUp">Create Account</a></p>
</form>
</div>
After Creating login form we will write the logic for logging in users
Code for user login is in the page auth.py
User login python Code
next_page = '/'
@auth.route('/login')
def login():
global next_page
next = request.args.get('next')
if next:
next_page = next
else:
next_page = '/'
return render_template('pages/others/authentication/login/login.html')
@auth.route('/login',methods=['POST','GET'])
def login_post():
global next_page
email = request.form.get('email')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
user = User.query.filter_by(email=email).first()
if user and check_password_hash(user.password,password):
login_user(user,remember=remember)
if next_page:
return redirect(next_page)
else:
return redirect('/index')
else:
flash('please Check you login details and try again!')
return redirect('/login')
Now that we have integrated authentication system ,we need to provide on which paths this authentication should apply.
To do that we need to add login required decorator on to of every path and give the default path where the app will redirect if login is unsuccessful.
We will first setup the default path in __init__.py file:
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
After that we will add the login_required decorators on all paths that requires
authentication, we will add
this in routes.py file:
from flask_login import login_required
@main.route('/')
@login_required
def homePage():
return redirect('/index')
This is how we add the login_required decorator above the funciton. Make sure that you add the decorator below the page path.
And we are now ready to authenticate user.