Example Login Page using Flask
Example of a Flask Login Page
Flask Login Page Example
Hey there! Today, I want to share with you an example of a Flask login page. Flask is a micro web framework written in Python that allows you to build web applications quickly and with ease. One of the essential features of many web applications is user authentication, and Flask provides a straightforward way to implement it using the Flask-Login extension.
Before we dive into the code, let’s briefly discuss why user authentication is important. In a web application, user authentication ensures that only authorized users can access certain parts of the site or perform specific actions. It helps protect user data, maintain privacy, and provide a personalized experience. With Flask and Flask-Login, we can add a secure login functionality to our web app quickly.
Setting Up Flask-Login
To get started, make sure you have Flask and Flask-Login installed. You can install them using pip:
$ pip install Flask Flask-Login
Next, let’s create a new Flask application and import the necessary modules:
from flask import Flask, render_template, redirect, url_for, request
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
We’ll also need to create an instance of the Flask and LoginManager classes:
app = Flask(__name__)
app.secret_key = 'your_secret_key'
login_manager = LoginManager(app)
The secret key is used to encrypt session cookies and other security-related purposes. Make sure to replace ‘your_secret_key’ with a strong and secure secret key.
Creating a User Model
Now, let’s create a User model that represents our application’s users. This model will inherit from the UserMixin class provided by Flask-Login:
class User(UserMixin):
def __init__(self, id):
self.id = id
In a real-world scenario, you would typically store user information in a database. For simplicity, we’ll use a dictionary to store a few user records:
users = {'user1': {'password': 'password1'},
'user2': {'password': 'password2'}}
Implementing Login and Logout Routes
Now, let’s implement the login and logout routes. The login route will render a login form and handle the login process:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username]['password'] == password:
user = User(username)
login_user(user)
return redirect(url_for('protected'))
flash('Invalid username or password')
return render_template('login.html')
In the login route, we retrieve the username and password from the form data submitted by the user. We then check if the username exists in our users dictionary and if the provided password matches. If the credentials are valid, we create a User instance and call the login_user() function to log the user in. Finally, we redirect the user to a protected page, which we’ll define next.
The logout route is simpler:
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
In the logout route, we use the login_required decorator provided by Flask-Login to ensure that only authenticated users can access this route. When the user logs out, we call the logout_user() function provided by Flask-Login and redirect them to the login page.
Protecting Routes
To protect certain routes in our application, we can use the login_required decorator:
@app.route('/protected')
@login_required
def protected():
return render_template('protected.html')
The login_required decorator ensures that only authenticated users can access the /protected route. If a user tries to access the route without being logged in, Flask-Login will redirect them to the login page automatically.
Creating the Login Form
Now, let’s create the login form using HTML and Flask’s template engine:
<form action="{{ url_for('login') }}" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
The login form has two input fields for the username and password, respectively. The action attribute of the form points to the login route, and the method is set to POST.
Conclusion
Congratulations! You now have a basic understanding of how to implement a login page using Flask and Flask-Login. User authentication is an essential feature for many web applications, and Flask makes it easy to add this functionality. Remember to keep security in mind and use best practices when handling user authentication.
Feel free to experiment and add more features to your login page, such as password reset functionality or user registration. Happy coding!