Contact: ontvangstadres uit de site-instellingen (instelling > env), PUT /contact-settings/recipient en Berichten-veld (CMS-U11)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+6
@@ -0,0 +1,6 @@
|
||||
# CMS-U11 — Recipient address from the site settings (summary)
|
||||
|
||||
- Backend: nullable `RecipientEmail` on `ContactSettings` (migration `ContactSettingsRecipient`); `IContactSettingsService.GetEffectiveRecipientAsync` (setting > env > none) and `SetRecipientAsync` (wakes the mail sender); `ContactMailSender` reads the recipient per send (`NotReadyReasonAsync`); `GET /contact-settings` + `recipientEmail`/`recipientSource` (the env address is never returned); `PUT /contact-settings/recipient`; OpenAPI regenerated.
|
||||
- Frontend: `RecipientCard` next to the form switch (field, save, back to the server setting, source text, client + server validation, translated), warning banner on the switch card while there is no address (no blocking). nl/en.
|
||||
- Tests (new/changed): resolution order, invalid stored value ignored, admin view never shows the env address, set/clear, signal, sender uses the setting without a restart, no address = not ready + nothing sent, controller (valid/trimmed/blank/invalid/CRLF/too long/missing body), pipeline on the real host (login/role, view, set/invalid/clear, no leak in the public token response, a stored-but-pending message goes out after the address is set), route-table test, OpenAPI snapshot; frontend (field, save, invalid client/server, clear, banner without blocking). The existing outgoing contact mail tests keep their intent (only their construction and the async `NotReadyReasonAsync` signature were adapted).
|
||||
- Decisions (approved): warn instead of block; the env address is not shown; the field sits on the Berichten page.
|
||||
@@ -109,7 +109,7 @@ CMS switch (not configuration): table `ContactSettings`, `PUT /contact-settings`
|
||||
Rebased onto `origin/master` `e671078` (merge of PR #11: identity-email-notifications + andreaslop-site-hosting). Conflicts: `aidlc-docs/active-features.md` (kept master's table, appended our row), `AvailabilityMiddleware` (kept their `CheckAdmin` / expired-token 401 behaviour, our marker block before it), `AddCmsRateLimiting.OnRejected` (kept their Retry-After logic for sliding windows, added the `60 s` fallback for policies without a wait and the problem+json body), `SlpModularCms.sln` (took master's, re-added the two Contact projects). No EF snapshot conflict (own contexts). Checklist steps 1 and 2 are DONE: `ContactRateLimitPartition.KeyFor` now returns `ClientPartitionKey.For(context)` and its test asserts different buckets per address. Still open: step 3 (`ForwardedHeaders:KnownProxies` per host), step 5 (`Contact:Enabled=true`), step 6 (CMS switch). `GET /System/capabilities` now carries `[PublicSiteEndpoint]` (never 503; separate commit). The pipeline tests for the management routes log in with a real user (the host validates every access token against its user and security stamp).
|
||||
|
||||
## 7. CMS-U5 additions (contact mail)
|
||||
- Env var `Contact__RecipientEmail` (SLP: environment only, like ASF). Optional `Contact__Mail__SweepSeconds|MaxAttempts|ClaimMinutes|BatchSize`, `Contact__Mail__BackoffMinutes__0..n`.
|
||||
- Recipient address: since CMS-U11 the **site setting wins over** the env var `Contact__RecipientEmail` (see section 9); the env var stays the default/fallback (SLP: environment only, like ASF). Optional `Contact__Mail__SweepSeconds|MaxAttempts|ClaimMinutes|BatchSize`, `Contact__Mail__BackoffMinutes__0..n`.
|
||||
- Mail itself needs the host's normal `Email:*` configuration; without it messages stay `pending` with `mailError: "disabled"`.
|
||||
- Detail: `nextMailAttemptAt`; resend: `mailError`. New migration `ContactMailClaim`.
|
||||
|
||||
@@ -144,3 +144,15 @@ With `Contact:Enabled=true` and `Captcha:Enabled=true` the host **refuses to sta
|
||||
- References `Modules.Contact`; section `Contact` in its `appsettings.json` (`Enabled:false`, `SiteId: andreaslop`), the three contact rate-limit policies. Capabilities now list `Contact`; the module does nothing and touches no database while `Contact:Enabled=false`.
|
||||
- Release conditions (also in the comment of that section): `ForwardedHeaders__KnownProxies__0` = reverse proxy (IIS) address first (otherwise the whole site shares one bucket); `Contact__RecipientEmail` (env only); mail via `Email__Smtp__*`, `App__PublicBaseUrl`; sender = `Email:FromAddress` or the address chosen in the site settings from `Email:AllowedFromAddresses` (set by environment for ASF); captcha settings above; then `Contact__Enabled=true` and the admin switch (Berichten).
|
||||
- Host tests (`Api.AndreaSlopFotografie.Tests/ContactHostTests.cs`, real MariaDB): closed by default; public routes stay reachable (200/202) while the availability gate is "not available" and the management routes answer 503; per-client buckets with a known proxy vs one shared bucket without.
|
||||
|
||||
## 9. CMS-U11 additions (recipient address from the site settings)
|
||||
|
||||
Order of precedence for the address contact mails are sent to: **site setting (CMS admin, Berichten) > `Contact__RecipientEmail` (environment) > none.** The setting changes without a restart (read on every send); an invalid stored value is ignored (falls back). Table `ContactSettings` gets a nullable `RecipientEmail` (migration `ContactSettingsRecipient`, additive).
|
||||
|
||||
| Method + path | Auth | Notes |
|
||||
|---|---|---|
|
||||
| `GET /contact-settings` | AdminOnly | now `{ enabled, hostEnabled, recipientEmail: string\|null, recipientSource: "setting"\|"config"\|"none" }`. `recipientEmail` is only the CMS setting; **the address from the environment is never returned** (source `config` = "set by the server configuration"). |
|
||||
| `PUT /contact-settings/recipient` `{ "recipientEmail": string\|null }` | AdminOnly | `200` same shape as GET; `null`/blank clears the setting (back to the environment default); trimmed; `EmailAddressRules`; `400` problem+json `errors.recipientEmail = ["invalid"]` or `["tooLong"]` (> 254), never echoing the value; `401/403/404/503` as the other management routes. Not part of any public route or OpenAPI example. |
|
||||
| `PUT /contact-settings` `{ enabled }` | AdminOnly | unchanged. |
|
||||
|
||||
Without any address (`recipientSource: "none"`) the host still starts and the form can still be switched on (warn, not block): messages are stored, the mail stays `pending` with `mailError: "recipient_not_configured"` (not counted as an attempt) and goes out by itself within seconds once an address is set (setting the address wakes the mail sender). The admin shows a warning banner on the switch card. Release condition for SLP/ASF: the address no longer has to be in the environment when it is set in the admin.
|
||||
|
||||
@@ -51,6 +51,15 @@ export function FormSwitchCard() {
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t('contact.switch.explanation')}</p>
|
||||
{settings.recipientSource === 'none' && (
|
||||
<p
|
||||
role="status"
|
||||
className="rounded-md border border-amber-500/50 bg-amber-500/10 p-2 text-sm"
|
||||
data-testid="contact-no-recipient-banner"
|
||||
>
|
||||
{t('contact.switch.noRecipientBanner')}
|
||||
</p>
|
||||
)}
|
||||
{!open && settings.hostEnabled && (
|
||||
<p className="text-sm text-muted-foreground" data-testid="contact-switch-hint">
|
||||
{t('contact.switch.firstTimeHint')}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ProblemDetailsError } from '@/lib/api-client';
|
||||
import { useContactSettings, useUpdateContactRecipient } from '../services/useContactSettings';
|
||||
import { contactErrorMessage } from '../errors';
|
||||
|
||||
// Same shape the server accepts: something@domain.tld, no spaces. The server decides; this only saves a round trip.
|
||||
const LOOKS_LIKE_AN_ADDRESS = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||
|
||||
function RecipientForm({ saved }: { saved: string }) {
|
||||
const { t } = useTranslation();
|
||||
const { data: settings } = useContactSettings();
|
||||
const update = useUpdateContactRecipient();
|
||||
const [draft, setDraft] = useState(saved);
|
||||
const [touched, setTouched] = useState(false);
|
||||
|
||||
const trimmed = draft.trim();
|
||||
const clientInvalid = trimmed.length > 0 && !LOOKS_LIKE_AN_ADDRESS.test(trimmed);
|
||||
const canSave = trimmed.length > 0 && !clientInvalid && trimmed !== saved && !update.isPending;
|
||||
const source = settings?.recipientSource ?? 'none';
|
||||
|
||||
const save = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
setTouched(true);
|
||||
if (!canSave) return;
|
||||
update.mutate(trimmed, { onSuccess: () => toast.success(t('contact.recipient.saved')) });
|
||||
};
|
||||
|
||||
const reset = () =>
|
||||
update.mutate(null, {
|
||||
onSuccess: () => {
|
||||
setDraft('');
|
||||
toast.success(t('contact.recipient.cleared'));
|
||||
},
|
||||
});
|
||||
|
||||
const serverMessage = update.isError
|
||||
? update.error instanceof ProblemDetailsError && update.error.status === 400
|
||||
? t('contact.recipient.invalid')
|
||||
: contactErrorMessage(update.error, t)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<form onSubmit={save} noValidate className="space-y-3" data-testid="contact-recipient-form">
|
||||
<div className="space-y-1">
|
||||
<label htmlFor="contact-recipient-input" className="text-sm font-medium">
|
||||
{t('contact.recipient.label')}
|
||||
</label>
|
||||
<Input
|
||||
id="contact-recipient-input"
|
||||
type="email"
|
||||
inputMode="email"
|
||||
autoComplete="off"
|
||||
value={draft}
|
||||
placeholder={t('contact.recipient.placeholder')}
|
||||
aria-invalid={touched && clientInvalid}
|
||||
aria-describedby="contact-recipient-source"
|
||||
onChange={(e) => {
|
||||
setDraft(e.target.value);
|
||||
setTouched(false);
|
||||
update.reset();
|
||||
}}
|
||||
data-testid="contact-recipient-input"
|
||||
/>
|
||||
{touched && clientInvalid && (
|
||||
<p
|
||||
role="alert"
|
||||
className="text-sm text-destructive"
|
||||
data-testid="contact-recipient-invalid"
|
||||
>
|
||||
{t('contact.recipient.invalid')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p
|
||||
id="contact-recipient-source"
|
||||
className="text-sm text-muted-foreground"
|
||||
data-testid="contact-recipient-source"
|
||||
>
|
||||
{t(`contact.recipient.source.${source}`)}
|
||||
</p>
|
||||
|
||||
{serverMessage && (
|
||||
<p
|
||||
role="alert"
|
||||
className="text-sm text-destructive"
|
||||
data-testid="contact-recipient-error"
|
||||
>
|
||||
{serverMessage}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="submit"
|
||||
className="min-h-11"
|
||||
disabled={update.isPending || trimmed.length === 0 || trimmed === saved}
|
||||
data-testid="contact-recipient-save"
|
||||
>
|
||||
{t('contact.recipient.save')}
|
||||
</Button>
|
||||
{saved && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11"
|
||||
disabled={update.isPending}
|
||||
onClick={reset}
|
||||
data-testid="contact-recipient-reset"
|
||||
>
|
||||
{t('contact.recipient.reset')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** The address contact messages are mailed to: the site setting, with the server configuration as the default. */
|
||||
export function RecipientCard() {
|
||||
const { t } = useTranslation();
|
||||
const { data: settings } = useContactSettings();
|
||||
|
||||
if (!settings) return null;
|
||||
|
||||
return (
|
||||
<Card data-testid="contact-recipient-card">
|
||||
<CardContent className="space-y-3 p-4">
|
||||
<div>
|
||||
<h2 className="font-semibold">{t('contact.recipient.title')}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('contact.recipient.description')}
|
||||
</p>
|
||||
</div>
|
||||
{/* Keyed by the saved value, so the field follows what the server answered. */}
|
||||
<RecipientForm
|
||||
key={settings.recipientEmail ?? ''}
|
||||
saved={settings.recipientEmail ?? ''}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -62,11 +62,21 @@ function seed(): ContactMessageDetail[] {
|
||||
}
|
||||
|
||||
let messages = seed();
|
||||
let settings: ContactSettings = { enabled: false, hostEnabled: true };
|
||||
let settings: ContactSettings = {
|
||||
enabled: false,
|
||||
hostEnabled: true,
|
||||
recipientEmail: null,
|
||||
recipientSource: 'config',
|
||||
};
|
||||
|
||||
export function resetMockContact(): void {
|
||||
messages = seed();
|
||||
settings = { enabled: false, hostEnabled: true };
|
||||
settings = {
|
||||
enabled: false,
|
||||
hostEnabled: true,
|
||||
recipientEmail: null,
|
||||
recipientSource: 'config',
|
||||
};
|
||||
}
|
||||
|
||||
export function getMockContactMessages(): ContactMessageDetail[] {
|
||||
@@ -87,6 +97,26 @@ function toItem(m: ContactMessageDetail): ContactMessageListItem {
|
||||
|
||||
export const contactHandlers = [
|
||||
http.get(SETTINGS, () => HttpResponse.json(settings)),
|
||||
http.put(`${SETTINGS}/recipient`, async ({ request }) => {
|
||||
const body = (await request.json()) as { recipientEmail: string | null };
|
||||
const address = body.recipientEmail?.trim() || null;
|
||||
if (address && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(address)) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
status: 400,
|
||||
title: 'Validation failed',
|
||||
errors: { recipientEmail: ['invalid'] },
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
settings = {
|
||||
...settings,
|
||||
recipientEmail: address,
|
||||
recipientSource: address ? 'setting' : 'config',
|
||||
};
|
||||
return HttpResponse.json(settings);
|
||||
}),
|
||||
http.put(SETTINGS, async ({ request }) => {
|
||||
const body = (await request.json()) as { enabled: boolean };
|
||||
settings = { ...settings, enabled: body.enabled };
|
||||
|
||||
@@ -165,6 +165,112 @@ describe('Form switch', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Recipient address', () => {
|
||||
it('shows the field, says that the server setting applies, and never an address it was not given', async () => {
|
||||
await openPage();
|
||||
|
||||
expect(await screen.findByTestId('contact-recipient-card')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('contact-recipient-input')).toHaveValue('');
|
||||
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||
'server setting applies',
|
||||
);
|
||||
expect(screen.queryByTestId('contact-recipient-reset')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('contact-no-recipient-banner')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves a valid address, shows where it comes from and offers to go back', async () => {
|
||||
await openPage();
|
||||
const input = await screen.findByTestId('contact-recipient-input');
|
||||
|
||||
await userEvent.type(input, ' inbox@example.org ');
|
||||
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||
'Messages go to this address',
|
||||
),
|
||||
);
|
||||
expect(screen.getByTestId('contact-recipient-input')).toHaveValue('inbox@example.org');
|
||||
expect(screen.getByTestId('contact-recipient-reset')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not save an invalid address (client side), and says so', async () => {
|
||||
await openPage();
|
||||
const input = await screen.findByTestId('contact-recipient-input');
|
||||
|
||||
await userEvent.type(input, 'not-an-address');
|
||||
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||
|
||||
expect(await screen.findByTestId('contact-recipient-invalid')).toHaveTextContent(
|
||||
'valid e-mail address',
|
||||
);
|
||||
});
|
||||
|
||||
it('shows a translated message when the server refuses the address', async () => {
|
||||
await openPage();
|
||||
server.use(
|
||||
http.put(`${API_BASE}/api/v1/contact-settings/recipient`, () =>
|
||||
HttpResponse.json(
|
||||
{
|
||||
status: 400,
|
||||
title: 'Validation failed',
|
||||
errors: { recipientEmail: ['invalid'] },
|
||||
},
|
||||
{ status: 400 },
|
||||
),
|
||||
),
|
||||
);
|
||||
await userEvent.type(
|
||||
await screen.findByTestId('contact-recipient-input'),
|
||||
'jan@example.org',
|
||||
);
|
||||
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||
|
||||
const error = await screen.findByTestId('contact-recipient-error');
|
||||
expect(error).toHaveTextContent('valid e-mail address');
|
||||
expect(error).not.toHaveTextContent('Validation failed');
|
||||
});
|
||||
|
||||
it('goes back to the server setting when cleared', async () => {
|
||||
await openPage();
|
||||
await userEvent.type(
|
||||
await screen.findByTestId('contact-recipient-input'),
|
||||
'inbox@example.org',
|
||||
);
|
||||
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||
await userEvent.click(await screen.findByTestId('contact-recipient-reset'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||
'server setting applies',
|
||||
),
|
||||
);
|
||||
expect(screen.getByTestId('contact-recipient-input')).toHaveValue('');
|
||||
});
|
||||
|
||||
it('warns (but does not block the switch) while there is no address at all', async () => {
|
||||
server.use(
|
||||
http.get(`${API_BASE}/api/v1/contact-settings`, () =>
|
||||
HttpResponse.json({
|
||||
enabled: false,
|
||||
hostEnabled: true,
|
||||
recipientEmail: null,
|
||||
recipientSource: 'none',
|
||||
}),
|
||||
),
|
||||
);
|
||||
await openPage();
|
||||
|
||||
expect(await screen.findByTestId('contact-no-recipient-banner')).toHaveTextContent(
|
||||
'No recipient address is set',
|
||||
);
|
||||
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||
'no recipient address yet',
|
||||
);
|
||||
expect(screen.getByTestId('contact-switch-toggle')).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Message list', () => {
|
||||
it('shows the inbox without spam and the unread counter', async () => {
|
||||
await openPage();
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Mail } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FormSwitchCard } from '../components/FormSwitchCard';
|
||||
import { RecipientCard } from '../components/RecipientCard';
|
||||
import { MessagesFilterChips } from '../components/MessagesFilterChips';
|
||||
import { MessagesTable } from '../components/MessagesTable';
|
||||
import { MessageDialog } from '../components/MessageDialog';
|
||||
@@ -38,6 +39,8 @@ export function MessagesPage() {
|
||||
|
||||
<FormSwitchCard />
|
||||
|
||||
<RecipientCard />
|
||||
|
||||
<MessagesFilterChips
|
||||
value={filter}
|
||||
unreadCount={data?.unreadCount}
|
||||
|
||||
@@ -42,6 +42,10 @@ export interface ContactSettings {
|
||||
/** The CMS switch: whether the form on the website is open. */
|
||||
enabled: boolean;
|
||||
hostEnabled: boolean;
|
||||
/** The address chosen in the CMS, or null. The address from the server configuration is never sent. */
|
||||
recipientEmail?: string | null;
|
||||
/** Where mail goes: the CMS setting, the server configuration (default) or nowhere. */
|
||||
recipientSource?: 'setting' | 'config' | 'none';
|
||||
}
|
||||
|
||||
export const PAGE_SIZE = 25;
|
||||
|
||||
@@ -25,6 +25,16 @@ export function useContactSettings(options?: { enabled?: boolean }) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Sets the address contact mails go to; null clears it (back to the server configuration). */
|
||||
export function useUpdateContactRecipient() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<ContactSettings, Error, string | null>({
|
||||
mutationFn: (recipientEmail) =>
|
||||
api.put<ContactSettings>('/api/v1/contact-settings/recipient', { recipientEmail }),
|
||||
onSuccess: (settings) => queryClient.setQueryData(CONTACT_SETTINGS_KEY, settings),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateContactSettings() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<ContactSettings, Error, boolean>({
|
||||
|
||||
@@ -431,7 +431,8 @@
|
||||
"nowOff": "The contact form is now off.",
|
||||
"explanation": "While the form is off, visitors only see your e-mail address. Turning it off helps against spam or during maintenance.",
|
||||
"firstTimeHint": "The form stays closed until you turn it on.",
|
||||
"hostOff": "The form is switched off at server level."
|
||||
"hostOff": "The form is switched off at server level.",
|
||||
"noRecipientBanner": "No recipient address is set: messages are kept but not mailed. Enter an address below."
|
||||
},
|
||||
"filter": {
|
||||
"label": "Filter messages",
|
||||
@@ -515,6 +516,22 @@
|
||||
"tls_failed": "The secure connection to the mail server failed.",
|
||||
"connection_failed": "Cannot reach the mail server.",
|
||||
"unknown": "Unknown error while sending."
|
||||
},
|
||||
"recipient": {
|
||||
"title": "Recipient address for contact messages",
|
||||
"description": "We mail every new message to this address. You can reply to that mail directly: the reply goes to the visitor.",
|
||||
"label": "E-mail address",
|
||||
"placeholder": "name@example.com",
|
||||
"save": "Save",
|
||||
"reset": "Back to the server setting",
|
||||
"saved": "Recipient address saved.",
|
||||
"cleared": "The server setting applies again.",
|
||||
"invalid": "Enter a valid e-mail address.",
|
||||
"source": {
|
||||
"setting": "Messages go to this address.",
|
||||
"config": "No address of your own is set: the server setting applies.",
|
||||
"none": "There is no recipient address yet: messages are kept but not mailed."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -431,7 +431,8 @@
|
||||
"nowOff": "Het contactformulier staat nu uit.",
|
||||
"explanation": "Als het formulier uit staat, ziet de bezoeker alleen je e-mailadres. Uitzetten helpt bij spam of onderhoud.",
|
||||
"firstTimeHint": "Het formulier is nog gesloten tot je het aanzet.",
|
||||
"hostOff": "Het formulier is op serverniveau uitgeschakeld."
|
||||
"hostOff": "Het formulier is op serverniveau uitgeschakeld.",
|
||||
"noRecipientBanner": "Er is geen ontvangstadres ingesteld: berichten worden bewaard maar niet gemaild. Vul hieronder een adres in."
|
||||
},
|
||||
"filter": {
|
||||
"label": "Filter berichten",
|
||||
@@ -515,6 +516,22 @@
|
||||
"tls_failed": "De beveiligde verbinding met de mailserver is mislukt.",
|
||||
"connection_failed": "Geen verbinding met de mailserver.",
|
||||
"unknown": "Onbekende fout bij het versturen."
|
||||
},
|
||||
"recipient": {
|
||||
"title": "Ontvangstadres contactberichten",
|
||||
"description": "Hierheen sturen we een mail bij elk nieuw bericht. Je kunt direct op die mail antwoorden: het antwoord gaat naar de bezoeker.",
|
||||
"label": "E-mailadres",
|
||||
"placeholder": "naam@voorbeeld.nl",
|
||||
"save": "Opslaan",
|
||||
"reset": "Terug naar serverinstelling",
|
||||
"saved": "Ontvangstadres opgeslagen.",
|
||||
"cleared": "De serverinstelling geldt weer.",
|
||||
"invalid": "Voer een geldig e-mailadres in.",
|
||||
"source": {
|
||||
"setting": "Berichten gaan naar dit adres.",
|
||||
"config": "Er is geen eigen adres ingesteld: de serverinstelling geldt.",
|
||||
"none": "Er is nog geen ontvangstadres: berichten worden bewaard maar niet gemaild."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,6 +344,16 @@
|
||||
},
|
||||
"hostEnabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"recipientEmail": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"recipientSource": {
|
||||
"default": "none",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -693,6 +703,20 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"UpdateContactRecipientRequest": {
|
||||
"properties": {
|
||||
"recipientEmail": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"recipientEmail"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"UpdateContactSettingsRequest": {
|
||||
"properties": {
|
||||
"enabled": {
|
||||
@@ -2088,6 +2112,63 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/contact-settings/recipient": {
|
||||
"put": {
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/*+json": {
|
||||
"schema": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/UpdateContactRecipientRequest"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/UpdateContactRecipientRequest"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ContactSettingsDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
},
|
||||
"400": {
|
||||
"content": {
|
||||
"application/problem+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ValidationProblemDetails"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Bad Request"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"ContactSettings"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/offerings": {
|
||||
"get": {
|
||||
"responses": {
|
||||
|
||||
@@ -248,6 +248,7 @@ public class ContactAdminControllerTests
|
||||
"POST contact-messages/{id:guid}/resend",
|
||||
"GET contact-settings",
|
||||
"PUT contact-settings",
|
||||
"PUT contact-settings/recipient",
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,14 @@ public class ContactMailSenderTests
|
||||
public CapturingLoggerProvider Logs { get; } = new();
|
||||
public OutgoingMail? Sent;
|
||||
|
||||
private readonly ContactDbContext _db = new(new DbContextOptionsBuilder<ContactDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
|
||||
|
||||
/// <summary>The real settings service on an in-memory database: the administrator's setting and the environment.</summary>
|
||||
public IContactSettingsService ContactSettings => new ContactSettingsService(
|
||||
new ContactRepository(_db), new ContactSettingsCache(TimeProvider.System), Options.Create(Contact),
|
||||
TimeProvider.System, Substitute.For<IContactMailSignal>());
|
||||
|
||||
public Rig()
|
||||
{
|
||||
Availability.IsEnabled.Returns(true);
|
||||
@@ -62,7 +70,7 @@ public class ContactMailSenderTests
|
||||
var settings = Substitute.For<ISiteSettingsService>();
|
||||
settings.GetEffectiveSenderAsync(Arg.Any<CancellationToken>()).Returns(("noreply@example.org", "De Site"));
|
||||
return new ContactMailSender(
|
||||
Email, new MailTemplateRenderer(), languages, settings, Availability,
|
||||
Email, new MailTemplateRenderer(), languages, settings, ContactSettings, Availability,
|
||||
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }),
|
||||
Options.Create(Contact), LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger<ContactMailSender>());
|
||||
}
|
||||
@@ -179,7 +187,7 @@ public class ContactMailSenderTests
|
||||
var result = await sut.SendAsync(Message(), CancellationToken.None);
|
||||
|
||||
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "disabled"));
|
||||
sut.NotReadyReason().Should().Be("disabled");
|
||||
(await sut.NotReadyReasonAsync(CancellationToken.None)).Should().Be("disabled");
|
||||
await rig.Email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -212,7 +220,7 @@ public class ContactMailServiceTests : IDisposable
|
||||
|
||||
public ContactMailServiceTests()
|
||||
{
|
||||
_sender.NotReadyReason().Returns((string?)null);
|
||||
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns((string?)null);
|
||||
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
|
||||
|
||||
var services = new ServiceCollection();
|
||||
@@ -330,7 +338,7 @@ public class ContactMailServiceTests : IDisposable
|
||||
[Fact]
|
||||
public async Task WhenMailCannotBeSent_NothingIsAttemptedOrCounted_AndTheReasonIsShown()
|
||||
{
|
||||
_sender.NotReadyReason().Returns("disabled");
|
||||
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns("disabled");
|
||||
var id = Add();
|
||||
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
|
||||
@@ -342,7 +350,7 @@ public class ContactMailServiceTests : IDisposable
|
||||
await _sender.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
|
||||
|
||||
// Once mail works again the same message goes out without any lost attempts.
|
||||
_sender.NotReadyReason().Returns((string?)null);
|
||||
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns((string?)null);
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(1);
|
||||
Get(id).MailAttempts.Should().Be(1);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Core.SiteSettings;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Controllers;
|
||||
using SlpModularCms.Modules.Contact.Data;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
using SlpModularCms.Modules.Contact.Models;
|
||||
using SlpModularCms.Modules.Contact.Repositories;
|
||||
using SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Tests;
|
||||
|
||||
/// <summary>The recipient of contact mails: the administrator's setting wins over the environment, which stays the default.</summary>
|
||||
public class ContactRecipientTests : IDisposable
|
||||
{
|
||||
private const string FromEnvironment = "env-inbox@example.org";
|
||||
private const string FromSetting = "setting-inbox@example.org";
|
||||
|
||||
private readonly ContactOptions _options = new() { Enabled = true, RecipientEmail = FromEnvironment };
|
||||
private readonly ContactDbContext _db = new(new DbContextOptionsBuilder<ContactDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
|
||||
private readonly IContactMailSignal _signal = Substitute.For<IContactMailSignal>();
|
||||
private readonly FakeTimeProvider _time = new(new DateTimeOffset(2026, 11, 10, 12, 0, 0, TimeSpan.Zero));
|
||||
|
||||
public void Dispose() => _db.Dispose();
|
||||
|
||||
private ContactSettingsService Settings() => new(
|
||||
new ContactRepository(_db), new ContactSettingsCache(_time), Options.Create(_options), _time, _signal);
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutASetting_TheEnvironmentIsTheDefault()
|
||||
{
|
||||
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFilledSetting_Wins_AndTheEnvironmentIsTheFallbackAgainAfterClearing()
|
||||
{
|
||||
var sut = Settings();
|
||||
|
||||
await sut.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
|
||||
(await sut.GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromSetting, "setting"));
|
||||
|
||||
await sut.SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None);
|
||||
(await sut.GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config"));
|
||||
|
||||
await sut.SetRecipientAsync(" ", Guid.NewGuid(), CancellationToken.None);
|
||||
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Source.Should().Be("config");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithNeitherOfThem_ThereIsNoRecipient()
|
||||
{
|
||||
_options.RecipientEmail = null;
|
||||
|
||||
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be(((string?)null, "none"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnInvalidStoredAddress_IsIgnored_NotUsed()
|
||||
{
|
||||
_db.ContactSettings.Add(new ContactSettings { Enabled = true, RecipientEmail = "not an address\r\nBcc: x@y.z", UpdatedAt = _time.GetUtcNow() });
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheAdminView_ShowsTheSettingAndTheSource_ButNeverTheEnvironmentAddress()
|
||||
{
|
||||
var sut = Settings();
|
||||
|
||||
var onlyEnvironment = await sut.GetAsync(CancellationToken.None);
|
||||
onlyEnvironment.RecipientEmail.Should().BeNull();
|
||||
onlyEnvironment.RecipientSource.Should().Be("config");
|
||||
|
||||
var withSetting = await sut.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
|
||||
withSetting.RecipientEmail.Should().Be(FromSetting);
|
||||
withSetting.RecipientSource.Should().Be("setting");
|
||||
System.Text.Json.JsonSerializer.Serialize(onlyEnvironment).Should().NotContain(FromEnvironment);
|
||||
|
||||
_options.RecipientEmail = null;
|
||||
(await Settings().SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None)).RecipientSource.Should().Be("none");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SettingTheAddress_KeepsTheSwitch_RemembersWho_AndWakesTheMailSender()
|
||||
{
|
||||
var sut = Settings();
|
||||
var user = Guid.NewGuid();
|
||||
await sut.SetEnabledAsync(true, user, CancellationToken.None);
|
||||
|
||||
var saved = await sut.SetRecipientAsync(FromSetting, user, CancellationToken.None);
|
||||
|
||||
saved.Enabled.Should().BeTrue("setting the address does not touch the switch");
|
||||
(await _db.ContactSettings.SingleAsync()).UpdatedByUserId.Should().Be(user);
|
||||
_signal.Received(1).Notify();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SettingTheAddressFirst_CreatesTheRowWithTheSwitchOff()
|
||||
{
|
||||
var saved = await Settings().SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
saved.Enabled.Should().BeFalse();
|
||||
saved.RecipientEmail.Should().Be(FromSetting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheMailSender_UsesTheSettingAtOnce_WithoutRestart_AndFallsBackToTheEnvironment()
|
||||
{
|
||||
var email = Substitute.For<IEmailSender>();
|
||||
OutgoingMail? sent = null;
|
||||
email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>()).Returns(call =>
|
||||
{
|
||||
sent = call.Arg<OutgoingMail>();
|
||||
return MailSendResult.Ok;
|
||||
});
|
||||
var availability = Substitute.For<IMailAvailability>();
|
||||
availability.IsEnabled.Returns(true);
|
||||
var languages = Substitute.For<ILanguageResolver>();
|
||||
languages.Resolve(Arg.Any<string?>()).Returns("nl");
|
||||
var siteSettings = Substitute.For<ISiteSettingsService>();
|
||||
siteSettings.GetEffectiveSenderAsync(Arg.Any<CancellationToken>()).Returns(("noreply@example.org", "De Site"));
|
||||
var settings = Settings();
|
||||
var sender = new ContactMailSender(
|
||||
email, new MailTemplateRenderer(), languages, siteSettings, settings, availability,
|
||||
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }),
|
||||
Options.Create(_options), LoggerFactory.Create(_ => { }).CreateLogger<ContactMailSender>());
|
||||
var message = new ContactMessage { Id = Guid.NewGuid(), SiteId = "s", Name = "Jan", Email = "jan@example.nl", Subject = "Website", Message = "Hallo" };
|
||||
|
||||
await sender.SendAsync(message, CancellationToken.None);
|
||||
sent!.ToAddress.Should().Be(FromEnvironment);
|
||||
|
||||
await settings.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
|
||||
await sender.SendAsync(message, CancellationToken.None);
|
||||
sent.ToAddress.Should().Be(FromSetting);
|
||||
|
||||
await settings.SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None);
|
||||
await sender.SendAsync(message, CancellationToken.None);
|
||||
sent.ToAddress.Should().Be(FromEnvironment);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutAnyAddress_TheSenderIsNotReady_WithAClearReason_AndNothingIsSent()
|
||||
{
|
||||
_options.RecipientEmail = null;
|
||||
var email = Substitute.For<IEmailSender>();
|
||||
var availability = Substitute.For<IMailAvailability>();
|
||||
availability.IsEnabled.Returns(true);
|
||||
var sender = new ContactMailSender(
|
||||
email, new MailTemplateRenderer(), Substitute.For<ILanguageResolver>(), Substitute.For<ISiteSettingsService>(), Settings(), availability,
|
||||
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions()), Options.Create(_options),
|
||||
LoggerFactory.Create(_ => { }).CreateLogger<ContactMailSender>());
|
||||
|
||||
(await sender.NotReadyReasonAsync(CancellationToken.None)).Should().Be("recipient_not_configured");
|
||||
var result = await sender.SendAsync(new ContactMessage { Id = Guid.NewGuid(), SiteId = "s", Name = "J", Email = "j@example.nl", Subject = "S", Message = "M" }, CancellationToken.None);
|
||||
|
||||
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "recipient_not_configured"));
|
||||
await email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactRecipientControllerTests
|
||||
{
|
||||
private readonly IContactSettingsService _settings = Substitute.For<IContactSettingsService>();
|
||||
private readonly ContactSettingsController _sut;
|
||||
|
||||
public ContactRecipientControllerTests()
|
||||
{
|
||||
_sut = new ContactSettingsController(_settings, Options.Create(new ContactOptions()))
|
||||
{
|
||||
ControllerContext = new ControllerContext { HttpContext = new Microsoft.AspNetCore.Http.DefaultHttpContext() },
|
||||
};
|
||||
_settings.SetRecipientAsync(Arg.Any<string?>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(call => new ContactSettingsDto(false, true, call.Arg<string?>(), call.Arg<string?>() is null ? "config" : "setting"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("jan@example.nl")]
|
||||
[InlineData(" jan@example.nl ")]
|
||||
public async Task AValidAddress_IsSavedTrimmed(string address)
|
||||
{
|
||||
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None);
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>();
|
||||
await _settings.Received(1).SetRecipientAsync("jan@example.nl", Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task NullOrBlank_ClearsTheSetting(string? address)
|
||||
{
|
||||
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None);
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>();
|
||||
await _settings.Received(1).SetRecipientAsync(null, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-an-address")]
|
||||
[InlineData("a@b")]
|
||||
[InlineData("jan@example.nl\r\nBcc: evil@example.com")]
|
||||
[InlineData("jan@example.nl, other@example.nl")]
|
||||
[InlineData("<script>@example.nl")]
|
||||
public async Task AnInvalidAddress_IsA400_NamingTheField_AndNothingIsSaved(string address)
|
||||
{
|
||||
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None);
|
||||
|
||||
var problem = result.Should().BeOfType<ObjectResult>().Subject;
|
||||
problem.StatusCode.Should().Be(400);
|
||||
problem.Value.Should().BeOfType<ValidationProblemDetails>().Which.Errors.Should().ContainKey("recipientEmail");
|
||||
await _settings.DidNotReceiveWithAnyArgs().SetRecipientAsync(default, default, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATooLongAddress_IsReportedAsTooLong()
|
||||
{
|
||||
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(new string('a', 250) + "@example.nl"), CancellationToken.None);
|
||||
|
||||
result.Should().BeOfType<ObjectResult>().Which.Value.Should().BeOfType<ValidationProblemDetails>()
|
||||
.Which.Errors["recipientEmail"].Should().Equal("tooLong");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AMissingBody_IsA400()
|
||||
{
|
||||
var result = await _sut.PutRecipient(null, CancellationToken.None);
|
||||
|
||||
result.Should().BeOfType<ObjectResult>().Which.StatusCode.Should().Be(400);
|
||||
}
|
||||
}
|
||||
@@ -20,13 +20,14 @@ public class ContactSettingsServiceTests
|
||||
public ContactDbContext Db { get; } = new(new DbContextOptionsBuilder<ContactDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
|
||||
public ContactSettingsCache Cache { get; }
|
||||
public IContactMailSignal Signal { get; } = Substitute.For<IContactMailSignal>();
|
||||
public ContactSettingsService Sut { get; }
|
||||
|
||||
public Setup()
|
||||
{
|
||||
Cache = new ContactSettingsCache(Time);
|
||||
Sut = new ContactSettingsService(
|
||||
new ContactRepository(Db), Cache, Microsoft.Extensions.Options.Options.Create(Options), Time);
|
||||
new ContactRepository(Db), Cache, Microsoft.Extensions.Options.Options.Create(Options), Time, Signal);
|
||||
}
|
||||
|
||||
public void Dispose() => Db.Dispose();
|
||||
|
||||
@@ -148,7 +148,7 @@ public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory
|
||||
var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true}""");
|
||||
(await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true,"recipientEmail":null,"recipientSource":"none"}""");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -182,7 +182,7 @@ public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory
|
||||
|
||||
var on = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":true}"""));
|
||||
on.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true}""");
|
||||
(await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true,"recipientEmail":null,"recipientSource":"none"}""");
|
||||
(await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
var off = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":false}"""));
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
|
||||
|
||||
/// <summary>Contact open, an address only in the environment, no mail sender needed (the management routes only).</summary>
|
||||
public sealed class RecipientEnvContactHostFactory() : ContactHostFactory(new()
|
||||
{
|
||||
["Contact:Enabled"] = "true",
|
||||
["Contact:SiteId"] = "pipeline-site",
|
||||
["Contact:MinSeconds"] = "0",
|
||||
["Contact:RecipientEmail"] = "env-pipeline@example.org",
|
||||
})
|
||||
{
|
||||
protected override bool OpenCmsSwitch => true;
|
||||
}
|
||||
|
||||
/// <summary>The real host with a capturing mail sender and NO address in the environment.</summary>
|
||||
public sealed class MailNoRecipientHostFactory() : ContactHostFactory(new()
|
||||
{
|
||||
["Contact:Enabled"] = "true",
|
||||
["Contact:SiteId"] = "pipeline-site",
|
||||
["Contact:MinSeconds"] = "0",
|
||||
["Contact:Mail:SweepSeconds"] = "5",
|
||||
["RateLimiting:ContactForm:PermitLimit"] = "1000",
|
||||
["RateLimiting:ContactToken:PermitLimit"] = "1000",
|
||||
})
|
||||
{
|
||||
public CapturingEmailSender Mailer { get; } = new();
|
||||
|
||||
protected override bool OpenCmsSwitch => true;
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
base.ConfigureWebHost(builder);
|
||||
var availability = Substitute.For<IMailAvailability>();
|
||||
availability.IsEnabled.Returns(true);
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.AddSingleton<IEmailSender>(Mailer);
|
||||
services.AddSingleton(availability);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactRecipientPipelineTests(RecipientEnvContactHostFactory factory) : IClassFixture<RecipientEnvContactHostFactory>
|
||||
{
|
||||
private const string Settings = "/api/v1/contact-settings";
|
||||
|
||||
[Fact]
|
||||
public async Task TheRecipientRoute_RequiresLogin_AndTheAdminRole()
|
||||
{
|
||||
(await factory.CreateClient().PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"x@example.org"}""")))
|
||||
.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
|
||||
var user = await Jwt.ClientWithRoleAsync(factory, "User");
|
||||
(await user.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"x@example.org"}""")))
|
||||
.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheAdminView_NeverShowsTheEnvironmentAddress_OnlyWhereItComesFrom()
|
||||
{
|
||||
var admin = await Jwt.ClientWithRoleAsync(factory, "Administrator");
|
||||
|
||||
var text = await admin.GetStringAsync(Settings);
|
||||
|
||||
text.Should().NotContain("env-pipeline@example.org");
|
||||
using var json = JsonDocument.Parse(text);
|
||||
json.RootElement.GetProperty("recipientSource").GetString().Should().Be("config");
|
||||
json.RootElement.GetProperty("recipientEmail").ValueKind.Should().Be(JsonValueKind.Null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetInvalidAndClear_WorkEndToEnd()
|
||||
{
|
||||
var admin = await Jwt.ClientWithRoleAsync(factory, "Owner");
|
||||
|
||||
var invalid = await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"not-an-address"}"""));
|
||||
invalid.StatusCode.Should().Be(HttpStatusCode.BadRequest);
|
||||
invalid.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
|
||||
(await invalid.Content.ReadAsStringAsync()).Should().Contain("recipientEmail").And.NotContain("not-an-address");
|
||||
|
||||
var set = await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":" inbox@example.org "}"""));
|
||||
set.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
using (var json = JsonDocument.Parse(await set.Content.ReadAsStringAsync()))
|
||||
{
|
||||
json.RootElement.GetProperty("recipientEmail").GetString().Should().Be("inbox@example.org");
|
||||
json.RootElement.GetProperty("recipientSource").GetString().Should().Be("setting");
|
||||
}
|
||||
|
||||
var stored = await factory.WithDb(db => db.ContactSettings.AsNoTracking().SingleAsync());
|
||||
stored.RecipientEmail.Should().Be("inbox@example.org");
|
||||
|
||||
var cleared = await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":null}"""));
|
||||
using var after = JsonDocument.Parse(await cleared.Content.ReadAsStringAsync());
|
||||
after.RootElement.GetProperty("recipientSource").GetString().Should().Be("config");
|
||||
after.RootElement.GetProperty("recipientEmail").ValueKind.Should().Be(JsonValueKind.Null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheAddress_IsNeverInThePublicTokenResponse()
|
||||
{
|
||||
var admin = await Jwt.ClientWithRoleAsync(factory, "Owner");
|
||||
await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"public-leak-check@example.org"}"""));
|
||||
|
||||
var text = await factory.CreateClient().GetStringAsync($"{Http.Route}/token");
|
||||
|
||||
text.Should().NotContain("public-leak-check").And.NotContain("env-pipeline");
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactRecipientMailPipelineTests(MailNoRecipientHostFactory factory) : IClassFixture<MailNoRecipientHostFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task WithoutAnyAddress_TheMessageIsStoredAndStaysPending_ThenGoesOutOnceAnAddressIsSet()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
var token = await Http.GetTokenAsync(client);
|
||||
(await Http.PostAsync(client, Http.Body(token, name: "Recipient Later"))).StatusCode.Should().Be(HttpStatusCode.Accepted);
|
||||
|
||||
// No address anywhere: not attempted, not counted, the reason is on the message.
|
||||
ContactMessage row = null!;
|
||||
var deadline = DateTime.UtcNow.AddSeconds(30);
|
||||
do
|
||||
{
|
||||
row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Recipient Later"));
|
||||
if (row.MailError == "recipient_not_configured") break;
|
||||
await Task.Delay(200);
|
||||
}
|
||||
while (DateTime.UtcNow < deadline);
|
||||
row.MailError.Should().Be("recipient_not_configured");
|
||||
row.MailStatus.Should().Be(ContactMailStatus.Pending);
|
||||
row.MailAttempts.Should().Be(0);
|
||||
factory.Mailer.Sent.Should().BeEmpty();
|
||||
|
||||
// The administrator fills in the address: the waiting message is sent to it without a restart.
|
||||
var admin = await Jwt.ClientWithRoleAsync(factory, "Owner");
|
||||
(await admin.PutAsync("/api/v1/contact-settings/recipient", Jwt.Json("""{"recipientEmail":"later@example.org"}""")))
|
||||
.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
deadline = DateTime.UtcNow.AddSeconds(30);
|
||||
do
|
||||
{
|
||||
row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Recipient Later"));
|
||||
if (row.MailStatus == ContactMailStatus.Sent) break;
|
||||
await Task.Delay(200);
|
||||
}
|
||||
while (DateTime.UtcNow < deadline);
|
||||
|
||||
row.MailStatus.Should().Be(ContactMailStatus.Sent);
|
||||
row.MailError.Should().BeNull();
|
||||
factory.Mailer.Sent.Single().ToAddress.Should().Be("later@example.org");
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,35 @@ public class ContactSettingsController(IContactSettingsService service, IOptions
|
||||
return Ok(await service.SetEnabledAsync(enabled, CallerId(), cancellationToken));
|
||||
}
|
||||
|
||||
[HttpPut("recipient")]
|
||||
[Consumes("application/json")]
|
||||
[ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")]
|
||||
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
|
||||
public async Task<IActionResult> PutRecipient([FromBody] UpdateContactRecipientRequest? request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ModelState.IsValid || request is null)
|
||||
{
|
||||
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "recipientEmail");
|
||||
}
|
||||
|
||||
// null or blank clears the setting (back to the server configuration); anything else must be a plain address.
|
||||
var address = string.IsNullOrWhiteSpace(request.RecipientEmail) ? null : request.RecipientEmail.Trim();
|
||||
if (!string.IsNullOrEmpty(address))
|
||||
{
|
||||
if (address.Length > 254)
|
||||
{
|
||||
return ContactProblems.Validation(new Dictionary<string, string[]> { ["recipientEmail"] = ["tooLong"] }, options.Value.ProblemTypeBase);
|
||||
}
|
||||
|
||||
if (!SlpModularCms.Core.Email.EmailAddressRules.IsValidAddress(address))
|
||||
{
|
||||
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "recipientEmail");
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(await service.SetRecipientAsync(address, CallerId(), cancellationToken));
|
||||
}
|
||||
|
||||
private Guid CallerId()
|
||||
{
|
||||
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
|
||||
|
||||
@@ -42,6 +42,7 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Id).ValueGeneratedNever();
|
||||
entity.Property(e => e.Enabled).IsRequired();
|
||||
entity.Property(e => e.RecipientEmail).HasMaxLength(254);
|
||||
entity.Property(e => e.UpdatedAt).IsRequired();
|
||||
entity.Property(e => e.UpdatedByUserId).IsRequired();
|
||||
});
|
||||
|
||||
@@ -68,6 +68,10 @@ public class ContactSettings
|
||||
|
||||
public int Id { get; set; } = SingletonId;
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>The address contact mails are sent to, chosen by an administrator. Null = use Contact:RecipientEmail from the environment.</summary>
|
||||
public string? RecipientEmail { get; set; }
|
||||
|
||||
public DateTimeOffset UpdatedAt { get; set; }
|
||||
public Guid UpdatedByUserId { get; set; }
|
||||
}
|
||||
|
||||
Generated
+139
@@ -0,0 +1,139 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SlpModularCms.Modules.Contact.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Migrations
|
||||
{
|
||||
[DbContext(typeof(ContactDbContext))]
|
||||
[Migration("20261110224342_ContactSettingsRecipient")]
|
||||
partial class ContactSettingsRecipient
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 64);
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasMaxLength(254)
|
||||
.HasColumnType("varchar(254)");
|
||||
|
||||
b.Property<int>("MailAttempts")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("MailError")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<string>("MailStatus")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("varchar(2000)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<DateTimeOffset?>("NextMailAttemptAt")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<DateTimeOffset>("ReceivedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<DateTimeOffset>("RetentionUntil")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("SiteId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RetentionUntil");
|
||||
|
||||
b.HasIndex("SiteId", "Status", "ReceivedAt");
|
||||
|
||||
b.ToTable("ContactMessages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("RecipientEmail")
|
||||
.HasMaxLength(254)
|
||||
.HasColumnType("varchar(254)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<Guid>("UpdatedByUserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("ContactSettings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
|
||||
{
|
||||
b.Property<string>("SiteId")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<Guid>("Key")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<int>("StatusCode")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("SiteId", "Key");
|
||||
|
||||
b.HasIndex("CreatedAt");
|
||||
|
||||
b.ToTable("ContactIdempotency", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ContactSettingsRecipient : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "RecipientEmail",
|
||||
table: "ContactSettings",
|
||||
type: "varchar(254)",
|
||||
maxLength: 254,
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "RecipientEmail",
|
||||
table: "ContactSettings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,10 @@ namespace SlpModularCms.Modules.Contact.Migrations
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("RecipientEmail")
|
||||
.HasMaxLength(254)
|
||||
.HasColumnType("varchar(254)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
|
||||
@@ -47,7 +47,22 @@ public record UpdateContactMessageStatusRequest(string? Status);
|
||||
public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed, string? MailError = null);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactSettingsDto(bool Enabled, bool HostEnabled);
|
||||
public record ContactSettingsDto(
|
||||
bool Enabled,
|
||||
bool HostEnabled,
|
||||
string? RecipientEmail = null,
|
||||
string RecipientSource = ContactRecipientSource.None);
|
||||
|
||||
/// <summary>Where the address contact mails go to comes from. The address from the environment is never returned.</summary>
|
||||
public static class ContactRecipientSource
|
||||
{
|
||||
public const string Setting = "setting";
|
||||
public const string Config = "config";
|
||||
public const string None = "none";
|
||||
}
|
||||
|
||||
/// <summary>Body of PUT /contact-settings/recipient. null or empty clears the setting (back to the server configuration).</summary>
|
||||
public record UpdateContactRecipientRequest(string? RecipientEmail);
|
||||
|
||||
/// <summary>Body of PUT /contact-settings. Nullable so a missing or non-boolean value is reported as errors.enabled.</summary>
|
||||
public record UpdateContactSettingsRequest(bool? Enabled);
|
||||
|
||||
@@ -18,25 +18,27 @@ public sealed class ContactMailSender(
|
||||
IMailTemplateRenderer renderer,
|
||||
ILanguageResolver languages,
|
||||
ISiteSettingsService siteSettings,
|
||||
IContactSettingsService contactSettings,
|
||||
IMailAvailability availability,
|
||||
IOptions<EmailOptions> email,
|
||||
IOptions<AppMailOptions> app,
|
||||
IOptions<ContactOptions> contact,
|
||||
ILogger<ContactMailSender> logger) : IContactMailSender
|
||||
{
|
||||
public string? NotReadyReason()
|
||||
public async Task<string?> NotReadyReasonAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!availability.IsEnabled)
|
||||
{
|
||||
return ContactMailResult.Disabled;
|
||||
}
|
||||
|
||||
return EmailAddressRules.IsValidAddress(contact.Value.RecipientEmail) ? null : ContactMailResult.RecipientNotConfigured;
|
||||
var (address, _) = await contactSettings.GetEffectiveRecipientAsync(cancellationToken);
|
||||
return address is null ? ContactMailResult.RecipientNotConfigured : null;
|
||||
}
|
||||
|
||||
public async Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken)
|
||||
{
|
||||
var notReady = NotReadyReason();
|
||||
var notReady = await NotReadyReasonAsync(cancellationToken);
|
||||
if (notReady is not null)
|
||||
{
|
||||
return new ContactMailResult(ContactMailOutcome.Skipped, notReady);
|
||||
@@ -44,6 +46,8 @@ public sealed class ContactMailSender(
|
||||
|
||||
try
|
||||
{
|
||||
// Read per send: the administrator's setting wins over the environment and changes without a restart.
|
||||
var (recipient, _) = await contactSettings.GetEffectiveRecipientAsync(cancellationToken);
|
||||
var (fromAddress, fromName) = await siteSettings.GetEffectiveSenderAsync(cancellationToken);
|
||||
var baseUrl = app.Value.PublicBaseUrl.TrimEnd('/');
|
||||
var language = languages.Resolve(null);
|
||||
@@ -65,7 +69,7 @@ public sealed class ContactMailSender(
|
||||
var rendered = renderer.Render(MailKind.ContactMessage, language, model);
|
||||
var result = await sender.SendAsync(
|
||||
new OutgoingMail(
|
||||
contact.Value.RecipientEmail!.Trim(), rendered.Subject, rendered.Html, rendered.Text,
|
||||
recipient!, rendered.Subject, rendered.Html, rendered.Text,
|
||||
fromAddress, fromName,
|
||||
ReplyToAddress: message.Email,
|
||||
ReplyToName: EmailAddressRules.IsValidDisplayName(message.Name) ? message.Name : null),
|
||||
|
||||
@@ -66,7 +66,7 @@ public class ContactMailService(
|
||||
}
|
||||
|
||||
// Mail cannot be sent at all: say why on the messages, count nothing, retry nothing in a loop.
|
||||
var notReady = sender.NotReadyReason();
|
||||
var notReady = await sender.NotReadyReasonAsync(cancellationToken);
|
||||
if (!string.IsNullOrEmpty(notReady))
|
||||
{
|
||||
foreach (var message in due.Where(m => m.MailError != notReady))
|
||||
|
||||
@@ -47,7 +47,7 @@ public readonly record struct ContactMailResult(ContactMailOutcome Outcome, stri
|
||||
public interface IContactMailSender
|
||||
{
|
||||
/// <summary>Null (or empty) when mail can be sent now, otherwise the short reason code.</summary>
|
||||
string? NotReadyReason();
|
||||
Task<string?> NotReadyReasonAsync(CancellationToken cancellationToken);
|
||||
|
||||
Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
using SlpModularCms.Modules.Contact.Models;
|
||||
@@ -53,13 +54,23 @@ public interface IContactSettingsService
|
||||
|
||||
Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken);
|
||||
Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The address contact mails go to: the administrator's setting if filled in and valid, otherwise
|
||||
/// Contact:RecipientEmail from the configuration, otherwise none. Read from the database on every call.
|
||||
/// </summary>
|
||||
Task<(string? Address, string Source)> GetEffectiveRecipientAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>null or empty clears the setting. The caller has validated the address.</summary>
|
||||
Task<ContactSettingsDto> SetRecipientAsync(string? recipientEmail, Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class ContactSettingsService(
|
||||
IContactRepository repository,
|
||||
ContactSettingsCache cache,
|
||||
IOptions<ContactOptions> options,
|
||||
TimeProvider time) : IContactSettingsService
|
||||
TimeProvider time,
|
||||
IContactMailSignal mailSignal) : IContactSettingsService
|
||||
{
|
||||
public async Task<bool> IsEnabledAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -76,8 +87,56 @@ public sealed class ContactSettingsService(
|
||||
public async Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// The administrator's own view is never served from the cache.
|
||||
var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false;
|
||||
return new ContactSettingsDto(enabled, options.Value.Enabled);
|
||||
var settings = await repository.GetSettingsAsync(cancellationToken);
|
||||
return ToDto(settings);
|
||||
}
|
||||
|
||||
public async Task<(string? Address, string Source)> GetEffectiveRecipientAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = await repository.GetSettingsAsync(cancellationToken);
|
||||
return Resolve(settings);
|
||||
}
|
||||
|
||||
private (string? Address, string Source) Resolve(ContactSettings? settings)
|
||||
{
|
||||
var fromSetting = settings?.RecipientEmail?.Trim();
|
||||
if (EmailAddressRules.IsValidAddress(fromSetting))
|
||||
{
|
||||
return (fromSetting, ContactRecipientSource.Setting);
|
||||
}
|
||||
|
||||
var fromConfig = options.Value.RecipientEmail?.Trim();
|
||||
return EmailAddressRules.IsValidAddress(fromConfig)
|
||||
? (fromConfig, ContactRecipientSource.Config)
|
||||
: (null, ContactRecipientSource.None);
|
||||
}
|
||||
|
||||
// The administrator sees their own setting, and only where the address comes from (never the environment's address).
|
||||
private ContactSettingsDto ToDto(ContactSettings? settings)
|
||||
{
|
||||
var (_, source) = Resolve(settings);
|
||||
return new ContactSettingsDto(
|
||||
settings?.Enabled ?? false, options.Value.Enabled,
|
||||
string.IsNullOrWhiteSpace(settings?.RecipientEmail) ? null : settings.RecipientEmail, source);
|
||||
}
|
||||
|
||||
public async Task<ContactSettingsDto> SetRecipientAsync(string? recipientEmail, Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = await repository.GetSettingsAsync(cancellationToken);
|
||||
if (settings is null)
|
||||
{
|
||||
settings = new ContactSettings();
|
||||
repository.Add(settings);
|
||||
}
|
||||
|
||||
settings.RecipientEmail = string.IsNullOrWhiteSpace(recipientEmail) ? null : recipientEmail.Trim();
|
||||
settings.UpdatedAt = time.GetUtcNow();
|
||||
settings.UpdatedByUserId = userId;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// Messages that waited for an address go out at once.
|
||||
mailSignal.Notify();
|
||||
return ToDto(settings);
|
||||
}
|
||||
|
||||
public async Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken)
|
||||
@@ -95,7 +154,7 @@ public sealed class ContactSettingsService(
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
cache.Invalidate();
|
||||
return new ContactSettingsDto(enabled, options.Value.Enabled);
|
||||
return ToDto(settings);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user