User Login with Flask Tutorial

beginner
20 min

User Login with Flask Tutorial

Welcome to our comprehensive guide on implementing user login functionality using Flask, a powerful web framework for Python! In this tutorial, we'll walk you through building a login system step-by-step. By the end, you'll have a solid understanding of how to secure user authentication in your web applications.

šŸŽÆ Objective: Learn how to create a user login system using Flask.

What is User Login?

User login is a crucial feature in web applications that enables users to access their personal account and protected resources. In this tutorial, we'll create a simple login system where users can register, log in, and access protected pages.

Prerequisites

  • Basic understanding of Python programming
  • Familiarity with Flask web framework

Setting Up the Environment

Before we dive into the login system, let's set up a new Flask project:

bash
$ mkdir my-flask-app $ cd my-flask-app $ pip install flask flask-sqlalchemy

Create a new file named app.py and let's get started!

Creating the Database

We'll use Flask-SQLAlchemy to manage our database. First, import the necessary modules and initialize the SQLAlchemy extension:

python
from flask import Flask, render_template, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app)

Now, let's create the User model:

python
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(120), nullable=False) def __repr__(self): return f'<User {self.username}>'

Initialize the database:

python
if __name__ == '__main__': db.create_all() app.run(debug=True)

Registering Users

Let's create a registration form and handle user registration in a separate route. First, create the registration template:

html
<!-- templates/register.html --> <!DOCTYPE html> <html lang="en"> <head> <!-- ... --> </head> <body> <h1>Register</h1> <form method="POST" action="{{ url_for('register') }}"> <!-- ... --> </form> </body> </html>

Now, create the register route in app.py and implement user registration logic:

python
@app.route('/register', methods=['GET', 'POST']) def register(): # ... if form.validate_on_submit(): user = User(username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() flash('Account created! You can now log in.', 'success') return redirect(url_for('login')) return render_template('register.html', form=form)

Implementing Login Functionality

Next, we'll create a login form and handle user authentication:

html
<!-- templates/login.html --> <!DOCTYPE html> <html lang="en"> <head> <!-- ... --> </head> <body> <h1>Login</h1> <form method="POST" action="{{ url_for('login') }}"> <!-- ... --> </form> </body> </html>

Create the login route in app.py and implement user authentication logic:

python
@app.route('/login', methods=['GET', 'POST']) def login(): # ... if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and user.password == form.password.data: # Login successful return redirect(url_for('protected')) else: # Invalid credentials flash('Invalid username or password', 'danger') return render_template('login.html', form=form)

Protecting Routes

Now that we have a login system, let's protect some routes with authentication:

python
@app.route('/protected') @login_required def protected(): # ... return 'Protected content.' @app.route('/logout') def logout(): # ... return redirect(url_for('login')) def login_required(view): @wraps(view) def wrapped_view(*args, **kwargs): if 'username' not in session: return redirect(url_for('login')) return view(*args, **kwargs) return wrapped_view

šŸ“ Note: We've created a login_required decorator to protect routes easily.

Testing Our Login System

Now, you can test your login system by running the application and navigating to the registration and login pages.

Quiz

Quick Quiz
Question 1 of 1

Which Flask extension is used to manage our database?

Conclusion

Congratulations! You've built a simple but functional user login system using Flask. You've learned about creating a database, registering users, implementing login functionality, and protecting routes. With this knowledge, you can now create more secure web applications!

šŸ’” Pro Tip: Remember to secure your application by hashing passwords and using secure cookies for session management.

That's all for this tutorial. Happy coding! šŸŽ‰


šŸ“ Important: This tutorial is just a starting point for building user login systems using Flask. There's much more to learn about web security and best practices for user authentication. Keep exploring and learning! 🌱