Skip to content

Commit 68bb591

Browse files
matteiusclaude
andcommitted
feat: brand-aware subjects, masthead, and body copy in transactional emails
Emails sent on behalf of LightNVR or OwlBooks now read as those brands end-to-end — subject line, masthead link, and inline copy — instead of "OpenSensor.io" leaking through. Pipeline: request host -> Brand -> EmailContext.brand (BrandEmailContext) templates: {{ brand.name if brand else tenant.name }} masthead link: {{ brand.application_url if brand else 'https://opensensor.io' }} - New BrandEmailContext schema (id, name, host, application_url, logo_url) - EmailContext gains brand: BrandEmailContext | None = None - TaskBase._get_brand now accepts the brand_id string directly; tasks fetch the brand once and feed it to both the context and the sender resolver (replacing the old _resolve_email_sender by-id helper). - FS templates updated for new defaults; initializer subjects updated for fresh installs; migration f3b1c2d4a5e6 UPDATEs the four existing rows in the production DB so the change activates immediately on deploy. OpenSensor brand has no overrides, so emails for opensensor.io users keep reading "OpenSensor.io" via the tenant.name fallback path. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 8d08b93 commit 68bb591

13 files changed

Lines changed: 152 additions & 19 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
"""Brandify transactional email templates (subjects + masthead + body)
2+
3+
Revision ID: f3b1c2d4a5e6
4+
Revises: e9a1c3b7d2f4
5+
Create Date: 2026-05-02 14:00:00.000000
6+
7+
Refreshes the four seeded email_templates rows in place so they read brand
8+
from the render context with a tenant.name fallback. The render path now
9+
populates `brand` whenever a transactional email is triggered through a
10+
Brand's host. Without this update, production keeps the original Fief seed
11+
(masthead links to https://example.com, subjects say "OpenSensor.io")
12+
because EmailTemplateInitializer only seeds rows when missing.
13+
14+
NOTE: this overwrites any customization made via the admin UI for these
15+
four template types. Current DB content matches the unmodified Fief seed,
16+
so this is safe at the time of writing.
17+
18+
"""
19+
20+
from pathlib import Path
21+
22+
import sqlalchemy as sa
23+
from alembic import op
24+
25+
# revision identifiers, used by Alembic.
26+
revision = "f3b1c2d4a5e6"
27+
down_revision = "e9a1c3b7d2f4"
28+
branch_labels = None
29+
depends_on = None
30+
31+
32+
# Templates dir relative to this migration: fief/alembic/versions/X.py
33+
# parents[2] resolves to the `fief` package root.
34+
_TEMPLATES_DIR = (
35+
Path(__file__).resolve().parents[2] / "services" / "email_template" / "templates"
36+
)
37+
38+
39+
_NEW_SUBJECTS = {
40+
"WELCOME": "Welcome to {{ brand.name if brand else tenant.name }}",
41+
"VERIFY_EMAIL": (
42+
"Verify your email for your {{ brand.name if brand else tenant.name }} account"
43+
),
44+
"FORGOT_PASSWORD": "Reset your {{ brand.name if brand else tenant.name }} password",
45+
}
46+
47+
_PRIOR_SUBJECTS = {
48+
"WELCOME": "Welcome to {{ tenant.name }}",
49+
"VERIFY_EMAIL": "Verify your email for your {{ tenant.name }}'s account",
50+
"FORGOT_PASSWORD": "Reset your {{ tenant.name }}'s password",
51+
}
52+
53+
54+
def _read_template(filename: str) -> str:
55+
return (_TEMPLATES_DIR / filename).read_text()
56+
57+
58+
def upgrade():
59+
table_prefix = op.get_context().opts["table_prefix"]
60+
table = f"{table_prefix}email_templates"
61+
62+
op.execute(
63+
sa.text(f"UPDATE {table} SET content = :c WHERE type = 'BASE'").bindparams(
64+
c=_read_template("base.html")
65+
)
66+
)
67+
op.execute(
68+
sa.text(
69+
f"UPDATE {table} SET subject = :s, content = :c WHERE type = 'WELCOME'"
70+
).bindparams(s=_NEW_SUBJECTS["WELCOME"], c=_read_template("welcome.html"))
71+
)
72+
op.execute(
73+
sa.text(
74+
f"UPDATE {table} SET subject = :s, content = :c WHERE type = 'VERIFY_EMAIL'"
75+
).bindparams(
76+
s=_NEW_SUBJECTS["VERIFY_EMAIL"], c=_read_template("verify_email.html")
77+
)
78+
)
79+
op.execute(
80+
sa.text(
81+
f"UPDATE {table} "
82+
"SET subject = :s, content = :c WHERE type = 'FORGOT_PASSWORD'"
83+
).bindparams(
84+
s=_NEW_SUBJECTS["FORGOT_PASSWORD"],
85+
c=_read_template("forgot_password.html"),
86+
)
87+
)
88+
89+
90+
def downgrade():
91+
# Best-effort downgrade: restore the prior subject lines. We cannot
92+
# restore the prior content bodies precisely without bundling them here,
93+
# so a roll-back leaves the brand-aware content in place — harmless
94+
# because a None brand falls back to tenant.name.
95+
table_prefix = op.get_context().opts["table_prefix"]
96+
table = f"{table_prefix}email_templates"
97+
for type_, subject in _PRIOR_SUBJECTS.items():
98+
op.execute(
99+
sa.text(f"UPDATE {table} SET subject = :s WHERE type = :t").bindparams(
100+
s=subject, t=type_
101+
)
102+
)

‎fief/schemas/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from fief.schemas import (
22
auth,
3+
brand,
34
client,
45
email_template,
56
generics,
@@ -19,6 +20,7 @@
1920

2021
__all__ = [
2122
"auth",
23+
"brand",
2224
"client",
2325
"email_template",
2426
"generics",

‎fief/schemas/brand.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from pydantic import UUID4, HttpUrl
2+
3+
from fief.schemas.generics import BaseModel
4+
5+
6+
class BrandEmailContext(BaseModel):
7+
"""Brand fields exposed to email templates so transactional emails can
8+
address the user under the brand they signed up under (LightNVR,
9+
OwlBooks, etc.) instead of the underlying tenant name."""
10+
11+
id: UUID4
12+
name: str
13+
host: str
14+
application_url: HttpUrl
15+
logo_url: HttpUrl | None = None

‎fief/services/email_template/contexts.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from fief.db import AsyncSession
66
from fief.repositories import TenantRepository, UserRepository
7+
from fief.schemas.brand import BrandEmailContext
78
from fief.schemas.tenant import Tenant
89
from fief.schemas.user import UserEmailContext
910
from fief.services.email_template.types import EmailTemplateType
@@ -12,6 +13,7 @@
1213
class EmailContext(BaseModel):
1314
tenant: Tenant
1415
user: UserEmailContext
16+
brand: BrandEmailContext | None = None
1517
model_config = ConfigDict(from_attributes=True)
1618

1719
@classmethod

‎fief/services/email_template/initializer.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,23 @@ async def init_templates(self):
2222
if await self.repository.get_by_type(EmailTemplateType.WELCOME) is None:
2323
welcome = EmailTemplate(
2424
type=EmailTemplateType.WELCOME,
25-
subject="Welcome to {{ tenant.name }}",
25+
subject="Welcome to {{ brand.name if brand else tenant.name }}",
2626
content=self._load_template("welcome.html"),
2727
)
2828
await self.repository.create(welcome)
2929

3030
if await self.repository.get_by_type(EmailTemplateType.VERIFY_EMAIL) is None:
3131
verify_email = EmailTemplate(
3232
type=EmailTemplateType.VERIFY_EMAIL,
33-
subject="Verify your email for your {{ tenant.name }}'s account",
33+
subject="Verify your email for your {{ brand.name if brand else tenant.name }} account",
3434
content=self._load_template("verify_email.html"),
3535
)
3636
await self.repository.create(verify_email)
3737

3838
if await self.repository.get_by_type(EmailTemplateType.FORGOT_PASSWORD) is None:
3939
forgot_password = EmailTemplate(
4040
type=EmailTemplateType.FORGOT_PASSWORD,
41-
subject="Reset your {{ tenant.name }}'s password",
41+
subject="Reset your {{ brand.name if brand else tenant.name }} password",
4242
content=self._load_template("forgot_password.html"),
4343
)
4444
await self.repository.create(forgot_password)

‎fief/services/email_template/templates/base.html‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -465,8 +465,8 @@
465465
<table class="email-content" width="100%" cellpadding="0" cellspacing="0" role="presentation">
466466
<tr>
467467
<td class="email-masthead">
468-
<a href="https://opensensor.io" class="f-fallback email-masthead_name">
469-
{{ tenant.name }}
468+
<a href="{{ brand.application_url if brand else 'https://opensensor.io' }}" class="f-fallback email-masthead_name">
469+
{{ brand.name if brand else tenant.name }}
470470
</a>
471471
</td>
472472
</tr>

‎fief/services/email_template/templates/forgot_password.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
{% block main %}
66
<h1>Reset your password</h1>
7-
<p>You recently requested to reset your password for your {{ tenant.name }} account. Use the button below to reset it. <strong>This password reset link is only valid for the next hour.</strong></p>
7+
<p>You recently requested to reset your password for your {{ brand.name if brand else tenant.name }} account. Use the button below to reset it. <strong>This password reset link is only valid for the next hour.</strong></p>
88
<table class="body-action" align="center" width="100%" cellpadding="0" cellspacing="0" role="presentation">
99
<tr>
1010
<td align="center">

‎fief/services/email_template/templates/verify_email.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
{% block main %}
66
<h1>Verify your email address</h1>
7-
<p>You recently created or updated your email on your {{ tenant.name }}'s account. To verify your email address, please enter the verification code below.</p>
7+
<p>You recently created or updated your email on your {{ brand.name if brand else tenant.name }} account. To verify your email address, please enter the verification code below.</p>
88
<table class="discount" align="center" width="100%" cellpadding="0" cellspacing="0" role="presentation">
99
<tr>
1010
<td align="center">
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
{% extends "BASE" %}
22

3-
{% block preheader %}Welcome to {{ tenant.name }}! We're thrilled to have you on board.{% endblock %}
3+
{% block preheader %}Welcome to {{ brand.name if brand else tenant.name }}! We're thrilled to have you on board.{% endblock %}
44

55
{% block main %}
66
<h1>Welcome!</h1>
7-
<p>Welcome to {{ tenant.name }}! We're thrilled to have you on board.</p>
7+
<p>Welcome to {{ brand.name if brand else tenant.name }}! We're thrilled to have you on board.</p>
88
{% endblock %}

‎fief/tasks/base.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -112,19 +112,19 @@ async def _get_tenant(self, tenant_id: UUID4) -> Tenant:
112112
raise TaskError()
113113
return tenant
114114

115-
async def _get_brand(self, brand_id: UUID4) -> Brand | None:
115+
async def _get_brand(self, brand_id: str | None) -> Brand | None:
116+
if brand_id is None:
117+
return None
116118
async with self.get_main_session() as session:
117119
repository = BrandRepository(session)
118120
return await repository.get_by_id(
119-
brand_id, (selectinload(Brand.email_domain),)
121+
uuid.UUID(brand_id), (selectinload(Brand.email_domain),)
120122
)
121123

122-
async def _resolve_email_sender(
123-
self, tenant: Tenant, brand_id: str | None
124+
@staticmethod
125+
def _resolve_email_sender(
126+
tenant: Tenant, brand: Brand | None
124127
) -> tuple[str, str | None]:
125-
if brand_id is None:
126-
return tenant.get_email_sender()
127-
brand = await self._get_brand(uuid.UUID(brand_id))
128128
if brand is None:
129129
return tenant.get_email_sender()
130130
return brand.get_email_sender(fallback_tenant=tenant)

0 commit comments

Comments
 (0)