Building a User Authentication System in Flask with mongoDB: Login and Register

Mohammed Farmaan
featurepreneur
3 min readJan 3, 2024

--

Introduction:

User authentication is a fundamental component of many web applications, ensuring secure access and personalized experiences. Flask, a lightweight web framework for Python, combined with Pymongo, a Python driver for MongoDB, provides a robust foundation for building a user authentication system. In this article, we’ll guide you through the process of implementing user login and registration functionalities in a Flask application using Pymongo for MongoDB interactions.

Setting Up Flask and Pymongo:

Before diving into user authentication, make sure you have Flask and Pymongo installed. You can install them using the following commands:

pip install Flask
pip install pymongo

Setting Up MongoDB:

Ensure that you have a MongoDB instance running. If not, install and start MongoDB by following the official instructions: MongoDB Installation Guide

Building a Flask Application:

Create a new Flask application and set up the necessary folders and files. Here’s a basic structure to get you started:

/myapp
/templates
layout.html
login.html
register.html
app.py

Implementing User Registration:

  1. Import Necessary Modules:

In your app.py file, import the required modules:

from flask import Flask, render_template, request, redirect, url_for, flash
from pymongo import MongoClient

2. Configure Flask App:

Set up your Flask app and configure the MongoDB connection:

app = Flask(__name__)
app.secret_key = "your_secret_key" # Replace with a strong secret key
client = MongoClient('localhost', 27017)
db = client['your_database_name'] # Replace with your MongoDB database name
users_collection = db['users']

3. Create Registration Route:

Implement a route for user registration:

@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

# Check if the username already exists
if users_collection.find_one({'username': username}):
flash('Username already exists. Choose a different one.', 'danger')
else:
users_collection.insert_one({'username': username, 'password': password})
flash('Registration successful. You can now log in.', 'success')
return redirect(url_for('login'))

return render_template('register.html')

Implementing User Login:

  1. Create Login Route:

Add a route for user login:

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

# Check if the username and password match
user = users_collection.find_one({'username': username, 'password': password})
if user:
flash('Login successful.', 'success')
# Add any additional logic, such as session management
else:
flash('Invalid username or password. Please try again.', 'danger')

return render_template('login.html')

Creating HTML Templates:

  1. Create Registration Form (register.html):
{% extends 'layout.html' %}

{% block content %}
<h2>Register</h2>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method="post" action="{{ url_for('register') }}">
<label for="username">Username:</label>
<input type="text" name="username" required>
<label for="password">Password:</label>
<input type="password" name="password" required>
<button type="submit">Register</button>
</form>
{% endblock %}

2. Create Login Form (login.html):

{% extends 'layout.html' %}

{% block content %}
<h2>Login</h2>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method="post" action="{{ url_for('login') }}">
<label for="username">Username:</label>
<input type="text" name="username" required>
<label for="password">Password:</label>
<input type="password" name="password" required>
<button type="submit">Login</button>
</form>
{% endblock %}

3. Create Layout Template (layout.html):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask User Authentication</title>
</head>
<body>
<header>
<h1>Flask User Authentication</h1>
</header>
<section>
{% block content %}{% endblock %}
</section>
</body>
</html>

Running the Application:

Run your Flask application using the following command:

python app.py

Visit http://localhost:5000 in your web browser to see the registration and login forms. You can now expand upon this foundation to add more features, such as session management, profile pages, and password hashing for enhanced security.

Conclusion:

In this article, we covered the basics of implementing user registration and login functionalities in a Flask application using Pymongo for MongoDB integration. Building on this foundation, you can further enhance your authentication system and customize it to suit the specific requirements of your web application.

Feel free to explore additional Flask extensions and features to expand the capabilities of your authentication system. Happy coding!

--

--