The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a simple login authentication system

Building a simple login authentication system involves creating a way for users to enter their credentials (typically username/email and password), verify them, and grant access to the user if the credentials are correct. Below is a basic Python example using Flask (a micro web framework) and SQLite (for storing user data). You’ll need to install Flask first by running pip install Flask.

1. Set up the project directory:

bash
project/ ├── app.py ├── templates/ │ ├── login.html │ └── home.html └── database.db

2. Create the Database

We’ll use SQLite for simplicity. Create the database.db file and add a simple users table.

python
import sqlite3 def create_db(): conn = sqlite3.connect('database.db') cursor = conn.cursor() # Create users table cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)''') # Insert a test user cursor.execute("INSERT INTO users (username, password) VALUES ('testuser', 'testpass')") conn.commit() conn.close() create_db()

3. Create the Flask App (app.py)

This file will handle the routing and authentication logic.

python
from flask import Flask, render_template, request, redirect, url_for, flash import sqlite3 app = Flask(__name__) app.secret_key = 'your_secret_key' # For session management # Function to check if the credentials are valid def validate_user(username, password): conn = sqlite3.connect('database.db') cursor = conn.cursor() # Query the user from the database cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password)) user = cursor.fetchone() conn.close() return user @app.route('/', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] # Validate user credentials user = validate_user(username, password) if user: return redirect(url_for('home')) else: flash('Invalid credentials, please try again.') return render_template('login.html') @app.route('/home') def home(): return render_template('home.html') if __name__ == '__main__': app.run(debug=True)

4. Create the Login HTML Form (templates/login.html)

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <h2>Login</h2> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <form method="POST"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <br><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <br><br> <button type="submit">Login</button> </form> </body> </html>

5. Create the Home Page (templates/home.html)

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <h2>Welcome to the Home Page!</h2> <p>You have successfully logged in.</p> </body> </html>

6. Run the Application

To run the application, execute the following command in your project directory:

bash
python app.py

Testing the Login

  1. Open a web browser and go to http://127.0.0.1:5000/.

  2. Use the credentials testuser and testpass to log in.

  3. If the login is successful, you’ll be redirected to the home page. If the credentials are incorrect, you’ll see an error message.

Improvements

  • Hashing Passwords: In a real application, passwords should be hashed (using libraries like bcrypt or hashlib), not stored in plain text.

  • Sessions: To keep the user logged in between pages, you’d typically use sessions in Flask (session object).

  • Error Handling: You can improve error handling and validation, especially for empty fields or invalid inputs.

This is a basic and simple authentication system. You can extend this further with features like registration, password resets, and more!

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About