Skip to main content

OL-Auth (v1.1.0)

OL-Auth (short for One-Line Auth) is a lightweight, zero-configuration authentication engine for Python web applications. With a single line of code, it provisions your user & session tables, handles password hashing and persistent cookie sessions, protects routes, and serves responsive light/dark Sign up, Log in, and Password Reset pages.


✨ Features

  • Zero-config local dev, easy cloud scaling: Defaults to SQLite (WAL mode), and switches to PostgreSQL or MySQL via a standard connection string (db= or OLAUTH_DATABASE_URL) with automatic reconnect-on-drop.
  • Flask & FastAPI out of the box: Auto-detects the framework and mounts /signup, /login, /logout, /verify, /forgot-password, and /reset-password.
  • One-line route protection: Use @olauth.login_required in Flask or Depends(olauth.login_required) in FastAPI, and read olauth.current_user() anywhere.
  • Production-minded security defaults:
    • bcrypt password hashing (12 rounds, safe handling for >72-byte passwords) and constant-time login checks.
    • Persistent opaque session tokens stored as SHA-256 digests in olauth_sessions.
    • HttpOnly, SameSite=Lax cookies (with automatic Secure flag over HTTPS).
    • CSRF same-origin POST checks (Origin / Sec-Fetch-Site), open-redirect validation on ?next=, XSS-escaped templates, and per-IP sliding-window rate limiting.

📦 Installation

Install directly from PyPI:

# Core package
pip install olauth

# With web framework extras
pip install "olauth[flask]"
pip install "olauth[fastapi]"

# Optional database drivers for cloud hosting
pip install "olauth[postgres]"
pip install "olauth[mysql]"

# Combine extras as needed (e.g. FastAPI + PostgreSQL)
pip install "olauth[fastapi,postgres]"

💻 Quickstart

Flask

from flask import Flask
import olauth

app = Flask(__name__)
olauth.init(app)  # Creates olauth.db and mounts /signup, /login, /logout

@app.route("/")
def home():
    user = olauth.current_user()
    if user:
        return f"Welcome back, {user['email']}! <a href='/logout'>Log out</a>"
    return "Hello guest! <a href='/login'>Log in</a>"

@app.route("/dashboard")
@olauth.login_required
def dashboard():
    user = olauth.current_user()
    return f"Protected dashboard for user #{user['id']} ({user['email']})"

if __name__ == "__main__":
    app.run(debug=True)

In Flask Jinja templates, current_user is also automatically injected into the template context.

FastAPI

from fastapi import Depends, FastAPI
import olauth

app = FastAPI()
olauth.init(app)

@app.get("/")
def home(user: dict | None = Depends(olauth.current_user)):
    return {"user": user}

@app.get("/dashboard")
def dashboard(user: dict = Depends(olauth.login_required)):
    return {"message": f"Hello {user['email']}", "user_id": user["id"]}
  • Browser requests (Accept: text/html) to protected FastAPI routes redirect (303) to /login?next=....
  • API/JSON clients receive 401 Unauthorized.

🗄️ Databases (SQLite, PostgreSQL, MySQL)

Pass a connection URL to olauth.init(app, db=...) or set the OLAUTH_DATABASE_URL environment variable:

import os
import olauth

# 1. Zero-config SQLite (default: olauth.db)
olauth.init(app)

# 2. Custom SQLite path
olauth.init(app, db="sqlite:///data/app.db")

# 3. PostgreSQL (requires `pip install "olauth[postgres]"`)
olauth.init(app, db=os.getenv("DATABASE_URL"))  # e.g. postgresql://user:pass@host:5432/db

# 4. MySQL (requires `pip install "olauth[mysql]"`)
olauth.init(app, db="mysql://user:pass@host:3306/db")

✉️ Email Verification (Opt-In 6-Digit Code)

Email verification is off by default so hackathons and prototypes stay instant. When you want to verify emails, use the built-in zero-dependency SMTP sender, console mode, or a custom callback:

# 1. Built-in SMTP sender (defaults to Gmail SSL on port 465; or set OLAUTH_SMTP_USER / OLAUTH_SMTP_PASSWORD)
olauth.init(
    app,
    smtp_user="myapp@gmail.com",
    smtp_password="xxxx-xxxx-xxxx-xxxx",  # App Password
)

# 2. Local dev mode: prints the 6-digit code in your terminal with zero credentials
olauth.init(app, verify_email="console")

# 3. Custom sender (Resend, SendGrid, Postmark, etc.)
olauth.init(
    app,
    send_verification_code=lambda email, code: send_my_email(
        to=email,
        subject="Your verification code",
        text=f"Your verification code is: {code}",
    ),
)

When enabled:

  • /signup creates the account unverified, hashes and stores a single-use 6-digit code, sends it, and redirects to /verify.
  • Unverified users trying to /login are sent a fresh code and redirected to /verify (403 for JSON requests).
  • Submitting the code on /verify activates the account and logs the user in.

🔑 Password Reset Flow

olauth includes a built-in 6-digit password reset flow on /forgot-password and /reset-password (linked directly from /login):

  • GET/POST /forgot-password: Accepts an email, generates a single-use 6-digit code if the account exists (without revealing whether the email is registered), sends it via send_verification_code / SMTP (or prints to the terminal if no email sender is configured), and redirects to /reset-password.
  • GET/POST /reset-password: Accepts email, code, and password, enforces min_password_length, updates password_hash, consumes the code, revokes all existing sessions for that user, and logs the user in (when auto_login_on_signup=True).

🎨 Custom Templates

By default, olauth serves its built-in light/dark pages with zero configuration. When you want your own HTML pages instead, pass a template_dir directory, individual template file overrides, or both:

# Option 1: Drop any of login.html, signup.html, verify.html,
# forgot_password.html (or forgot.html), reset_password.html (or reset.html)
# into a folder — missing files fall back to built-in pages.
olauth.init(app, template_dir="templates/auth")

# Option 2: Override specific pages individually
olauth.init(
    app,
    login_template="templates/my_login.html",
    signup_template="templates/my_signup.html",
)

Custom templates are rendered with Jinja2 when installed (or safe HTML-escaped {key} / {{ key }} substitution otherwise) and receive these context variables: error, email_value, next_param, switch_url, login_url, signup_url, logout_url, verify_url, forgot_password_url, reset_password_url, title, heading, button_text, switch_prompt, and switch_action.


⚙️ Configuration Options

All options have safe defaults and can be customized in olauth.init(...):

Parameter Default Description
db None (olauth.db) SQLite path/URI, postgresql://..., or mysql://... (falls back to OLAUTH_DATABASE_URL).
redirect_to "/" Default destination after successful login/signup when ?next= is absent.
login_url "/login" Route for login and destination when unauthenticated browser requests are redirected.
verify_url "/verify" Route for entering the 6-digit email verification code.
forgot_password_url "/forgot-password" Route for requesting a 6-digit password reset code.
reset_password_url "/reset-password" Route for entering the 6-digit reset code and choosing a new password.
cookie_name "olauth_session" Name of the HttpOnly session cookie.
session_ttl 604800 (7 days) Session lifetime in seconds.
verification_ttl 900 (15 min) Email verification and password reset code lifetime in seconds.
cookie_secure None (auto) Force Secure cookie flag (True/False), or auto-detect from HTTPS / X-Forwarded-Proto.
auto_login_on_signup True Immediately issue a session cookie upon account creation, verification, or password reset.
min_password_length 8 Minimum password length enforced on /signup and /reset-password.
rate_limit 15 Failed auth attempts per client IP allowed per 60-second sliding window (0 disables).
verify_email False Set to "console" for terminal verification codes during local dev.
smtp_user None SMTP username/sender address (falls back to OLAUTH_SMTP_USER).
smtp_password None SMTP password/app password (falls back to OLAUTH_SMTP_PASSWORD).
smtp_host "smtp.gmail.com" SMTP server hostname for built-in email delivery.
smtp_port 465 SMTP port (465 uses SSL; other ports use STARTTLS).
send_verification_code None Optional custom callback (email, code) -> None overriding the built-in sender.
template_dir None Directory searched for login.html, signup.html, verify.html, forgot_password.html, reset_password.html.
login_template None Path to a custom HTML template file overriding /login.
signup_template None Path to a custom HTML template file overriding /signup.
verify_template None Path to a custom HTML template file overriding /verify.
forgot_password_template None Path to a custom HTML template file overriding /forgot-password.
reset_password_template None Path to a custom HTML template file overriding /reset-password.

🧪 Running Tests

pip install -e ".[dev]"
pytest

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

Metadata

Release files for olauth 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for olauth 1.1.0
File Size Uploaded Provenance Actions
olauth-1.1.0.tar.gz 35.3 kB With provenance Details for olauth-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for olauth 1.1.0
File Interpreter ABI Platform Actions
olauth-1.1.0-py3-none-any.whl Python 3 none any Details for olauth-1.1.0-py3-none-any.whl

Total release size: 63.3 kB

Release files / olauth-1.1.0.tar.gz

Download URL olauth-1.1.0.tar.gz
Size 35.3 kB
Tags Source
SHA-256 checksum
How to use checksums
36b5cf37c84be33daf1199d5a431dd8e04fd138b8114f7b93c75c6221c441f53
BLAKE2b-256 checksum
How to use checksums
49e63e7eed6d64184a95185dfdfe2b001d30137d6616b383c3767349835cc8d4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / olauth-1.1.0-py3-none-any.whl

Download URL olauth-1.1.0-py3-none-any.whl
Size 28.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7270717558d50aff442809979912b3f56dd29687423fb502839a151eb7c5eba7
BLAKE2b-256 checksum
How to use checksums
bf6c83aadcf8db64f22ca51cb65da7ce2f7950766fbb02796de5b97a2460039c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for olauth 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for olauth-1.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page