Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2284f49
feat: configure production database cache auth and logging
ashutoshpalhare Oct 27, 2026
082b3a2
build: add PostgreSQL and auth protection dependencies
ashutoshpalhare Oct 27, 2026
68d81ee
feat: add account password recovery routes
ashutoshpalhare Oct 27, 2026
97dd543
feat: rate limit signup and log security events
ashutoshpalhare Oct 27, 2026
2f48c4d
docs: document production database cache and email settings
ashutoshpalhare Oct 27, 2026
ace8de6
feat: add password_reset_form.html
ashutoshpalhare Oct 27, 2026
23dbbc1
feat: add password_reset_done.html
ashutoshpalhare Oct 27, 2026
a24ce86
feat: add password_reset_confirm.html
ashutoshpalhare Oct 27, 2026
c778ed0
feat: add password_reset_complete.html
ashutoshpalhare Oct 27, 2026
ebf3421
feat: add password_reset_email.html
ashutoshpalhare Oct 27, 2026
ddad5db
feat: add password_reset_subject.txt
ashutoshpalhare Oct 27, 2026
6e24a2a
feat: add backup_db.py
ashutoshpalhare Oct 27, 2026
04047ef
feat: add restore_db.py
ashutoshpalhare Oct 27, 2026
6101ab9
feat: link password recovery from sign-in
ashutoshpalhare Oct 27, 2026
f9d3463
build: include Redis client for shared cache support
ashutoshpalhare Oct 27, 2026
7cd5af5
security: require TLS for production PostgreSQL connections
ashutoshpalhare Oct 27, 2026
f6b8cac
feat: log privacy-conscious authentication security events
ashutoshpalhare Oct 27, 2026
4db4080
feat: register account security signal handlers
ashutoshpalhare Oct 27, 2026
7619e2c
test: cover password recovery and email privacy
ashutoshpalhare Oct 27, 2026
6d0e15e
fix: ensure account security signal handlers are loaded
ashutoshpalhare Oct 27, 2026
804706d
docs: document production database backups recovery and auth controls
ashutoshpalhare Oct 27, 2026
fea3194
security: keep database backups out of version control
ashutoshpalhare Oct 27, 2026
ecb9b59
fix: specify authentication backend for signup login
ashutoshpalhare Oct 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,20 @@ DJANGO_BEHIND_PROXY=False
DJANGO_HSTS_SECONDS=31536000
DJANGO_ADMIN_URL=admin/
DJANGO_DB_PATH=
# Optional PostgreSQL URL, e.g. postgres://user:password@host:5432/ember
DATABASE_URL=
DB_CONN_MAX_AGE=60
# Optional Redis URL for a shared cache/rate-limit cache in multi-worker deployments
CACHE_URL=
AXES_FAILURE_LIMIT=5
AXES_COOLOFF_HOURS=1
DJANGO_LOG_LEVEL=INFO
# Production SMTP for password-reset email
DEFAULT_FROM_EMAIL=Ember Notes <no-reply@example.com>
EMAIL_HOST=
EMAIL_PORT=587
EMAIL_HOST_USER=
EMAIL_HOST_PASSWORD=
EMAIL_USE_TLS=True
EMAIL_USE_SSL=False
EMAIL_TIMEOUT=10
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ staticfiles/

# Ignore setup script
setup_history.py

# Database backups and pre-restore safety copies contain private user data
/backups/
*.pre-restore-*
63 changes: 58 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

A self-hostable, Django-powered notes app with a focused dark interface, autosave, tags, pinning, archive, trash, search, sorting, and per-user note isolation.

> **Project status:** Phase 1 stabilization and documentation. Review the deployment and persistence checklist before hosting real user data.
> **Project status:** Phase 2 production-readiness work. Configure a persistent database, shared cache, SMTP and verified backups before hosting real user data.

## Features

- Account signup, login, and logout
- Account signup, login, logout, password-reset emails, and reset-token flow
- Brute-force protection for login attempts and IP-based signup throttling
- Privacy-conscious authentication event logs that omit credentials and note content
- Configurable PostgreSQL connections and optional Redis-backed shared cache
- SQLite backup/restore commands with integrity checks and a pre-restore safety copy
- Create and edit notes with debounced autosave and manual save
- Save-state feedback, retry on failure, and flush pending edits before destructive actions
- Tags, pinned notes, archive, recoverable trash, and permanent deletion
Expand All @@ -18,7 +22,7 @@ A self-hostable, Django-powered notes app with a focused dark interface, autosav

- Python 3.10+ (use a supported Python version compatible with your deployment)
- Django 5.2
- SQLite by default
- SQLite for local development; PostgreSQL supported through `DATABASE_URL`
- WhiteNoise for static files
- Gunicorn as the WSGI server

Expand Down Expand Up @@ -96,7 +100,15 @@ The deploy check is expected to report configuration warnings until the hosting
| `DJANGO_BEHIND_PROXY` | Enables forwarded-protocol handling only when the trusted proxy is configured correctly. |
| `DJANGO_HSTS_SECONDS` | HSTS duration in production; only enable long durations after HTTPS is confirmed. |
| `DJANGO_ADMIN_URL` | Admin URL path. This is not a substitute for authentication or rate limiting. |
| `DJANGO_DB_PATH` | Optional path to the SQLite database file. |
| `DJANGO_DB_PATH` | Optional path to the SQLite database file when `DATABASE_URL` is unset. |
| `DATABASE_URL` | Optional PostgreSQL connection URL; TLS is required by the app in production. |
| `DB_CONN_MAX_AGE` | Persistent database connection lifetime in seconds (default 60). |
| `CACHE_URL` | Optional Redis URL for a shared cache; configure this for reliable IP rate limits across multiple workers. |
| `AXES_FAILURE_LIMIT` | Failed login attempts before lockout (default 5). |
| `AXES_COOLOFF_HOURS` | Login lockout duration in hours (default 1). |
| `DEFAULT_FROM_EMAIL` | Sender shown on password-reset emails. |
| `EMAIL_HOST`, `EMAIL_PORT`, `EMAIL_HOST_USER`, `EMAIL_HOST_PASSWORD` | Production SMTP connection settings; keep credentials in the hosting secret manager. |
| `EMAIL_USE_TLS`, `EMAIL_USE_SSL`, `EMAIL_TIMEOUT` | SMTP transport and timeout settings. |
| `DJANGO_LOG_LEVEL` | Python root logger level. Do not log note contents or credentials. |

The application currently configures SQLite in `ember/settings.py`. `DJANGO_DB_PATH` changes the file location; it does **not** make storage persistent on its own. On hosting platforms with ephemeral filesystems, SQLite data can disappear during redeploys/restarts. Before production use, confirm persistent storage or migrate to a managed database such as PostgreSQL, and test a restore from backup.
Expand All @@ -112,11 +124,52 @@ Do not treat a successful local run as proof of production readiness.
- [ ] Configure scheduled, access-controlled backups and perform a restore drill.
- [ ] Apply migrations during deployment and collect static files with `python manage.py collectstatic --noinput`.
- [ ] Run `python manage.py check --deploy` against the actual production environment and resolve applicable warnings.
- [ ] Add rate limiting for authentication endpoints and a password reset/account recovery flow before public launch.
- [ ] Confirm login lockout and signup rate limits with your actual shared-cache/worker topology.
- [ ] Configure production SMTP and test password recovery end to end.
- [ ] Confirm logs do not contain secrets, passwords, session tokens, or private note content.
- [ ] Schedule `python manage.py purge_trash --days 30` only after documenting its permanent-deletion policy and ensuring backups exist.
- [ ] Verify registration, login/logout, CRUD, autosave, trash/restore, search, mobile layout, and error states in a real browser.

## Database backups and restore

### SQLite (local/single-instance only)

Create an integrity-checked snapshot:

```bash
python manage.py backup_db
python manage.py backup_db --output /secure/backups/ember.sqlite3
```

The default destination is `backups/`, which is excluded from Git. Backups contain private note content and account data: restrict access, encrypt them at rest, and copy them to storage independent of the app host. Never commit or publicly serve backups.

To restore, **stop every app worker first** and verify the chosen backup. The command requires an explicit destructive confirmation and preserves the previous live database as a safety copy when one exists:

```bash
python manage.py restore_db /secure/backups/ember.sqlite3 --confirm
```

The restore command supports SQLite only. Run a restore drill on a non-production copy before relying on it; a successful backup is not proof that recovery works.

### PostgreSQL (recommended for production)

Use managed database snapshots/PITR when your provider supports them. As a portable manual alternative, use the provider's recommended `pg_dump` and `pg_restore` workflow from a secured host:

```bash
pg_dump --format=custom --file=ember-backup.dump "$DATABASE_URL"
# Destructive restore: stop app workers and confirm the target database first.
pg_restore --clean --if-exists --no-owner --dbname="$DATABASE_URL" ember-backup.dump
```

Keep dumps encrypted and access-controlled. A restore can replace database objects/data; never test it against the only production database. Schedule backups, monitor their success, and periodically restore into an isolated database.

## Authentication protection and email

- Login failures are tracked by Django Axes; the default lockout is five failures for the username/IP combination for one hour.
- Signup POSTs are limited to five per IP per hour. Configure `CACHE_URL` to Redis for shared rate-limit state across multiple workers; the local-memory fallback is not shared between processes.
- Password reset uses Django's token-based built-in flow. Unknown email addresses receive the same confirmation page to reduce account enumeration. Production must configure working SMTP credentials; development prints reset emails to the console.
- Authentication logs record event types only; they intentionally omit usernames, passwords, session tokens, and note contents. Protect and rotate host logs as part of operations.

## Data and privacy notes

Notes are private to the authenticated owner at the application-query level. This is not end-to-end encryption: operators with database access may be able to read stored note content. Do not promise encrypted notes unless encryption and key management are implemented and independently reviewed.
Expand Down
3 changes: 3 additions & 0 deletions accounts/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class AccountsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "accounts"

def ready(self):
from . import security # noqa: F401
22 changes: 22 additions & 0 deletions accounts/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Privacy-conscious security event logging; never log note contents or credentials."""
import logging

from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
from django.dispatch import receiver

logger = logging.getLogger("accounts.security")


@receiver(user_logged_in, dispatch_uid="accounts.log_login_success")
def log_login_success(sender, request, user, **kwargs):
logger.info("authentication_succeeded")


@receiver(user_login_failed, dispatch_uid="accounts.log_login_failure")
def log_login_failure(sender, credentials, request, **kwargs):
logger.warning("authentication_failed")


@receiver(user_logged_out, dispatch_uid="accounts.log_logout")
def log_logout(sender, request, user, **kwargs):
logger.info("authentication_ended")
42 changes: 42 additions & 0 deletions accounts/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase, override_settings
from django.urls import reverse


User = get_user_model()


@override_settings(
EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
DEFAULT_FROM_EMAIL="Ember Notes <no-reply@example.com>",
)
class PasswordRecoveryTests(TestCase):
def setUp(self):
self.user = User.objects.create_user(
username="recovery-user",
email="recovery@example.com",
password="Strong-test-password-482!",
)

def test_known_email_receives_reset_link(self):
response = self.client.post(
reverse("password_reset"),
{"email": self.user.email},
)
self.assertRedirects(response, reverse("password_reset_done"))
self.assertEqual(len(mail.outbox), 1)
self.assertIn("/accounts/reset/", mail.outbox[0].body)

def test_unknown_email_uses_same_success_page_without_sending_mail(self):
response = self.client.post(
reverse("password_reset"),
{"email": "unknown@example.com"},
)
self.assertRedirects(response, reverse("password_reset_done"))
self.assertEqual(len(mail.outbox), 0)

def test_reset_form_and_completion_pages_render(self):
self.assertEqual(self.client.get(reverse("password_reset")).status_code, 200)
self.assertEqual(self.client.get(reverse("password_reset_done")).status_code, 200)
self.assertEqual(self.client.get(reverse("password_reset_complete")).status_code, 200)
10 changes: 9 additions & 1 deletion accounts/views.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import logging

from django.contrib.auth import login
from django.shortcuts import redirect, render
from django_ratelimit.decorators import ratelimit

from .forms import SignupForm

security_logger = logging.getLogger("accounts.security")


@ratelimit(key="ip", rate="5/h", method="POST", block=True)
def signup(request):
if request.user.is_authenticated:
return redirect("notes:list")
form = SignupForm(request.POST or None)
if request.method == "POST" and form.is_valid():
login(request, form.save())
user = form.save()
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
security_logger.info("account_signup_succeeded")
return redirect("notes:list")
return render(request, "registration/signup.html", {"form": form})
78 changes: 68 additions & 10 deletions ember/settings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Ember settings. All sensitive values come from environment variables (or a local .env)."""
"""Ember settings. Sensitive configuration is read from environment variables."""
import os
import sys
from pathlib import Path
Expand Down Expand Up @@ -55,7 +55,8 @@ def env_list(name, default=""):
"django.contrib.messages",
"django.contrib.humanize",
"django.contrib.staticfiles",
"accounts",
"axes",
"accounts.apps.AccountsConfig",
"notes",
]

Expand All @@ -68,6 +69,7 @@ def env_list(name, default=""):
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"axes.middleware.AxesMiddleware",
]

ROOT_URLCONF = "ember.urls"
Expand All @@ -89,12 +91,45 @@ def env_list(name, default=""):
},
]

DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.environ.get("DJANGO_DB_PATH") or BASE_DIR / "db.sqlite3",
DATABASE_URL = os.environ.get("DATABASE_URL", "").strip()
if DATABASE_URL:
import dj_database_url
DATABASES = {"default": dj_database_url.parse(
DATABASE_URL, conn_max_age=int(os.environ.get("DB_CONN_MAX_AGE", "60")),
conn_health_checks=True, ssl_require=PROD,
)}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.environ.get("DJANGO_DB_PATH") or BASE_DIR / "db.sqlite3",
}
}
}

# Configure a shared cache (recommended for multi-worker production) or safe local fallback.
CACHE_URL = os.environ.get("CACHE_URL", "").strip()
if CACHE_URL.startswith(("redis://", "rediss://")):
CACHES = {"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": CACHE_URL,
"KEY_PREFIX": "ember",
}}
else:
CACHES = {"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "ember-local-cache",
"KEY_PREFIX": "ember",
}}

AUTHENTICATION_BACKENDS = [
"axes.backends.AxesStandaloneBackend",
"django.contrib.auth.backends.ModelBackend",
]
AXES_FAILURE_LIMIT = int(os.environ.get("AXES_FAILURE_LIMIT", "5"))
AXES_COOLOFF_TIME = int(os.environ.get("AXES_COOLOFF_HOURS", "1"))
AXES_RESET_ON_SUCCESS = True
AXES_LOCKOUT_PARAMETERS = ["username", "ip_address"]
AXES_ENABLE_ADMIN = True

AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
Expand All @@ -106,9 +141,22 @@ def env_list(name, default=""):
LOGIN_URL = "login"
LOGIN_REDIRECT_URL = "notes:list"
LOGOUT_REDIRECT_URL = "login"
PASSWORD_RESET_TIMEOUT = 3600
DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", "Ember Notes <no-reply@example.com>")
if DEBUG:
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
else:
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = os.environ.get("EMAIL_HOST", "")
EMAIL_PORT = int(os.environ.get("EMAIL_PORT", "587"))
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", "")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", "")
EMAIL_USE_TLS = env_bool("EMAIL_USE_TLS", True)
EMAIL_USE_SSL = env_bool("EMAIL_USE_SSL", False)
EMAIL_TIMEOUT = int(os.environ.get("EMAIL_TIMEOUT", "10"))

LANGUAGE_CODE = "en-us"
TIME_ZONE = os.environ.get("DJANGO_TIME_ZONE", "UTC")
TIME_ZONE = os.environ.get("DJANGO_TIME_ZONE", "Asia/Kolkata")
USE_I18N = True
USE_TZ = True

Expand Down Expand Up @@ -136,9 +184,19 @@ def env_list(name, default=""):
if env_bool("DJANGO_BEHIND_PROXY", False):
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

LOG_LEVEL = os.environ.get("DJANGO_LOG_LEVEL", "INFO").upper()
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"root": {"handlers": ["console"], "level": os.environ.get("DJANGO_LOG_LEVEL", "INFO")},
"formatters": {
"standard": {"format": "%(asctime)s %(levelname)s %(name)s %(message)s"},
},
"handlers": {
"console": {"class": "logging.StreamHandler", "formatter": "standard"},
},
"root": {"handlers": ["console"], "level": LOG_LEVEL},
"loggers": {
"django.security": {"handlers": ["console"], "level": "WARNING", "propagate": False},
"accounts.security": {"handlers": ["console"], "level": "INFO", "propagate": False},
},
}
17 changes: 17 additions & 0 deletions ember/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import include, path

urlpatterns = [
path(settings.ADMIN_URL, admin.site.urls),
path("accounts/", include("accounts.urls")),
path("accounts/password-reset/", auth_views.PasswordResetView.as_view(
template_name="registration/password_reset_form.html",
email_template_name="registration/password_reset_email.html",
subject_template_name="registration/password_reset_subject.txt",
success_url="/accounts/password-reset/done/",
), name="password_reset"),
path("accounts/password-reset/done/", auth_views.PasswordResetDoneView.as_view(
template_name="registration/password_reset_done.html",
), name="password_reset_done"),
path("accounts/reset/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(
template_name="registration/password_reset_confirm.html",
success_url="/accounts/reset/complete/",
), name="password_reset_confirm"),
path("accounts/reset/complete/", auth_views.PasswordResetCompleteView.as_view(
template_name="registration/password_reset_complete.html",
), name="password_reset_complete"),
path("", include("notes.urls")),
]
Loading
Loading