Unix-style user accounts (passwd, groups, permissions) with a web-friendly Python API.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-accounts.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-accounts.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-accounts.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add comprehensive FAQ section 369661c 1 year ago History
README.md

dbbasic-accounts

PyPI version Python 3.8+

Unix-style user accounts with web-friendly API and filesystem integration.

"The web forked from Unix. Let's merge it back."

Why?

The critical insight: Unix already solved user management, authentication, and permissions. The web abandoned it and reinvented everything poorly. What if we just... used Unix?

Docker = isolated Unix system per app. Each container can have its own /etc/passwd without conflicts. We can return to Unix.

Features

  • Dual API: Unix layer (useradd, passwd) + Web layer (register, login)
  • Email-based auth: Use emails like john@example.com
  • Filesystem integration: Auto-creates home directories and mailboxes
  • Unix-compatible: Commands like cat etc/passwd.tsv work
  • Zero dependencies: Just Python and TSV files
  • Secure: Argon2id password hashing

Installation

pip install dbbasic-accounts

PyPI: https://pypi.org/project/dbbasic-accounts/

GitHub: https://github.com/askrobots/dbbasic-accounts

Quick Start

Web-Friendly API

from dbbasic_accounts import Accounts

# Initialize (creates etc/, home/, var/ directories)
accounts = Accounts('.', domain='example.com')

# Register user (web-style)
user = accounts.register('john@example.com', 'secret', name='John Doe')
# Creates:
# - etc/passwd.tsv entry
# - etc/shadow.tsv password hash
# - home/john/ directory
# - var/mail/john mailbox

# Login (web-style)
user = accounts.login('john@example.com', 'secret')
if user:
    print(f"Welcome {user.fullname}!")

# Add roles
accounts.add_role('john@example.com', 'editor')
accounts.add_role('john@example.com', 'admin')

# Check roles
roles = accounts.get_roles('john@example.com')
print(roles)  # ['users', 'editor', 'admin']

# Get user
user = accounts.get_user(email='john@example.com')
user = accounts.get_user(user_id=1000)
user = accounts.get_user(username='john')

Unix-Style API

from dbbasic_accounts import PasswdDB

# Initialize
passwd = PasswdDB('./etc')

# Unix commands (just like the real thing)
user = passwd.useradd('john', password='secret', fullname='John Doe')
passwd.passwd('john', 'newsecret')
passwd.usermod('john', add_groups=['editors', 'admins'])
print(passwd.groups('john'))  # ['users', 'editors', 'admins']

# Authenticate
user = passwd.authenticate('john', 'newsecret')
if user:
    print(f"Authenticated: {user.username}")

File Structure

Your app becomes a Unix system:

myapp/
├── etc/
│   ├── passwd.tsv      # Users (like /etc/passwd)
│   ├── shadow.tsv      # Password hashes (like /etc/shadow, mode 0600)
│   └── group.tsv       # Groups/roles (like /etc/group)
├── home/               # User directories
│   ├── john/           # User john's files
│   │   ├── profile.jpg
│   │   └── uploads/
│   └── jane/
├── var/
│   ├── mail/           # Email spool (user inboxes)
│   │   ├── john
│   │   └── jane
│   └── log/            # Logs
└── app.py              # Your web app

Now Unix tools work:

# List users
cat etc/passwd.tsv

# Check user's files
ls home/john/

# Read user's mailbox
cat var/mail/john

API Reference

Accounts Class (Web-Friendly)

register(email, password, name='')

Register new user.

user = accounts.register('john@example.com', 'secret123', name='John Doe')
# Returns User object
# Creates home directory and mailbox

login(email, password)

Authenticate user.

user = accounts.login('john@example.com', 'secret123')
if user:
    session['user_id'] = user.uid
    session['username'] = user.username

get_user(user_id=None, email=None, username=None)

Get user by ID, email, or username.

user = accounts.get_user(user_id=1000)
user = accounts.get_user(email='john@example.com')
user = accounts.get_user(username='john')

add_role(email, role)

Add role to user (groups).

accounts.add_role('john@example.com', 'editor')

get_roles(email)

Get user's roles.

roles = accounts.get_roles('john@example.com')
# ['users', 'editors', 'admins']

change_password(email, new_password)

Change user password.

accounts.change_password('john@example.com', 'newsecret')

delete_user(email)

Delete user account.

accounts.delete_user('john@example.com')

get_home_directory(email)

Get path to user's home directory.

home = accounts.get_home_directory('john@example.com')
# Path: home/john/

get_mailbox(email)

Get path to user's mailbox.

mailbox = accounts.get_mailbox('john@example.com')
# Path: var/mail/john

PasswdDB Class (Unix-Compatible)

Full Unix-style commands:

  • useradd(username, password, fullname, groups) - Add user
  • getuser(username) - Get user
  • authenticate(username, password) - Auth user
  • passwd(username, new_password) - Change password
  • usermod(username, add_groups, remove_groups) - Modify user
  • userdel(username) - Delete user
  • groups(username) - Get user's groups
  • groupadd(groupname, gid) - Add group
  • list_users() - List all users
  • list_groups() - List all groups

See dbbasic-passwd for full Unix API docs.

Flask Integration

from flask import Flask, session, request, redirect, render_template
from dbbasic_accounts import Accounts

app = Flask(__name__)
app.secret_key = 'your-secret-key'
accounts = Accounts('./data', domain='example.com')

@app.route('/register', methods=['POST'])
def register():
    try:
        user = accounts.register(
            request.form['email'],
            request.form['password'],
            name=request.form['name']
        )
        session['user_id'] = user.uid
        session['email'] = request.form['email']
        return redirect('/dashboard')
    except ValueError as e:
        return str(e), 400

@app.route('/login', methods=['POST'])
def login():
    user = accounts.login(
        request.form['email'],
        request.form['password']
    )
    if user:
        session['user_id'] = user.uid
        session['email'] = request.form['email']
        return redirect('/dashboard')
    return 'Invalid credentials', 401

@app.route('/admin')
def admin():
    email = session.get('email')
    if not email:
        return redirect('/login')

    # Check if user has admin role
    if 'admin' not in accounts.get_roles(email):
        return 'Forbidden', 403

    return render_template('admin.html')

@app.route('/profile')
def profile():
    email = session.get('email')
    if not email:
        return redirect('/login')

    user = accounts.get_user(email=email)
    home_dir = accounts.get_home_directory(email)

    return render_template('profile.html', user=user, home_dir=home_dir)

@app.route('/logout')
def logout():
    session.clear()
    return redirect('/')

Docker Integration

FROM python:3.11

WORKDIR /app

# Install dbbasic-accounts
RUN pip install dbbasic-accounts

# Copy app
COPY app.py /app/

# Initialize users (optional - can also do this in app.py)
RUN python -c "
from dbbasic_accounts import Accounts
accounts = Accounts('/app/data', domain='example.com')
accounts.register('admin@example.com', 'changeme', name='Admin User')
accounts.add_role('admin@example.com', 'admin')
"

CMD ["python", "app.py"]

Each container = isolated Unix system with its own users. No conflicts.

Design Philosophy

  1. Mirror Unix: Use 50 years of battle-tested design
  2. Stay Compatible: Unix commands should work
  3. Web-Friendly: Add convenience for web developers
  4. No Fork: Don't diverge from Unix, extend it
  5. Filesystem Integration: home/ and var/mail/ like real Unix

Comparison

Traditional Web Apps

# Requires MySQL server, complex schema, ORMs
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

user = User.objects.create_user('john', 'john@example.com', 'secret')
user = authenticate(username='john', password='secret')

dbbasic-accounts

# Just TSV files, no database
from dbbasic_accounts import Accounts

accounts = Accounts('.')
user = accounts.register('john@example.com', 'secret')
user = accounts.login('john@example.com', 'secret')

TSV File Format

passwd.tsv

username	uid	gid	fullname	homedir	shell	created
john	1000	100	John Doe <john@example.com>	/home/john	/bin/bash	2025-10-09T10:30:00
jane	1001	100	Jane Smith <jane@example.com>	/home/jane	/bin/bash	2025-10-09T11:00:00

shadow.tsv

username	password_hash	last_changed	min_age	max_age	warn_age	inactive
john	$argon2id$v=19$m=65536,t=3,p=4$...	2025-10-09T10:30:00	0	90	7	14
jane	$argon2id$v=19$m=65536,t=3,p=4$...	2025-10-09T11:00:00	0	90	7	14

group.tsv

groupname	gid	members
users	100
editors	101	john,jane
admins	102	john

Security

  • Argon2id: Current best-practice password hashing (winner of Password Hashing Competition)
  • Automatic rehashing: Passwords automatically rehashed if Argon2 parameters change
  • shadow.tsv permissions: Automatically set to 0600 (owner read/write only) on Unix
  • No plaintext passwords: Passwords never stored in plaintext

FAQ

Why passwords instead of passkeys/WebAuthn?

Short answer: Passwords with strong hashing (Argon2id) are simpler, more portable, and sufficient for most applications.

Longer answer:

Passkeys/WebAuthn solve specific problems at scale (phishing, credential stuffing) that are most relevant to large platforms. For individual applications and smaller services, traditional password authentication offers several advantages:

Advantages of password authentication:

  • Universal compatibility: Works everywhere (browsers, mobile apps, APIs, CLI tools)
  • User control: Users can store passwords however they prefer (memory, password manager, written down)
  • Simple recovery: Standard email-based password reset flows
  • No device dependencies: Not tied to specific hardware or platform vendors
  • Developer simplicity: Straightforward implementation without WebAuthn complexity
  • Offline capable: Can work without internet connectivity
  • Cross-platform: Not dependent on Apple/Google/Microsoft ecosystems

When you might want passkeys:

  • You're operating at massive scale (millions of users)
  • Phishing is a primary threat vector for your specific use case
  • You have resources to implement and maintain WebAuthn
  • Your users are technical enough to manage device-based credentials
  • You can support the full recovery/backup flow

What dbbasic-accounts provides:

  • Industry-standard Argon2id hashing (same security as modern systems)
  • Simple, auditable implementation
  • Full control over your authentication system
  • Easy integration with existing 2FA/TOTP if you need additional security

Can I add 2FA/TOTP?

Yes! dbbasic-accounts handles password authentication. You can layer TOTP (Time-based One-Time Passwords) on top:

import pyotp

# During registration
totp_secret = pyotp.random_base32()
# Store totp_secret with user (add field to passwd.tsv or separate file)

# During login
user = accounts.login(email, password)
if user:
    totp = pyotp.TOTP(user_totp_secret)
    if totp.verify(user_provided_code):
        # Grant access

Popular 2FA libraries: pyotp, oath

Can I use OAuth/SSO (Login with Google, etc)?

Yes! You can use dbbasic-accounts alongside OAuth:

# OAuth flow
oauth_user_info = google_oauth_callback()

# Create/get user in your system
user = accounts.get_user(email=oauth_user_info['email'])
if not user:
    # Create user without password (or with random password)
    user = accounts.register(
        oauth_user_info['email'],
        password=secrets.token_urlsafe(32),  # Random, unused password
        name=oauth_user_info['name']
    )

# User is now in your system
session['user_id'] = user.uid

Is this secure enough for production?

Yes, with proper deployment:

dbbasic-accounts provides:

  • Argon2id password hashing (current best practice)
  • Secure password storage (shadow.tsv with restricted permissions)
  • Protection against timing attacks (Argon2 built-in)

You should also:

  • Use HTTPS (TLS/SSL) for all traffic
  • Implement rate limiting on login attempts
  • Use secure session management (httponly, secure cookies)
  • Consider adding 2FA for sensitive applications
  • Regular backups of your TSV files
  • Keep shadow.tsv permissions at 0600

How does this compare to Firebase Auth, Auth0, etc?

SaaS Auth Services (Firebase, Auth0, Supabase):

  • ✅ Managed service, less operational work
  • ✅ Built-in OAuth providers
  • ❌ Monthly costs scale with users
  • ❌ Vendor lock-in
  • ❌ External dependency (outages affect you)
  • ❌ Your user data on their servers

dbbasic-accounts:

  • ✅ Zero monthly costs
  • ✅ Full control over user data
  • ✅ No external dependencies
  • ✅ Simple, auditable code
  • ✅ Easy to migrate or modify
  • ❌ You handle operational aspects
  • ❌ OAuth requires custom integration

Best fit: Self-hosted apps, internal tools, indie projects, anything where you want full control and simplicity over managed service convenience.

Can I migrate from WordPress/Django/etc?

The Unix layer (PasswdDB) is designed to be migration-friendly. You can write scripts to import users:

from dbbasic_accounts import Accounts

accounts = Accounts('./data')

# Import from existing database
for user_row in old_database.get_users():
    try:
        # Create user with temporary password
        accounts.register(
            user_row['email'],
            password=generate_temp_password(),
            name=user_row['name']
        )
        # Send password reset email
        send_password_reset(user_row['email'])
    except ValueError:
        # User already exists
        pass

Note: Old password hashes (bcrypt, MD5, etc) can't be directly imported. Users need to reset passwords.

Requirements

  • Python 3.8+
  • argon2-cffi >= 23.1.0

Testing

pip install -e ".[dev]"
pytest
pytest --cov=dbbasic_accounts

License

MIT

Credits

Inspired by:

  • Unix user management (/etc/passwd, /etc/shadow, /etc/group)
  • Docker's container isolation
  • The need to escape MySQL/ORM complexity

Part of the dbbasic-* family:

  • dbbasic-tsv - TSV database
  • dbbasic-accounts - This package