How to store Username and Password in Flask
×


How to store Username and Password in Flask

797

Introduction

Storing usernames and passwords securely is fundamental when developing Flask applications. In this guide, you’ll learn how to save user credentials safely using hashing for passwords and a database like SQLite, ensuring sensitive data remains protected.

Required Libraries

Install the needed Flask extensions before getting started:

pip install Flask Flask-SQLAlchemy Flask-Bcrypt

App and Database Configuration

Set up your Flask app with SQLAlchemy for ORM and Bcrypt for password hashing:

import os
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///users.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
bcrypt = Bcrypt(app)

Creating User Model

Define a User table with fields for username and a hashed password:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)

    def set_password(self, password):
        self.password_hash = bcrypt.generate_password_hash(password).decode('utf-8')

    def check_password(self, password):
        return bcrypt.check_password_hash(self.password_hash, password)

Initializing the Database

Create the users table before handling any requests:

@app.before_first_request
def create_tables():
    db.create_all()

User Registration Endpoint

Implement an API route to register new users with hashed passwords:

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'error': 'Missing username or password'}), 400

    if User.query.filter_by(username=username).first():
        return jsonify({'error': 'Username already exists'}), 400

    user = User(username=username)
    user.set_password(password)
    db.session.add(user)
    db.session.commit()

    return jsonify({'message': 'User created successfully'}), 201

User Login Endpoint

Authenticate users by comparing their password against the stored hash:

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    user = User.query.filter_by(username=username).first()
    if user and user.check_password(password):
        return jsonify({'message': 'Login successful'}), 200

    return jsonify({'error': 'Invalid username or password'}), 401

Security Best Practices

  • Always hash passwords; never store plaintext.
  • Use strong hashing like Bcrypt for added security.
  • Store sensitive configs like DB URI in environment variables.
  • Enforce HTTPS in production to protect data in transit.

Conclusion

With this setup, you can securely store usernames and password hashes in Flask. Using SQLAlchemy for data handling and Bcrypt for hashing ensures your users' credentials are well protected from breach scenarios.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat