Fix: self-hosted accounts stuck unverified without email (#100)

Standard mode (the Docker default) verifies accounts by email, but Docker
doesn't pass SMTP settings through and .env.example ships placeholder
credentials, so on most self-hosted installs no verification email was ever
sent. The owner's own account stayed unverified on the guest tier, and login
said "Please wait for admin approval" on a server with no admin and no
admin UI.

- email_service: is_email_configured(), treating the .env.example
  placeholders as not configured.
- auth_db: claim_first_admin() makes the first account a verified admin when
  the instance has no admin (the local/skip-auth synthetic admins don't
  count), under a write lock so concurrent registrations can't both win.
  Used only when email is not configured, so servers that verify by email
  are unaffected.
- register: without email, the first account becomes admin; later ones are
  told the server operator has to approve them.
- login: an unverified account on a server without email and without an
  admin claims admin, which un-sticks installs that registered before this.
  The unverified messages now say what to actually do.
- manage.py: users / approve / set-tier, so operators don't need SQL.
- main: load .env before importing src modules; email_service read its SMTP
  settings at import time, before .env was loaded.
- README: Docker starts in standard mode (it said local mode); document
  account management.
- tests: first-admin, later accounts, approve, stuck account, SMTP servers
  unaffected, and a concurrent-registration race.
This commit is contained in:
phialsbasement committed 2026-11-06 16:15:27 +11:00
1 parent fefc66ad1d
commit b5b288f489
6 files changed
+334 -16

No files matched your search

+22 -1
View File
@@ -94,7 +94,7 @@ docker compose up -d
# Open browser to http://localhost:5000
```
By default, LibreCrawl runs in local mode for easy personal use. The `.env` file controls this:
Docker starts in **standard mode** (accounts and login) unless you set `LOCAL_MODE=true`. The start scripts above use local mode. For personal use on your own machine, set this in `.env` to skip accounts entirely:
```bash
# .env file
@@ -103,6 +103,8 @@ HOST_BINDING=127.0.0.1
REGISTRATION_DISABLED=false
```
In standard mode without email (SMTP) set up, **the first account you register becomes the admin** and can log in straight away. Accounts registered after that need approving, see [Managing accounts](#managing-accounts).
For production deployment with user authentication, edit your `.env` file:
```bash
@@ -302,6 +304,25 @@ Check out these example plugins to get started:
- Perfect for personal use or single-user self-hosting
- Recommended for local development and testing
### Managing accounts
In standard mode, new accounts are verified by email when SMTP is configured (`SMTP_*` in `.env`). Without SMTP:
- The **first account** registered on the server becomes the **admin** and can log in immediately. If you registered before this existed, just log in: an unverified account claims admin if the server has none yet.
- Later accounts can't log in until the admin approves them.
There's no admin page yet, so use `manage.py`:
```bash
python manage.py users # list accounts, verified status and tier
python manage.py approve <username> # let an account log in (tier "user")
python manage.py approve <username> --tier extra
python manage.py set-tier <username> admin # guest, user, extra or admin
# Docker
docker compose exec librecrawl python manage.py users
```
## Configuration
Click "Settings" to configure:
+32 -7
View File
@@ -13,6 +13,12 @@ import re
import base64
from io import StringIO, BytesIO
from datetime import datetime, timedelta
# Load .env before importing src modules: several of them (email_service's
# SMTP settings, for one) read environment variables at import time.
from dotenv import load_dotenv
load_dotenv()
from flask import Flask, render_template, request, jsonify, session, redirect, url_for
from flask_compress import Compress
from functools import wraps
@@ -24,14 +30,10 @@ NGRAM_EXPORT_FIELDS = [
'gram', 'body', 'density', 'body_unlinked', 'headings',
'title', 'inlinks_anchor', 'inlinks_alt', 'total', 'url_count'
]
from src.auth_db import init_db, create_user, authenticate_user, get_user_by_id, log_guest_crawl, get_guest_crawls_last_24h, verify_user, set_user_tier, create_verification_token, verify_token, get_user_by_email, get_or_create_zoho_user, get_user_settings, save_user_settings
from src.email_service import send_verification_email, send_welcome_email
from src.auth_db import init_db, create_user, authenticate_user, get_user_by_id, log_guest_crawl, get_guest_crawls_last_24h, verify_user, set_user_tier, create_verification_token, verify_token, get_user_by_email, get_or_create_zoho_user, get_user_settings, save_user_settings, claim_first_admin
from src.email_service import send_verification_email, send_welcome_email, is_email_configured
from src.zoho_oauth import ZohoOAuthConfig, ZohoOAuthError
# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
# Parse command line arguments
parser = argparse.ArgumentParser(description='LibreCrawl - SEO Spider Tool')
parser.add_argument('--local', '-l', action='store_true',
@@ -190,6 +192,18 @@ if DISABLE_GUEST:
print("Guest login is not allowed")
print("=" * 60)
if not LOCAL_MODE and not SKIP_AUTH and not is_email_configured():
from src.auth_db import has_admin
print("=" * 60)
print("EMAIL NOT CONFIGURED (no SMTP_USER / SMTP_PASSWORD)")
print("Accounts can't be verified by email.")
if has_admin():
print("New accounts need approval: python manage.py approve <username>")
else:
print("No admin account yet: the first account to register (or an")
print("existing unverified account logging in) becomes the admin.")
print("=" * 60)
if DEMO_MODE:
print("=" * 60)
print("DEMO MODE ENABLED")
@@ -694,6 +708,16 @@ def register():
print(f"Error during local mode auto-verification: {e}")
# Don't fail the registration, just log the error
# The account is still created successfully
elif success and not is_email_configured():
# No SMTP: nobody can verify by email. The first account on the
# instance is its owner and becomes admin; anyone after that needs the
# admin to approve them (python manage.py approve <username>).
if claim_first_admin(user_id):
print(f"Email is not configured: '{username}' is the first account and is now the admin of this instance")
message = 'Account created! As the first account on this server, you are its admin. You can log in now.'
else:
message = ("Account created, but this server can't send verification emails, "
"so whoever runs it needs to approve your account before you can log in.")
elif success:
# Not in local mode - send verification email
is_resend = (message == 'resend')
@@ -737,7 +761,8 @@ def login():
success, message = skip_auth_login(username)
return jsonify({'success': success, 'message': message})
success, message, user_data = authenticate_user(username, password)
success, message, user_data = authenticate_user(username, password,
email_configured=is_email_configured())
if success:
session['user_id'] = user_data['id']
+89
View File
@@ -0,0 +1,89 @@
"""Account admin CLI for a LibreCrawl server.
There is no admin UI, so approving accounts and changing tiers happens here
rather than through hand-written SQL against data/users.db.
python manage.py users
python manage.py approve <username> [--tier user]
python manage.py set-tier <username> <guest|user|extra|admin>
In Docker, run it inside the container:
docker compose exec librecrawl python manage.py users
"""
import argparse
import sys
from dotenv import load_dotenv
load_dotenv()
from src import auth_db # noqa: E402
TIERS = ('guest', 'user', 'extra', 'admin')
def _find(cursor, username):
cursor.execute('SELECT id, username, verified, tier FROM users WHERE username = ?', (username,))
user = cursor.fetchone()
if not user:
sys.exit(f"no account named '{username}' (see: python manage.py users)")
return user
def cmd_users(args):
with auth_db.get_db() as conn:
rows = conn.execute(
'SELECT id, username, email, verified, tier, created_at, last_login '
'FROM users ORDER BY id').fetchall()
if not rows:
print('no accounts')
return
print(f'{"id":>4} {"username":<22} {"email":<32} {"verified":<9} {"tier":<6} {"last login":<19}')
for row in rows:
print(f'{row["id"]:>4} {row["username"][:22]:<22} {row["email"][:32]:<32} '
f'{"yes" if row["verified"] else "no":<9} {(row["tier"] or "guest"):<6} '
f'{(row["last_login"] or "never")[:19]:<19}')
def cmd_approve(args):
with auth_db.get_db() as conn:
cursor = conn.cursor()
user = _find(cursor, args.username)
cursor.execute('UPDATE users SET verified = 1, tier = ? WHERE id = ?', (args.tier, user['id']))
print(f"approved '{args.username}' with tier {args.tier}")
def cmd_set_tier(args):
with auth_db.get_db() as conn:
cursor = conn.cursor()
user = _find(cursor, args.username)
cursor.execute('UPDATE users SET tier = ? WHERE id = ?', (args.tier, user['id']))
note = '' if user['verified'] else " (account is still unverified: use 'approve' to let it log in)"
print(f"'{args.username}' is now tier {args.tier}{note}")
def main(argv=None):
parser = argparse.ArgumentParser(description='LibreCrawl account admin')
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('users', help='list accounts').set_defaults(func=cmd_users)
approve = sub.add_parser('approve', help='verify an account so it can log in')
approve.add_argument('username')
approve.add_argument('--tier', choices=TIERS, default='user',
help='tier to give the account (default: user)')
approve.set_defaults(func=cmd_approve)
set_tier = sub.add_parser('set-tier', help="change an account's tier")
set_tier.add_argument('username')
set_tier.add_argument('tier', choices=TIERS)
set_tier.set_defaults(func=cmd_set_tier)
args = parser.parse_args(argv)
auth_db.init_db()
args.func(args)
if __name__ == '__main__':
main()
+81 -6
View File
@@ -181,7 +181,7 @@ def create_user(username, email, password):
VALUES (?, ?, ?, 0)
''', (username, email, password_hash))
return True, "Registration successful! Please wait for admin verification.", cursor.lastrowid
return True, "Account created.", cursor.lastrowid
except sqlite3.IntegrityError as e:
if 'username' in str(e):
@@ -192,10 +192,28 @@ def create_user(username, email, password):
print(f"Registration error: {e}")
return False, "An error occurred during registration", None
def authenticate_user(username, password):
UNVERIFIED_EMAIL_MESSAGE = (
"Please verify your email address first: check your inbox (and spam folder) "
"for the link we sent. Registering again with the same email sends a new one."
)
UNVERIFIED_NO_EMAIL_MESSAGE = (
"Your account hasn't been approved yet. This LibreCrawl server can't send "
"verification emails, so whoever runs it needs to approve the account "
"(python manage.py approve <username>)."
)
def authenticate_user(username, password, email_configured=True):
"""
Authenticate a user login attempt
Returns (success, message, user_data)
email_configured: whether this server can send verification emails. When it
can't, an unverified account can only be approved by an admin, so if the
instance has no admin yet, the account logging in claims it (see
claim_first_admin). That un-sticks self-hosted installs where the owner
registered before this existed.
"""
try:
with get_db() as conn:
@@ -215,10 +233,19 @@ def authenticate_user(username, password):
if not verify_password(password, user['password_hash']):
return False, "Invalid username or password", None
# Check if user is verified
if user['verified'] != 1:
return False, "Account not verified yet. Please wait for admin approval.", None
# Check if user is verified
tier = user['tier']
if user['verified'] != 1:
if email_configured:
return False, UNVERIFIED_EMAIL_MESSAGE, None
if not claim_first_admin(user['id']):
return False, UNVERIFIED_NO_EMAIL_MESSAGE, None
tier = 'admin'
print(f"No admin account existed and email is not configured: "
f"'{user['username']}' is now the admin of this instance")
with get_db() as conn:
cursor = conn.cursor()
# Update last login time
cursor.execute('''
UPDATE users
@@ -230,7 +257,7 @@ def authenticate_user(username, password):
'id': user['id'],
'username': user['username'],
'email': user['email'],
'tier': user['tier'] or 'guest'
'tier': tier or 'guest'
}
return True, "Login successful", user_data
@@ -288,6 +315,54 @@ def verify_user(user_id):
print(f"Error verifying user: {e}")
return False, str(e)
# Accounts the app creates for itself in local mode (local@localhost) and
# skip-auth mode (<name>@skipauth.local) are admins nobody can log in to with a
# password, so they don't count as "this instance already has an admin".
_SYNTHETIC_ADMIN_EMAIL_PATTERNS = ('%@localhost', '%@skipauth.local')
def has_admin(exclude_user_id=None):
"""True if a verified admin account exists that a person can log in to."""
with get_db() as conn:
return _has_admin(conn.cursor(), exclude_user_id)
def _has_admin(cursor, exclude_user_id=None):
cursor.execute('''
SELECT 1 FROM users
WHERE tier = 'admin' AND verified = 1
AND email NOT LIKE ? AND email NOT LIKE ?
AND id != ?
LIMIT 1
''', (*_SYNTHETIC_ADMIN_EMAIL_PATTERNS, exclude_user_id if exclude_user_id is not None else -1))
return cursor.fetchone() is not None
def claim_first_admin(user_id):
"""
Make `user_id` a verified admin if the instance has no admin yet.
Self-hosted installs without SMTP can't verify anyone by email, and there is
no admin UI, so without this the owner's own account is stuck unverified on
the guest tier forever. Only the first account gets this: the check and the
update run under one write lock, so two simultaneous registrations can't
both become admin. Callers only use it when email is NOT configured, so
servers that verify by email (e.g. a public instance) are unaffected.
Returns True if the user was promoted.
"""
try:
with get_db() as conn:
conn.execute('BEGIN IMMEDIATE')
cursor = conn.cursor()
if _has_admin(cursor, exclude_user_id=user_id):
return False
cursor.execute("UPDATE users SET verified = 1, tier = 'admin' WHERE id = ?", (user_id,))
return cursor.rowcount == 1
except Exception as e:
print(f"Error claiming first admin: {e}")
return False
def save_user_settings(user_id, settings_dict):
"""Save settings for a user (stores as JSON)"""
import json
+17 -2
View File
@@ -24,6 +24,21 @@ SMTP_FROM_NAME = get_env('SMTP_FROM_NAME', 'LibreCrawl')
MAIN_APP_URL = get_env('MAIN_APP_URL', 'https://crawl.librecrawl.com')
WORKSHOP_APP_URL = get_env('WORKSHOP_APP_URL', 'https://workshop.librecrawl.com')
# Values shipped in .env.example. Copying that file without filling these in
# must count as "not configured", otherwise every registration tries to log in
# to Gmail as your-email@gmail.com and the account is stuck unverified.
_PLACEHOLDER_SMTP_VALUES = {'your-email@gmail.com', 'your-app-password'}
def is_email_configured() -> bool:
"""True when SMTP credentials are set to something other than the
.env.example placeholders, i.e. verification emails can actually be sent."""
for value in (SMTP_USER, SMTP_PASSWORD):
value = (value or '').strip()
if not value or value in _PLACEHOLDER_SMTP_VALUES:
return False
return True
def send_verification_email(to_email: str, username: str, token: str, app_source: str = 'main', is_resend: bool = False) -> Tuple[bool, str]:
"""
Send verification email to user
@@ -37,7 +52,7 @@ def send_verification_email(to_email: str, username: str, token: str, app_source
Returns:
(success, message)
"""
if not SMTP_USER or not SMTP_PASSWORD:
if not is_email_configured():
print("Warning: SMTP credentials not configured. Email not sent.")
print(f"Verification link would be: {MAIN_APP_URL}/verify?token={token}")
return False, "Email service not configured"
@@ -208,7 +223,7 @@ def send_welcome_email(to_email: str, username: str, app_source: str = 'main') -
Returns:
(success, message)
"""
if not SMTP_USER or not SMTP_PASSWORD:
if not is_email_configured():
return False, "Email service not configured"
try:
+93
View File
@@ -837,6 +837,98 @@ def test_ngram_extraction():
srv.shutdown()
def test_self_hosted_accounts_without_email():
"""Discussion #100: on a self-hosted server without SMTP, a registered
account sat unverified on the guest tier forever, with a login message
telling the owner to wait for an admin that didn't exist."""
import tempfile
import manage
from src import auth_db, crawl_db, email_service
saved = (auth_db.DB_FILE, crawl_db.DB_FILE, email_service.SMTP_USER, email_service.SMTP_PASSWORD)
tmp = tempfile.TemporaryDirectory()
try:
# Placeholder values from .env.example are "not configured".
email_service.SMTP_USER, email_service.SMTP_PASSWORD = 'your-email@gmail.com', 'your-app-password'
placeholders_off = not email_service.is_email_configured()
email_service.SMTP_USER, email_service.SMTP_PASSWORD = 'me@example.com', 'hunter22'
real_on = email_service.is_email_configured()
email_service.SMTP_USER, email_service.SMTP_PASSWORD = '', ''
result('placeholder SMTP values count as not configured', placeholders_off and real_on)
def fresh_db(name):
auth_db.DB_FILE = crawl_db.DB_FILE = os.path.join(tmp.name, name)
auth_db.init_db()
def row(username):
with auth_db.get_db() as conn:
return conn.execute('SELECT verified, tier FROM users WHERE username = ?',
(username,)).fetchone()
# A fresh install that once ran in local mode: the synthetic
# local@localhost admin must not count as "already has an admin".
fresh_db('fresh.db')
with auth_db.get_db() as conn:
conn.execute("INSERT INTO users (username, email, password_hash, verified, tier) "
"VALUES ('local', 'local@localhost', 'x', 1, 'admin')")
ok, _, owner_id = auth_db.create_user('owner', 'owner@example.com', 'password123')
claimed = ok and auth_db.claim_first_admin(owner_id)
r = row('owner')
result('first account becomes a verified admin',
claimed and r['verified'] == 1 and r['tier'] == 'admin', str(dict(r)))
ok, msg, user = auth_db.authenticate_user('owner', 'password123', email_configured=False)
result('first admin can log in', ok and user['tier'] == 'admin', msg)
_, _, second_id = auth_db.create_user('second', 'second@example.com', 'password123')
second_claimed = auth_db.claim_first_admin(second_id)
ok, msg, _ = auth_db.authenticate_user('second', 'password123', email_configured=False)
result('later accounts are not promoted and get an honest message',
not second_claimed and not ok and msg == auth_db.UNVERIFIED_NO_EMAIL_MESSAGE
and 'admin approval' not in msg, msg)
manage.main(['approve', 'second'])
ok, msg, user = auth_db.authenticate_user('second', 'password123', email_configured=False)
result('manage.py approve lets the account log in as tier user',
ok and user['tier'] == 'user', msg)
# An install that registered before this fix: the owner's account is
# unverified with no admin anywhere. Logging in claims admin.
fresh_db('stuck.db')
auth_db.create_user('stuck', 'stuck@example.com', 'password123')
ok, msg, user = auth_db.authenticate_user('stuck', 'password123', email_configured=False)
r = row('stuck')
result('existing stuck account claims admin on login',
ok and user['tier'] == 'admin' and r['verified'] == 1, msg)
# Servers that verify by email are unaffected.
fresh_db('smtp.db')
auth_db.create_user('mailer', 'mailer@example.com', 'password123')
ok, msg, _ = auth_db.authenticate_user('mailer', 'password123', email_configured=True)
r = row('mailer')
result('with SMTP, unverified accounts are told to check email and stay unverified',
not ok and msg == auth_db.UNVERIFIED_EMAIL_MESSAGE and r['verified'] == 0, msg)
# Two registrations racing for the empty admin seat: exactly one wins.
fresh_db('race.db')
ids = [auth_db.create_user(f'racer{i}', f'racer{i}@example.com', 'password123')[2]
for i in range(8)]
wins = []
threads = [threading.Thread(target=lambda uid=uid: wins.append(auth_db.claim_first_admin(uid)))
for uid in ids]
for t in threads:
t.start()
for t in threads:
t.join()
with auth_db.get_db() as conn:
admins = conn.execute("SELECT count(*) FROM users WHERE tier = 'admin'").fetchone()[0]
result('concurrent registrations produce exactly one admin',
wins.count(True) == 1 and admins == 1, f'{wins.count(True)} claims, {admins} admins')
finally:
auth_db.DB_FILE, crawl_db.DB_FILE, email_service.SMTP_USER, email_service.SMTP_PASSWORD = saved
tmp.cleanup()
def _playwright_available():
try:
import playwright # noqa: F401
@@ -861,6 +953,7 @@ TESTS = (
test_custom_extraction,
test_ngram_analyzer,
test_ngram_extraction,
test_self_hosted_accounts_without_email,
)