Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Flask-Login Example to Build User Authentication System With Logout Using HTML5 Templates in Browser

Posted on January 6, 2023

 

 

Welcome folks today in this blog post we will be building a user authentication system with login and logout system in flask using flask-login library. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to install the flask library using the pip command as shown below

 

 

pip install flask

 

 

And now you need to install the flask-login library using the pip command as shown below

 

 

pip install flask-login

 

 

And after that you need to see the directory structure of the flask app as shown below

 

 

 

 

 

And now as you can see we have the templates folder inside which we are having the html template files for rendering the login page and logout page. And also we have the protected page template where we redirect the user when they are successfully authenticated with the correct email and password.

 

 

Now we need to create the app.py file where we start the basic flask app and then include the flask_login authentication app as shown below

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
from flask import Flask, render_template, request, redirect, url_for
from flask_login import LoginManager, login_user, logout_user, login_required
 
app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)
 
 
if __name__ == "__main__":
    app.secret_key = "secret"
    app.run(debug=True)

 

 

As you can see we are importing the flask and flask_login libraries at the top and then we are starting the LoginManager() and passing it inside the flask app. And then we are starting out the flask app using the run() method and also before that we are setting the secret key.

 

 

And now we will declaring the dummy users with username and password. We will be declaring a simple dictionary of users as shown below

 

 

Python
1
2
3
4
5
6
7
# a dummy list of users
users = {
    'geekygautam1997@gmail.com': {'password': '123456'},
    'gauti123456@mail.com': {'password': '123456789'},
    'john@gmail.com': {'password': 'john123456'},
    'smith@gmail.com': {'password': 'smith123456'}
}

 

 

And now we need to make the User class inside that we will be declare the various methods of the user authentication as shown below

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class User:
    def __init__(self, email):
        self.email = email
 
    def is_authenticated(self):
        return True
 
    def is_active(self):
        return True
 
    def is_anonymous(self):
        return False
 
    def get_id(self):
        return self.email

 

 

And now we will be assigning the middleware where we will be checking if the email is valid one or not. If the email is valid one then we are inserting that user inside the login system as shown below

 

 

Python
1
2
3
4
5
6
@login_manager.user_loader
def load_user(email):
    if email not in users:
        return "email not exist"
    user = User(email)
    return user

 

 

Making the Login Template

 

 

Now we will be loading the login template where we will be opening the /login route and after that we will be opening the login.html template file which will be stored inside the templates folder as shown below

 

 

Python
1
2
3
@app.route('/login', methods=['GET', 'POST'])
def login():
    return render_template('login.html')

 

 

templates/login.html

 

 

1
2
3
4
5
6
7
<form method="post">
    <label for="email">Email:</label><br>
    <input type="email" id="email" name="email"><br>
    <label for="password">Password:</label><br>
    <input type="password" id="password" name="password"><br><br>
    <input type="submit" value="Submit">
</form>

 

 

As you can see we have the simple html5 login form where we have the input fields for taking the user input for email and password and then we have the submit button to submit the form. And now if you go to the /login route you will see the below login.html file as shown below

 

 

 

 

And now we will be handling the form submit event where user will be redirected to the /protected route. For this you need to add this code inside the login() method as shown below

 

 

Python
1
2
3
4
5
6
7
8
9
10
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        if request.form['password'] == users[email]['password']:
            user = User(email)
            login_user(user)
            return redirect(url_for('protected'))
 
    return render_template('login.html')

 

 

As you can see in the above code we are checking if the method is equal to POST or not and then we are getting the value of the email and then we are comparing the password which is submitted by user. If that password exist inside the dictionary then we will redirect them to the /protected route. And also inserting it inside the login system using the login_user() method.

 

 

Rendering the Protected Route

 

 

Now we will be loading the protected.html template file whenever we redirect the user after the successful authentication of the user. Inside that we have also the @login_required decorator it means that for this route the user must be validated

 

 

Python
1
2
3
4
@app.route('/protected')
@login_required
def protected():
    return render_template('protected.html')

 

 

And now we need to make the protected.html file inside the templates folder to show the logged_in user and also to show the logout button as shown below

 

 

templates/protected.html

 

 

Python
1
2
You are logged in as {{ current_user.email }}.
<a href="/logout">Logout</a>

 

 

As you can see we are showing the dynamic logged_in user using the {{}} operator. And then we have the logout button and inside that we are having the /logout route

 

 

 

 

 

Logging out Users

 

 

Now we will be writing the route for logging out the users which will be handled inside the /logout route as shown below

 

 

Python
1
2
3
4
@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))

 

 

As you can see we are first of all calling the logout_user() method of the flask_login library and then we are redirecting the user to the login page as shown below

 

 

 

 

Full Source Code

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from flask import Flask, render_template, request, redirect, url_for
from flask_login import LoginManager, login_user, logout_user, login_required
 
app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)
 
# a dummy list of users
users = {
    'geekygautam1997@gmail.com': {'password': '123456'},
    'gauti123456@mail.com': {'password': '123456789'},
    'john@gmail.com': {'password': 'john123456'},
    'smith@gmail.com': {'password': 'smith123456'}
}
 
class User:
    def __init__(self, email):
        self.email = email
 
    def is_authenticated(self):
        return True
 
    def is_active(self):
        return True
 
    def is_anonymous(self):
        return False
 
    def get_id(self):
        return self.email
 
 
@login_manager.user_loader
def load_user(email):
    if email not in users:
        return "email not exist"
    user = User(email)
    return user
 
 
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        if request.form['password'] == users[email]['password']:
            user = User(email)
            login_user(user)
            return redirect(url_for('protected'))
 
    return render_template('login.html')
 
 
@app.route('/protected')
@login_required
def protected():
    return render_template('protected.html')
 
 
@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))
 
 
if __name__ == "__main__":
    app.secret_key = "sdcdds"
    app.run(debug=True)

 

Recent Posts

  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme