diff --git a/.dockerignore b/.dockerignore index c4d2928..042cbfd 100644 --- a/.dockerignore +++ b/.dockerignore @@ -8,6 +8,7 @@ **/*.user **/*.pfx **/*.pem +**/.graph-token-cache .aspnet .vs .idea diff --git a/.gitignore b/.gitignore index 0aa08e7..ebf91e8 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,7 @@ node_modules/ .env .env.* !.env.example +server/.graph-token-cache/ # Build results [Dd]ebug/ diff --git a/README.md b/README.md index 54c4f91..f256738 100644 --- a/README.md +++ b/README.md @@ -194,8 +194,24 @@ Restart the backend and sign in again. In the `Development` environment, a match For local sandbox users, the IAM IDs are `sandbox-10001` (Sample User) and `sandbox-10002` (Basic User). This setting updates the database admin flag; the template's fixed `User` and `SampleRole` claims stay unchanged. The Docker sandbox excludes host `.env` files, so pass `DevelopmentData__AdminIamIds` to the app container's environment when using Docker. +For local development and hosted calendar connections in Site administration, +see [Graph authentication, token persistence, and calendar access](docs/GRAPH-DEVELOPMENT.md). +An approved Web redirect URI and IT-authorized account are required before its first sign-in. +Test meetings with email invitations are available to site administrators when the +backend environment is named `Development` or `test`; they are hidden and blocked +in `prod`. The UI follows the backend environment regardless of the frontend build +mode, with no additional feature flag. + ### Key Vault secrets +Graph reuses the existing `Azure__TenantId`, `Azure__ClientId`, and +`Azure__ClientSecret` settings. Its hosted MSAL cache is saved in the fixed Key Vault +secret `graph-calendar-token-cache`, created by the app after verified sign-in. +There are no separate Graph credential overrides or credential-secret references. +Configure `Graph__RedirectUri` for the separate calendar callback. Local development +uses file caching; see +[Graph credential setup](docs/GRAPH-DEVELOPMENT.md#key-vault-credentials-and-future-federation). + `ISecretsService` provides asynchronous reads and writes by secret name. Configure `Azure__KeyVaultUrl` when the service is needed. Azure deployment creates a vault in each environment's resource group, grants the App Service's managed identity access diff --git a/client/src/features/admin/components/DevelopmentCalendar.tsx b/client/src/features/admin/components/DevelopmentCalendar.tsx new file mode 100644 index 0000000..12eb66c --- /dev/null +++ b/client/src/features/admin/components/DevelopmentCalendar.tsx @@ -0,0 +1,297 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useAppForm } from '@/shared/forms/formContext.tsx'; +import { z } from 'zod'; +import { HttpError } from '@/lib/api.ts'; +import { + checkDevelopmentGraph, + connectDevelopmentGraph, + developmentGraphStatusOptions, + createDevelopmentTestMeeting, +} from '@/queries/developmentGraph.ts'; + +export function DevelopmentCalendar() { + const queryClient = useQueryClient(); + const status = useQuery(developmentGraphStatusOptions()); + const connect = useMutation({ + mutationFn: connectDevelopmentGraph, + onSuccess: ({ authorizationUrl }) => + window.location.assign(authorizationUrl), + }); + const check = useMutation({ + mutationFn: checkDevelopmentGraph, + onSuccess: () => + queryClient.invalidateQueries({ + queryKey: developmentGraphStatusOptions().queryKey, + }), + }); + const meeting = useMutation({ + mutationFn: createDevelopmentTestMeeting, + retry: false, + }); + const form = useAppForm({ + defaultValues: { recipientEmail: '' }, + onSubmit: async ({ value }) => { + if ( + !status.data?.connected || + connect.isPending || + check.isPending || + meeting.isPending + ) { + return; + } + try { + await meeting.mutateAsync(value.recipientEmail.trim()); + form.reset(); + } catch { + // Keep the entered address and show the safe API error below. + } + }, + }); + const outcome = new URLSearchParams(window.location.search).get( + 'graphConnection' + ); + const error = connect.error ?? check.error ?? status.error; + const busy = connect.isPending || check.isPending || meeting.isPending; + + const showTestMeeting = status.data?.testMeetingEnabled === true; + + return ( +
+

+ {showTestMeeting ? 'Development calendar' : 'Calendar connection'} +

+

+ Connect the Microsoft account whose default calendar you want to use. + This account is separate from your Booking login. +

+
+ {status.isPending &&

Loading calendar connection…

} + {status.data && ( + <> +

+ {status.data.connected + ? 'Microsoft authentication cached' + : 'Not connected'} +

+ {status.data.connected && status.data.calendarEmail && ( +

Connected calendar: {status.data.calendarEmail}

+ )} + {status.data.username && ( +

Cached Microsoft account: {status.data.username}

+ )} +

{status.data.message}

+ + )} + {outcome === 'connected' && ( +

+ Calendar authentication completed. Run the read-only check to verify + access. +

+ )} + {outcome === 'failed' && ( +

+ {status.data?.lastError ?? + 'Calendar authentication failed or expired. Start the connection again.'} +

+ )} + {error &&

{calendarErrorMessage(error)}

} + {check.data && ( +
+ {check.data.username && ( +

Microsoft account used for check: {check.data.username}

+ )} +

{check.data.message}

+
+ )} +
+
+ + +
+ {showTestMeeting && ( + <> +
{ + event.preventDefault(); + if (!busy) { + void form.handleSubmit(); + } + }} + > +

+ Create a 30-minute test meeting. Microsoft must verify the + connected calendar before creating it. The recipient will be added + as a required attendee. +

+ + {(field) => ( +
+ + field.handleChange(event.target.value)} + required + type="email" + value={field.state.value} + /> + {!field.state.meta.isValid && ( + + )} +
+ )} +
+ [state.canSubmit, state.isSubmitting]} + > + {([canSubmit, isSubmitting]) => ( + + )} + +
+ {meeting.isPending && ( +

+

+ )} + {meeting.error && ( +

+ {calendarErrorMessage(meeting.error)} +

+ )} +
+
+ {meeting.data && ( +
+

+ Microsoft Graph successfully created the event. +

+
+
Calendar used
+
{meeting.data.calendarEmail}
+
Calendar ID
+
{meeting.data.calendarId}
+
Subject
+
{meeting.data.subject}
+
Start (Pacific Time)
+
{formatPacific(meeting.data.start)}
+
End (Pacific Time)
+
{formatPacific(meeting.data.end)}
+
Invited email address
+
{meeting.data.recipientEmail}
+
Graph event ID
+
{meeting.data.eventId}
+
+

{meeting.data.message}

+
+ )} + + )} +
+ ); +} + +function formatPacific(value: string) { + return new Intl.DateTimeFormat('en-US', { + dateStyle: 'full', + timeStyle: 'long', + timeZone: 'America/Los_Angeles', + }).format(new Date(value)); +} + +function calendarErrorMessage(error: unknown): string { + if (error instanceof HttpError) { + // ASP.NET routing/antiforgery failures can have an empty response body. + if (typeof error.body === 'string' && error.body.trim()) { + return error.body; + } + switch (error.status) { + case 404: + case 405: + return 'The running backend does not have the requested calendar endpoint available. Restart the backend, refresh this page, and try again. No meeting was created by this request.'; + case 400: + return 'The request was rejected. Refresh this page to renew your session verification token, confirm the recipient email address, and try again.'; + case 401: + case 403: + return 'Calendar access was denied. Sign into Booking as a site administrator and stop emulating before trying again.'; + default: + return `The calendar request failed (HTTP ${error.status}). Check the development calendar before retrying if event creation is uncertain.`; + } + } + return 'The calendar request could not be completed. Check your connection and the development calendar before retrying to avoid a duplicate meeting.'; +} diff --git a/client/src/queries/developmentGraph.ts b/client/src/queries/developmentGraph.ts new file mode 100644 index 0000000..7de00bb --- /dev/null +++ b/client/src/queries/developmentGraph.ts @@ -0,0 +1,55 @@ +import { queryOptions } from '@tanstack/react-query'; +import { fetchJson } from '@/lib/api.ts'; + +export interface DevelopmentGraphStatus { + calendarEmail: string | null; + configured: boolean; + connected: boolean; + lastError: string | null; + message: string; + testMeetingEnabled: boolean; + username: string | null; +} + +export const developmentGraphStatusOptions = () => + queryOptions({ + gcTime: 0, + queryFn: ({ signal }) => + fetchJson( + '/api/development-graph/status', + { cache: 'no-store' }, + signal + ), + queryKey: ['development-graph', 'status'] as const, + retry: false, + }); + +export const connectDevelopmentGraph = () => + fetchJson<{ authorizationUrl: string }>('/api/development-graph/connect', { + method: 'POST', + }); + +export const checkDevelopmentGraph = () => + fetchJson<{ message: string; succeeded: boolean; username?: string }>( + '/api/development-graph/check', + { method: 'POST' } + ); + +export interface DevelopmentTestMeeting { + calendarEmail: string; + calendarId: string; + created: boolean; + end: string; + eventId: string; + message: string; + recipientEmail: string; + start: string; + subject: string; + timeZone: string; +} + +export const createDevelopmentTestMeeting = (recipientEmail: string) => + fetchJson('/api/development-graph/test-meeting', { + body: JSON.stringify({ recipientEmail }), + method: 'POST', + }); diff --git a/client/src/routes/(authenticated)/admin.index.tsx b/client/src/routes/(authenticated)/admin.index.tsx index f77c92c..d5334fe 100644 --- a/client/src/routes/(authenticated)/admin.index.tsx +++ b/client/src/routes/(authenticated)/admin.index.tsx @@ -6,6 +6,7 @@ import { TrophyIcon, } from '@heroicons/react/24/outline'; import { createFileRoute, Link } from '@tanstack/react-router'; +import { DevelopmentCalendar } from '@/features/admin/components/DevelopmentCalendar.tsx'; export const Route = createFileRoute('/(authenticated)/admin/')({ component: SiteAdminPage, @@ -77,7 +78,10 @@ function SiteAdminPage() { className="group flex flex-col rounded-sm border border-base-300 bg-base-200 p-6 shadow-sm transition hover:border-primary/40 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-primary sm:p-8" to="/admin/spaces" > -