refactor(auth): migrate to new Supabase JWT Signing keys (#303)
* refactor(auth): replace Supabase `User` type with new `JWTUserData` type across the codebase - Replaced usage of Supabase's `User` type with the newly defined `JWTUserData` type for better type mapping and alignment with JWT claims. - Refactored session-related components and hooks (`useUser`, `requireUser`) to use the updated user structure. - Updated Supabase client keys to use `publicKey` instead of `anonKey`. - Adjusted multi-factor authentication logic and components to use `aal` and additional properties. - Applied consistent naming for Supabase secret key functions. - Incremented version to 2.12.0. - Introduced a new `deprecated` property in the `EnvVariableModel` type to handle deprecated environment variables. - Updated the `EnvList` component to display a warning badge for deprecated variables, including reason and alternative suggestions. - Enhanced filtering logic to allow users to toggle the visibility of deprecated variables. - Added new deprecated variables for Supabase keys with appropriate reasons and alternatives. - Added support for filtering deprecated environment variables in the `FilterSwitcher` component. - Updated the `Summary` component to display a badge for the count of deprecated variables. - Introduced a button to filter and display only deprecated variables. - Adjusted filtering logic to include deprecated variables in the overall state management. add BILLING_MODE configuration to environment variables - Introduced a new environment variable `BILLING_MODE` to configure billing options for the application. - The variable supports two values: `subscription` and `one-time`. - Marked as deprecated with a reason indicating that this configuration is no longer required, as billing mode is now automatically determined. - Added validation logic for the new variable to ensure correct value parsing.
This commit is contained in:
committed by
GitHub
parent
da8a3a903d
commit
9104ce9a2c
@@ -16,6 +16,7 @@ import {
|
|||||||
EyeOff,
|
EyeOff,
|
||||||
EyeOffIcon,
|
EyeOffIcon,
|
||||||
InfoIcon,
|
InfoIcon,
|
||||||
|
TriangleAlertIcon,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { Subject, debounceTime } from 'rxjs';
|
import { Subject, debounceTime } from 'rxjs';
|
||||||
|
|
||||||
@@ -121,6 +122,7 @@ function EnvList({ appState }: { appState: AppEnvState }) {
|
|||||||
const showPrivateVars = searchParams.get('private') === 'true';
|
const showPrivateVars = searchParams.get('private') === 'true';
|
||||||
const showOverriddenVars = searchParams.get('overridden') === 'true';
|
const showOverriddenVars = searchParams.get('overridden') === 'true';
|
||||||
const showInvalidVars = searchParams.get('invalid') === 'true';
|
const showInvalidVars = searchParams.get('invalid') === 'true';
|
||||||
|
const showDeprecatedVars = searchParams.get('deprecated') === 'true';
|
||||||
|
|
||||||
const toggleShowValue = (key: string) => {
|
const toggleShowValue = (key: string) => {
|
||||||
setShowValues((prev) => ({
|
setShowValues((prev) => ({
|
||||||
@@ -421,6 +423,35 @@ function EnvList({ appState }: { appState: AppEnvState }) {
|
|||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
</Badge>
|
</Badge>
|
||||||
</If>
|
</If>
|
||||||
|
|
||||||
|
<If condition={model?.deprecated}>
|
||||||
|
{(deprecated) => (
|
||||||
|
<Badge variant="warning">
|
||||||
|
Deprecated
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger>
|
||||||
|
<TriangleAlertIcon className="ml-2 h-3 w-3" />
|
||||||
|
</TooltipTrigger>
|
||||||
|
|
||||||
|
<TooltipContent>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="font-medium">This variable is deprecated</div>
|
||||||
|
<div className="text-sm">
|
||||||
|
<strong>Reason:</strong> {deprecated.reason}
|
||||||
|
</div>
|
||||||
|
{deprecated.alternative && (
|
||||||
|
<div className="text-sm">
|
||||||
|
<strong>Use instead:</strong> {deprecated.alternative}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</If>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -506,7 +537,8 @@ function EnvList({ appState }: { appState: AppEnvState }) {
|
|||||||
!showPublicVars &&
|
!showPublicVars &&
|
||||||
!showPrivateVars &&
|
!showPrivateVars &&
|
||||||
!showInvalidVars &&
|
!showInvalidVars &&
|
||||||
!showOverriddenVars
|
!showOverriddenVars &&
|
||||||
|
!showDeprecatedVars
|
||||||
) {
|
) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -539,6 +571,10 @@ function EnvList({ appState }: { appState: AppEnvState }) {
|
|||||||
return !varState.validation.success;
|
return !varState.validation.success;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (showDeprecatedVars && isInSearch) {
|
||||||
|
return !!model?.deprecated;
|
||||||
|
}
|
||||||
|
|
||||||
return isInSearch;
|
return isInSearch;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -561,6 +597,7 @@ function EnvList({ appState }: { appState: AppEnvState }) {
|
|||||||
overridden: showOverriddenVars,
|
overridden: showOverriddenVars,
|
||||||
private: showPrivateVars,
|
private: showPrivateVars,
|
||||||
invalid: showInvalidVars,
|
invalid: showInvalidVars,
|
||||||
|
deprecated: showDeprecatedVars,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -640,6 +677,7 @@ function FilterSwitcher(props: {
|
|||||||
overridden: boolean;
|
overridden: boolean;
|
||||||
private: boolean;
|
private: boolean;
|
||||||
invalid: boolean;
|
invalid: boolean;
|
||||||
|
deprecated: boolean;
|
||||||
};
|
};
|
||||||
}) {
|
}) {
|
||||||
const secretVars = props.filters.secret;
|
const secretVars = props.filters.secret;
|
||||||
@@ -647,6 +685,7 @@ function FilterSwitcher(props: {
|
|||||||
const overriddenVars = props.filters.overridden;
|
const overriddenVars = props.filters.overridden;
|
||||||
const privateVars = props.filters.private;
|
const privateVars = props.filters.private;
|
||||||
const invalidVars = props.filters.invalid;
|
const invalidVars = props.filters.invalid;
|
||||||
|
const deprecatedVars = props.filters.deprecated;
|
||||||
|
|
||||||
const handleFilterChange = useUpdateFilteredVariables();
|
const handleFilterChange = useUpdateFilteredVariables();
|
||||||
|
|
||||||
@@ -658,6 +697,7 @@ function FilterSwitcher(props: {
|
|||||||
if (overriddenVars) filters.push('Overridden');
|
if (overriddenVars) filters.push('Overridden');
|
||||||
if (privateVars) filters.push('Private');
|
if (privateVars) filters.push('Private');
|
||||||
if (invalidVars) filters.push('Invalid');
|
if (invalidVars) filters.push('Invalid');
|
||||||
|
if (deprecatedVars) filters.push('Deprecated');
|
||||||
|
|
||||||
if (filters.length === 0) return 'Filter variables';
|
if (filters.length === 0) return 'Filter variables';
|
||||||
|
|
||||||
@@ -665,7 +705,7 @@ function FilterSwitcher(props: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const allSelected =
|
const allSelected =
|
||||||
!secretVars && !publicVars && !overriddenVars && !invalidVars;
|
!secretVars && !publicVars && !overriddenVars && !invalidVars && !deprecatedVars;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -731,6 +771,15 @@ function FilterSwitcher(props: {
|
|||||||
>
|
>
|
||||||
Overridden
|
Overridden
|
||||||
</DropdownMenuCheckboxItem>
|
</DropdownMenuCheckboxItem>
|
||||||
|
|
||||||
|
<DropdownMenuCheckboxItem
|
||||||
|
checked={deprecatedVars}
|
||||||
|
onCheckedChange={() => {
|
||||||
|
handleFilterChange('deprecated', !deprecatedVars);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Deprecated
|
||||||
|
</DropdownMenuCheckboxItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
);
|
);
|
||||||
@@ -746,6 +795,12 @@ function Summary({ appState }: { appState: AppEnvState }) {
|
|||||||
return !variable.validation.success;
|
return !variable.validation.success;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Find deprecated variables
|
||||||
|
const deprecatedVariables = varsArray.filter((variable) => {
|
||||||
|
const model = envVariables.find((env) => env.name === variable.key);
|
||||||
|
return !!model?.deprecated;
|
||||||
|
});
|
||||||
|
|
||||||
const validVariables = varsArray.length - variablesWithErrors.length;
|
const validVariables = varsArray.length - variablesWithErrors.length;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -773,6 +828,15 @@ function Summary({ appState }: { appState: AppEnvState }) {
|
|||||||
{overridden.length} Overridden
|
{overridden.length} Overridden
|
||||||
</Badge>
|
</Badge>
|
||||||
</If>
|
</If>
|
||||||
|
|
||||||
|
<If condition={deprecatedVariables.length > 0}>
|
||||||
|
<Badge
|
||||||
|
variant={'outline'}
|
||||||
|
className={cn({ 'text-amber-500': deprecatedVariables.length > 0 })}
|
||||||
|
>
|
||||||
|
{deprecatedVariables.length} Deprecated
|
||||||
|
</Badge>
|
||||||
|
</If>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={'flex items-center gap-x-2'}>
|
<div className={'flex items-center gap-x-2'}>
|
||||||
@@ -787,6 +851,17 @@ function Summary({ appState }: { appState: AppEnvState }) {
|
|||||||
</Button>
|
</Button>
|
||||||
</If>
|
</If>
|
||||||
|
|
||||||
|
<If condition={deprecatedVariables.length > 0}>
|
||||||
|
<Button
|
||||||
|
size={'sm'}
|
||||||
|
variant={'outline'}
|
||||||
|
onClick={() => handleFilterChange('deprecated', true, true)}
|
||||||
|
>
|
||||||
|
<TriangleAlertIcon className="mr-2 h-3 w-3" />
|
||||||
|
Display Deprecated only
|
||||||
|
</Button>
|
||||||
|
</If>
|
||||||
|
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
@@ -860,6 +935,7 @@ function useUpdateFilteredVariables() {
|
|||||||
searchParams.delete('overridden');
|
searchParams.delete('overridden');
|
||||||
searchParams.delete('private');
|
searchParams.delete('private');
|
||||||
searchParams.delete('invalid');
|
searchParams.delete('invalid');
|
||||||
|
searchParams.delete('deprecated');
|
||||||
};
|
};
|
||||||
|
|
||||||
if (reset) {
|
if (reset) {
|
||||||
|
|||||||
@@ -21,6 +21,10 @@ export type EnvVariableModel = {
|
|||||||
values?: Values;
|
values?: Values;
|
||||||
category: string;
|
category: string;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
|
deprecated?: {
|
||||||
|
reason: string;
|
||||||
|
alternative?: string;
|
||||||
|
};
|
||||||
validate?: ({
|
validate?: ({
|
||||||
value,
|
value,
|
||||||
variables,
|
variables,
|
||||||
@@ -409,6 +413,10 @@ export const envVariables: EnvVariableModel[] = [
|
|||||||
category: 'Supabase',
|
category: 'Supabase',
|
||||||
required: true,
|
required: true,
|
||||||
type: 'string',
|
type: 'string',
|
||||||
|
deprecated: {
|
||||||
|
reason: 'Replaced by new JWT signing key system',
|
||||||
|
alternative: 'NEXT_PUBLIC_SUPABASE_PUBLIC_KEY',
|
||||||
|
},
|
||||||
validate: ({ value }) => {
|
validate: ({ value }) => {
|
||||||
return z
|
return z
|
||||||
.string()
|
.string()
|
||||||
@@ -419,6 +427,24 @@ export const envVariables: EnvVariableModel[] = [
|
|||||||
.safeParse(value);
|
.safeParse(value);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'NEXT_PUBLIC_SUPABASE_PUBLIC_KEY',
|
||||||
|
description: 'Your Supabase public API key.',
|
||||||
|
category: 'Supabase',
|
||||||
|
required: false,
|
||||||
|
type: 'string',
|
||||||
|
hint: 'Falls back to NEXT_PUBLIC_SUPABASE_ANON_KEY if not provided',
|
||||||
|
validate: ({ value }) => {
|
||||||
|
return z
|
||||||
|
.string()
|
||||||
|
.min(
|
||||||
|
1,
|
||||||
|
`The NEXT_PUBLIC_SUPABASE_PUBLIC_KEY variable must be at least 1 character`,
|
||||||
|
)
|
||||||
|
.optional()
|
||||||
|
.safeParse(value);
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'SUPABASE_SERVICE_ROLE_KEY',
|
name: 'SUPABASE_SERVICE_ROLE_KEY',
|
||||||
description: 'Your Supabase service role key (keep this secret!).',
|
description: 'Your Supabase service role key (keep this secret!).',
|
||||||
@@ -426,6 +452,10 @@ export const envVariables: EnvVariableModel[] = [
|
|||||||
secret: true,
|
secret: true,
|
||||||
required: true,
|
required: true,
|
||||||
type: 'string',
|
type: 'string',
|
||||||
|
deprecated: {
|
||||||
|
reason: 'Renamed for consistency with new JWT signing key system',
|
||||||
|
alternative: 'SUPABASE_SECRET_KEY',
|
||||||
|
},
|
||||||
validate: ({ value, variables }) => {
|
validate: ({ value, variables }) => {
|
||||||
return z
|
return z
|
||||||
.string()
|
.string()
|
||||||
@@ -444,6 +474,34 @@ export const envVariables: EnvVariableModel[] = [
|
|||||||
.safeParse(value);
|
.safeParse(value);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'SUPABASE_SECRET_KEY',
|
||||||
|
description:
|
||||||
|
'Your Supabase secret key (preferred over SUPABASE_SERVICE_ROLE_KEY).',
|
||||||
|
category: 'Supabase',
|
||||||
|
secret: true,
|
||||||
|
required: false,
|
||||||
|
type: 'string',
|
||||||
|
hint: 'Falls back to SUPABASE_SERVICE_ROLE_KEY if not provided',
|
||||||
|
validate: ({ value, variables }) => {
|
||||||
|
return z
|
||||||
|
.string()
|
||||||
|
.min(1, `The SUPABASE_SECRET_KEY variable must be at least 1 character`)
|
||||||
|
.refine(
|
||||||
|
(value) => {
|
||||||
|
const anonKey =
|
||||||
|
variables['NEXT_PUBLIC_SUPABASE_ANON_KEY'] ||
|
||||||
|
variables['NEXT_PUBLIC_SUPABASE_PUBLIC_KEY'];
|
||||||
|
return value !== anonKey;
|
||||||
|
},
|
||||||
|
{
|
||||||
|
message: `The SUPABASE_SECRET_KEY variable must be different from public keys`,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.optional()
|
||||||
|
.safeParse(value);
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'SUPABASE_DB_WEBHOOK_SECRET',
|
name: 'SUPABASE_DB_WEBHOOK_SECRET',
|
||||||
description: 'Secret key for Supabase webhook verification.',
|
description: 'Secret key for Supabase webhook verification.',
|
||||||
@@ -474,6 +532,21 @@ export const envVariables: EnvVariableModel[] = [
|
|||||||
return z.enum(['stripe', 'lemon-squeezy']).optional().safeParse(value);
|
return z.enum(['stripe', 'lemon-squeezy']).optional().safeParse(value);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'BILLING_MODE',
|
||||||
|
description: 'Billing mode configuration for the application.',
|
||||||
|
category: 'Billing',
|
||||||
|
required: false,
|
||||||
|
type: 'enum',
|
||||||
|
values: ['subscription', 'one-time'],
|
||||||
|
deprecated: {
|
||||||
|
reason: 'This configuration is no longer required and billing mode is now automatically determined',
|
||||||
|
alternative: undefined,
|
||||||
|
},
|
||||||
|
validate: ({ value }) => {
|
||||||
|
return z.enum(['subscription', 'one-time']).optional().safeParse(value);
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY',
|
name: 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY',
|
||||||
description: 'Your Stripe publishable key.',
|
description: 'Your Stripe publishable key.',
|
||||||
|
|||||||
@@ -3,11 +3,9 @@
|
|||||||
import dynamic from 'next/dynamic';
|
import dynamic from 'next/dynamic';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
|
|
||||||
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
|
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
|
||||||
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
|
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
|
||||||
import { useSupabase } from '@kit/supabase/hooks/use-supabase';
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { If } from '@kit/ui/if';
|
import { If } from '@kit/ui/if';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
@@ -35,17 +33,20 @@ const features = {
|
|||||||
enableThemeToggle: featuresFlagConfig.enableThemeToggle,
|
enableThemeToggle: featuresFlagConfig.enableThemeToggle,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function SiteHeaderAccountSection() {
|
export function SiteHeaderAccountSection({
|
||||||
const session = useSession();
|
user,
|
||||||
|
}: {
|
||||||
|
user: JWTUserData | null;
|
||||||
|
}) {
|
||||||
const signOut = useSignOut();
|
const signOut = useSignOut();
|
||||||
|
|
||||||
if (session.data) {
|
if (user) {
|
||||||
return (
|
return (
|
||||||
<PersonalAccountDropdown
|
<PersonalAccountDropdown
|
||||||
showProfileName={false}
|
showProfileName={false}
|
||||||
paths={paths}
|
paths={paths}
|
||||||
features={features}
|
features={features}
|
||||||
user={session.data.user}
|
user={user}
|
||||||
signOutRequested={() => signOut.mutateAsync()}
|
signOutRequested={() => signOut.mutateAsync()}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -85,16 +86,3 @@ function AuthButtons() {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function useSession() {
|
|
||||||
const client = useSupabase();
|
|
||||||
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ['session'],
|
|
||||||
queryFn: async () => {
|
|
||||||
const { data } = await client.auth.getSession();
|
|
||||||
|
|
||||||
return data.session;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
import { Header } from '@kit/ui/marketing';
|
import { Header } from '@kit/ui/marketing';
|
||||||
|
|
||||||
import { AppLogo } from '~/components/app-logo';
|
import { AppLogo } from '~/components/app-logo';
|
||||||
@@ -5,12 +6,12 @@ import { AppLogo } from '~/components/app-logo';
|
|||||||
import { SiteHeaderAccountSection } from './site-header-account-section';
|
import { SiteHeaderAccountSection } from './site-header-account-section';
|
||||||
import { SiteNavigation } from './site-navigation';
|
import { SiteNavigation } from './site-navigation';
|
||||||
|
|
||||||
export function SiteHeader() {
|
export function SiteHeader(props: { user?: JWTUserData | null }) {
|
||||||
return (
|
return (
|
||||||
<Header
|
<Header
|
||||||
logo={<AppLogo />}
|
logo={<AppLogo />}
|
||||||
navigation={<SiteNavigation />}
|
navigation={<SiteNavigation />}
|
||||||
actions={<SiteHeaderAccountSection />}
|
actions={<SiteHeaderAccountSection user={props.user ?? null} />}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
|
import { requireUser } from '@kit/supabase/require-user';
|
||||||
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
import { SiteFooter } from '~/(marketing)/_components/site-footer';
|
import { SiteFooter } from '~/(marketing)/_components/site-footer';
|
||||||
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
function SiteLayout(props: React.PropsWithChildren) {
|
async function SiteLayout(props: React.PropsWithChildren) {
|
||||||
|
const client = getSupabaseServerClient();
|
||||||
|
const user = await requireUser(client, { verifyMfa: false });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={'flex min-h-[100vh] flex-col'}>
|
<div className={'flex min-h-[100vh] flex-col'}>
|
||||||
<SiteHeader />
|
<SiteHeader user={user.data} />
|
||||||
|
|
||||||
{props.children}
|
{props.children}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import Link from 'next/link';
|
|||||||
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
||||||
|
|
||||||
import { useCaptureException } from '@kit/monitoring/hooks';
|
import { useCaptureException } from '@kit/monitoring/hooks';
|
||||||
|
import { useUser } from '@kit/supabase/hooks/use-user';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Heading } from '@kit/ui/heading';
|
import { Heading } from '@kit/ui/heading';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
@@ -20,9 +21,11 @@ const ErrorPage = ({
|
|||||||
}) => {
|
}) => {
|
||||||
useCaptureException(error);
|
useCaptureException(error);
|
||||||
|
|
||||||
|
const user = useUser();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={'flex h-screen flex-1 flex-col'}>
|
<div className={'flex h-screen flex-1 flex-col'}>
|
||||||
<SiteHeader />
|
<SiteHeader user={user.data} />
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className={
|
className={
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import Link from 'next/link';
|
|||||||
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
||||||
|
|
||||||
import { useCaptureException } from '@kit/monitoring/hooks';
|
import { useCaptureException } from '@kit/monitoring/hooks';
|
||||||
|
import { useUser } from '@kit/supabase/hooks/use-user';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Heading } from '@kit/ui/heading';
|
import { Heading } from '@kit/ui/heading';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
@@ -21,12 +22,14 @@ const GlobalErrorPage = ({
|
|||||||
}) => {
|
}) => {
|
||||||
useCaptureException(error);
|
useCaptureException(error);
|
||||||
|
|
||||||
|
const user = useUser();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html>
|
<html>
|
||||||
<body>
|
<body>
|
||||||
<RootProviders>
|
<RootProviders>
|
||||||
<div className={'flex h-screen flex-1 flex-col'}>
|
<div className={'flex h-screen flex-1 flex-col'}>
|
||||||
<SiteHeader />
|
<SiteHeader user={user.data} />
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className={
|
className={
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import type { User } from '@supabase/supabase-js';
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Sidebar,
|
Sidebar,
|
||||||
SidebarContent,
|
SidebarContent,
|
||||||
@@ -24,7 +23,7 @@ export function TeamAccountLayoutSidebar(props: {
|
|||||||
account: string;
|
account: string;
|
||||||
accountId: string;
|
accountId: string;
|
||||||
accounts: AccountModel[];
|
accounts: AccountModel[];
|
||||||
user: User;
|
user: JWTUserData;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<SidebarContainer
|
<SidebarContainer
|
||||||
@@ -40,7 +39,7 @@ function SidebarContainer(props: {
|
|||||||
account: string;
|
account: string;
|
||||||
accountId: string;
|
accountId: string;
|
||||||
accounts: AccountModel[];
|
accounts: AccountModel[];
|
||||||
user: User;
|
user: JWTUserData;
|
||||||
}) {
|
}) {
|
||||||
const { account, accounts, user } = props;
|
const { account, accounts, user } = props;
|
||||||
const userId = user.id;
|
const userId = user.id;
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import Link from 'next/link';
|
|||||||
|
|
||||||
import { ArrowLeft } from 'lucide-react';
|
import { ArrowLeft } from 'lucide-react';
|
||||||
|
|
||||||
|
import { requireUser } from '@kit/supabase/require-user';
|
||||||
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Heading } from '@kit/ui/heading';
|
import { Heading } from '@kit/ui/heading';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
@@ -20,9 +22,12 @@ export const generateMetadata = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const NotFoundPage = async () => {
|
const NotFoundPage = async () => {
|
||||||
|
const client = getSupabaseServerClient();
|
||||||
|
const user = await requireUser(client, { verifyMfa: false });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={'flex h-screen flex-1 flex-col'}>
|
<div className={'flex h-screen flex-1 flex-col'}>
|
||||||
<SiteHeader />
|
<SiteHeader user={user.data} />
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className={
|
className={
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import type { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
|
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
|
||||||
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
|
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
|
||||||
import { useUser } from '@kit/supabase/hooks/use-user';
|
import { useUser } from '@kit/supabase/hooks/use-user';
|
||||||
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
|
|
||||||
import featuresFlagConfig from '~/config/feature-flags.config';
|
import featuresFlagConfig from '~/config/feature-flags.config';
|
||||||
import pathsConfig from '~/config/paths.config';
|
import pathsConfig from '~/config/paths.config';
|
||||||
@@ -18,7 +17,7 @@ const features = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function ProfileAccountDropdownContainer(props: {
|
export function ProfileAccountDropdownContainer(props: {
|
||||||
user?: User;
|
user?: JWTUserData | null;
|
||||||
showProfileName?: boolean;
|
showProfileName?: boolean;
|
||||||
|
|
||||||
account?: {
|
account?: {
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ import { useMemo } from 'react';
|
|||||||
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import type { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ChevronsUpDown,
|
ChevronsUpDown,
|
||||||
Home,
|
Home,
|
||||||
@@ -14,6 +12,7 @@ import {
|
|||||||
Shield,
|
Shield,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
@@ -38,7 +37,7 @@ export function PersonalAccountDropdown({
|
|||||||
features,
|
features,
|
||||||
account,
|
account,
|
||||||
}: {
|
}: {
|
||||||
user: User;
|
user: JWTUserData;
|
||||||
|
|
||||||
account?: {
|
account?: {
|
||||||
id: string | null;
|
id: string | null;
|
||||||
@@ -76,13 +75,10 @@ export function PersonalAccountDropdown({
|
|||||||
personalAccountData?.name ?? account?.name ?? user?.email ?? '';
|
personalAccountData?.name ?? account?.name ?? user?.email ?? '';
|
||||||
|
|
||||||
const isSuperAdmin = useMemo(() => {
|
const isSuperAdmin = useMemo(() => {
|
||||||
const factors = user?.factors ?? [];
|
|
||||||
const hasAdminRole = user?.app_metadata.role === 'super-admin';
|
const hasAdminRole = user?.app_metadata.role === 'super-admin';
|
||||||
const hasTotpFactor = factors.some(
|
const isAal2 = user?.aal === 'aal2';
|
||||||
(factor) => factor.factor_type === 'totp' && factor.status === 'verified',
|
|
||||||
);
|
|
||||||
|
|
||||||
return hasAdminRole && hasTotpFactor;
|
return hasAdminRole && isAal2;
|
||||||
}, [user]);
|
}, [user]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -12,9 +12,11 @@ export function UpdateEmailFormContainer(props: { callbackPath: string }) {
|
|||||||
return <LoadingOverlay fullPage={false} />;
|
return <LoadingOverlay fullPage={false} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!user) {
|
if (!user || !user.email) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <UpdateEmailForm callbackPath={props.callbackPath} user={user} />;
|
return (
|
||||||
|
<UpdateEmailForm callbackPath={props.callbackPath} email={user.email} />
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import type { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { CheckIcon } from '@radix-ui/react-icons';
|
import { CheckIcon } from '@radix-ui/react-icons';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
@@ -34,10 +32,10 @@ function createEmailResolver(currentEmail: string, errorMessage: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function UpdateEmailForm({
|
export function UpdateEmailForm({
|
||||||
user,
|
email,
|
||||||
callbackPath,
|
callbackPath,
|
||||||
}: {
|
}: {
|
||||||
user: User;
|
email: string;
|
||||||
callbackPath: string;
|
callbackPath: string;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation('account');
|
const { t } = useTranslation('account');
|
||||||
@@ -61,10 +59,8 @@ export function UpdateEmailForm({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const currentEmail = user.email;
|
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
resolver: createEmailResolver(currentEmail!, t('emailNotMatching')),
|
resolver: createEmailResolver(email, t('emailNotMatching')),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
email: '',
|
email: '',
|
||||||
repeatEmail: '',
|
repeatEmail: '',
|
||||||
|
|||||||
@@ -413,6 +413,7 @@ function FactorNameForm(
|
|||||||
|
|
||||||
function QrImage({ src }: { src: string }) {
|
function QrImage({ src }: { src: string }) {
|
||||||
return (
|
return (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
<img
|
<img
|
||||||
alt={'QR Code'}
|
alt={'QR Code'}
|
||||||
src={src}
|
src={src}
|
||||||
|
|||||||
@@ -20,5 +20,7 @@ export function UpdatePasswordFormContainer(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <UpdatePasswordForm callbackPath={props.callbackPath} user={user} />;
|
return (
|
||||||
|
<UpdatePasswordForm callbackPath={props.callbackPath} email={user.email} />
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
import type { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { ExclamationTriangleIcon } from '@radix-ui/react-icons';
|
import { ExclamationTriangleIcon } from '@radix-ui/react-icons';
|
||||||
import { Check } from 'lucide-react';
|
import { Check } from 'lucide-react';
|
||||||
@@ -31,10 +29,10 @@ import { Trans } from '@kit/ui/trans';
|
|||||||
import { PasswordUpdateSchema } from '../../../schema/update-password.schema';
|
import { PasswordUpdateSchema } from '../../../schema/update-password.schema';
|
||||||
|
|
||||||
export const UpdatePasswordForm = ({
|
export const UpdatePasswordForm = ({
|
||||||
user,
|
email,
|
||||||
callbackPath,
|
callbackPath,
|
||||||
}: {
|
}: {
|
||||||
user: User;
|
email: string;
|
||||||
callbackPath: string;
|
callbackPath: string;
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation('account');
|
const { t } = useTranslation('account');
|
||||||
@@ -69,8 +67,6 @@ export const UpdatePasswordForm = ({
|
|||||||
}: {
|
}: {
|
||||||
newPassword: string;
|
newPassword: string;
|
||||||
}) => {
|
}) => {
|
||||||
const email = user.email;
|
|
||||||
|
|
||||||
// if the user does not have an email assigned, it's possible they
|
// if the user does not have an email assigned, it's possible they
|
||||||
// don't have an email/password factor linked, and the UI is out of sync
|
// don't have an email/password factor linked, and the UI is out of sync
|
||||||
if (!email) {
|
if (!email) {
|
||||||
|
|||||||
@@ -2,9 +2,8 @@
|
|||||||
|
|
||||||
import { createContext } from 'react';
|
import { createContext } from 'react';
|
||||||
|
|
||||||
import { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { Tables } from '@kit/supabase/database';
|
import { Tables } from '@kit/supabase/database';
|
||||||
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
|
|
||||||
interface UserWorkspace {
|
interface UserWorkspace {
|
||||||
accounts: Array<{
|
accounts: Array<{
|
||||||
@@ -20,7 +19,7 @@ interface UserWorkspace {
|
|||||||
subscription_status: Tables<'subscriptions'>['status'] | null;
|
subscription_status: Tables<'subscriptions'>['status'] | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
user: User;
|
user: JWTUserData;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const UserWorkspaceContext = createContext<UserWorkspace>(
|
export const UserWorkspaceContext = createContext<UserWorkspace>(
|
||||||
|
|||||||
@@ -2,14 +2,13 @@
|
|||||||
|
|
||||||
import { createContext } from 'react';
|
import { createContext } from 'react';
|
||||||
|
|
||||||
import { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
|
|
||||||
interface AccountWorkspace {
|
interface AccountWorkspace {
|
||||||
accounts: Database['public']['Views']['user_accounts']['Row'][];
|
accounts: Database['public']['Views']['user_accounts']['Row'][];
|
||||||
account: Database['public']['Functions']['team_account_workspace']['Returns'][0];
|
account: Database['public']['Functions']['team_account_workspace']['Returns'][0];
|
||||||
user: User;
|
user: JWTUserData;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const TeamAccountWorkspaceContext = createContext<AccountWorkspace>(
|
export const TeamAccountWorkspaceContext = createContext<AccountWorkspace>(
|
||||||
|
|||||||
@@ -2,13 +2,12 @@ import 'server-only';
|
|||||||
|
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
import type { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { ZodType, z } from 'zod';
|
import { ZodType, z } from 'zod';
|
||||||
|
|
||||||
import { verifyCaptchaToken } from '@kit/auth/captcha/server';
|
import { verifyCaptchaToken } from '@kit/auth/captcha/server';
|
||||||
import { requireUser } from '@kit/supabase/require-user';
|
import { requireUser } from '@kit/supabase/require-user';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
|
|
||||||
import { zodParseFactory } from '../utils';
|
import { zodParseFactory } from '../utils';
|
||||||
|
|
||||||
@@ -30,14 +29,14 @@ export function enhanceAction<
|
|||||||
>(
|
>(
|
||||||
fn: (
|
fn: (
|
||||||
params: Config['schema'] extends ZodType ? z.infer<Config['schema']> : Args,
|
params: Config['schema'] extends ZodType ? z.infer<Config['schema']> : Args,
|
||||||
user: Config['auth'] extends false ? undefined : User,
|
user: Config['auth'] extends false ? undefined : JWTUserData,
|
||||||
) => Response | Promise<Response>,
|
) => Response | Promise<Response>,
|
||||||
config: Config,
|
config: Config,
|
||||||
) {
|
) {
|
||||||
return async (
|
return async (
|
||||||
params: Config['schema'] extends ZodType ? z.infer<Config['schema']> : Args,
|
params: Config['schema'] extends ZodType ? z.infer<Config['schema']> : Args,
|
||||||
) => {
|
) => {
|
||||||
type UserParam = Config['auth'] extends false ? undefined : User;
|
type UserParam = Config['auth'] extends false ? undefined : JWTUserData;
|
||||||
|
|
||||||
const requireAuth = config.auth ?? true;
|
const requireAuth = config.auth ?? true;
|
||||||
let user: UserParam = undefined as UserParam;
|
let user: UserParam = undefined as UserParam;
|
||||||
|
|||||||
@@ -3,13 +3,12 @@ import 'server-only';
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
|
||||||
import { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { verifyCaptchaToken } from '@kit/auth/captcha/server';
|
import { verifyCaptchaToken } from '@kit/auth/captcha/server';
|
||||||
import { requireUser } from '@kit/supabase/require-user';
|
import { requireUser } from '@kit/supabase/require-user';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { JWTUserData } from '@kit/supabase/types';
|
||||||
|
|
||||||
import { zodParseFactory } from '../utils';
|
import { zodParseFactory } from '../utils';
|
||||||
|
|
||||||
@@ -24,7 +23,7 @@ interface HandlerParams<
|
|||||||
RequireAuth extends boolean | undefined,
|
RequireAuth extends boolean | undefined,
|
||||||
> {
|
> {
|
||||||
request: NextRequest;
|
request: NextRequest;
|
||||||
user: RequireAuth extends false ? undefined : User;
|
user: RequireAuth extends false ? undefined : JWTUserData;
|
||||||
body: Schema extends z.ZodType ? z.infer<Schema> : undefined;
|
body: Schema extends z.ZodType ? z.infer<Schema> : undefined;
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
}
|
}
|
||||||
@@ -75,7 +74,7 @@ export const enhanceRouteHandler = <
|
|||||||
params: Promise<Record<string, string>>;
|
params: Promise<Record<string, string>>;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
type UserParam = Params['auth'] extends false ? undefined : User;
|
type UserParam = Params['auth'] extends false ? undefined : JWTUserData;
|
||||||
|
|
||||||
let user: UserParam = undefined as UserParam;
|
let user: UserParam = undefined as UserParam;
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,8 @@
|
|||||||
"./require-user": "./src/require-user.ts",
|
"./require-user": "./src/require-user.ts",
|
||||||
"./hooks/*": "./src/hooks/*.ts",
|
"./hooks/*": "./src/hooks/*.ts",
|
||||||
"./database": "./src/database.types.ts",
|
"./database": "./src/database.types.ts",
|
||||||
"./auth": "./src/auth.ts"
|
"./auth": "./src/auth.ts",
|
||||||
|
"./types": "./src/types.ts"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@kit/eslint-config": "workspace:*",
|
"@kit/eslint-config": "workspace:*",
|
||||||
|
|||||||
@@ -10,5 +10,5 @@ import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
|||||||
export function getSupabaseBrowserClient<GenericSchema = Database>() {
|
export function getSupabaseBrowserClient<GenericSchema = Database>() {
|
||||||
const keys = getSupabaseClientKeys();
|
const keys = getSupabaseClientKeys();
|
||||||
|
|
||||||
return createBrowserClient<GenericSchema>(keys.url, keys.anonKey);
|
return createBrowserClient<GenericSchema>(keys.url, keys.publicKey);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export function createMiddlewareClient<GenericSchema = Database>(
|
|||||||
) {
|
) {
|
||||||
const keys = getSupabaseClientKeys();
|
const keys = getSupabaseClientKeys();
|
||||||
|
|
||||||
return createServerClient<GenericSchema>(keys.url, keys.anonKey, {
|
return createServerClient<GenericSchema>(keys.url, keys.publicKey, {
|
||||||
cookies: {
|
cookies: {
|
||||||
getAll() {
|
getAll() {
|
||||||
return request.cookies.getAll();
|
return request.cookies.getAll();
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import { createClient } from '@supabase/supabase-js';
|
|||||||
|
|
||||||
import { Database } from '../database.types';
|
import { Database } from '../database.types';
|
||||||
import {
|
import {
|
||||||
getServiceRoleKey,
|
getSupabaseSecretKey,
|
||||||
warnServiceRoleKeyUsage,
|
warnServiceRoleKeyUsage,
|
||||||
} from '../get-service-role-key';
|
} from '../get-secret-key';
|
||||||
import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,8 +17,9 @@ export function getSupabaseServerAdminClient<GenericSchema = Database>() {
|
|||||||
warnServiceRoleKeyUsage();
|
warnServiceRoleKeyUsage();
|
||||||
|
|
||||||
const url = getSupabaseClientKeys().url;
|
const url = getSupabaseClientKeys().url;
|
||||||
|
const secretKey = getSupabaseSecretKey();
|
||||||
|
|
||||||
return createClient<GenericSchema>(url, getServiceRoleKey(), {
|
return createClient<GenericSchema>(url, secretKey, {
|
||||||
auth: {
|
auth: {
|
||||||
persistSession: false,
|
persistSession: false,
|
||||||
detectSessionInUrl: false,
|
detectSessionInUrl: false,
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
|||||||
export function getSupabaseServerClient<GenericSchema = Database>() {
|
export function getSupabaseServerClient<GenericSchema = Database>() {
|
||||||
const keys = getSupabaseClientKeys();
|
const keys = getSupabaseClientKeys();
|
||||||
|
|
||||||
return createServerClient<GenericSchema>(keys.url, keys.anonKey, {
|
return createServerClient<GenericSchema>(keys.url, keys.publicKey, {
|
||||||
cookies: {
|
cookies: {
|
||||||
async getAll() {
|
async getAll() {
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
|
|||||||
@@ -3,14 +3,14 @@ import 'server-only';
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const message =
|
const message =
|
||||||
'Invalid Supabase Service Role Key. Please add the environment variable SUPABASE_SERVICE_ROLE_KEY.';
|
'Invalid Supabase Secret Key. Please add the environment variable SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY.';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @name getServiceRoleKey
|
* @name getSupabaseSecretKey
|
||||||
* @description Get the Supabase Service Role Key.
|
* @description Get the Supabase Service Role Key.
|
||||||
* ONLY USE IN SERVER-SIDE CODE. DO NOT EXPOSE THIS TO CLIENT-SIDE CODE.
|
* ONLY USE IN SERVER-SIDE CODE. DO NOT EXPOSE THIS TO CLIENT-SIDE CODE.
|
||||||
*/
|
*/
|
||||||
export function getServiceRoleKey() {
|
export function getSupabaseSecretKey() {
|
||||||
return z
|
return z
|
||||||
.string({
|
.string({
|
||||||
required_error: message,
|
required_error: message,
|
||||||
@@ -18,7 +18,9 @@ export function getServiceRoleKey() {
|
|||||||
.min(1, {
|
.min(1, {
|
||||||
message: message,
|
message: message,
|
||||||
})
|
})
|
||||||
.parse(process.env.SUPABASE_SERVICE_ROLE_KEY);
|
.parse(
|
||||||
|
process.env.SUPABASE_SECRET_KEY || process.env.SUPABASE_SERVICE_ROLE_KEY,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,7 +29,7 @@ export function getServiceRoleKey() {
|
|||||||
export function warnServiceRoleKeyUsage() {
|
export function warnServiceRoleKeyUsage() {
|
||||||
if (process.env.NODE_ENV !== 'production') {
|
if (process.env.NODE_ENV !== 'production') {
|
||||||
console.warn(
|
console.warn(
|
||||||
`[Dev Only] This is a simple warning to let you know you are using the Supabase Service Role. Make sure it's the right call.`,
|
`[Dev Only] This is a simple warning to let you know you are using the Supabase Secret Key. This key bypasses RLS and should only be used in server-side code. Please make sure it's the intended usage.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,15 +10,15 @@ export function getSupabaseClientKeys() {
|
|||||||
description: `This is the URL of your hosted Supabase instance. Please provide the variable NEXT_PUBLIC_SUPABASE_URL.`,
|
description: `This is the URL of your hosted Supabase instance. Please provide the variable NEXT_PUBLIC_SUPABASE_URL.`,
|
||||||
required_error: `Please provide the variable NEXT_PUBLIC_SUPABASE_URL`,
|
required_error: `Please provide the variable NEXT_PUBLIC_SUPABASE_URL`,
|
||||||
}),
|
}),
|
||||||
anonKey: z
|
publicKey: z.string({
|
||||||
.string({
|
description: `This is the public key provided by Supabase. It is a public key used client-side. Please provide the variable NEXT_PUBLIC_SUPABASE_PUBLIC_KEY.`,
|
||||||
description: `This is the anon key provided by Supabase. It is a public key used client-side. Please provide the variable NEXT_PUBLIC_SUPABASE_ANON_KEY.`,
|
required_error: `Please provide the variable NEXT_PUBLIC_SUPABASE_PUBLIC_KEY`,
|
||||||
required_error: `Please provide the variable NEXT_PUBLIC_SUPABASE_ANON_KEY`,
|
}),
|
||||||
})
|
|
||||||
.min(1),
|
|
||||||
})
|
})
|
||||||
.parse({
|
.parse({
|
||||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
|
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
|
||||||
anonKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
publicKey:
|
||||||
|
process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY ||
|
||||||
|
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,22 @@
|
|||||||
import type { User } from '@supabase/supabase-js';
|
|
||||||
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
|
||||||
|
import { requireUser } from '../require-user';
|
||||||
|
import { JWTUserData } from '../types';
|
||||||
import { useSupabase } from './use-supabase';
|
import { useSupabase } from './use-supabase';
|
||||||
|
|
||||||
const queryKey = ['supabase:user'];
|
const queryKey = ['supabase:user'];
|
||||||
|
|
||||||
export function useUser(initialData?: User | null) {
|
export function useUser(initialData?: JWTUserData | null) {
|
||||||
const client = useSupabase();
|
const client = useSupabase();
|
||||||
|
|
||||||
const queryFn = async () => {
|
const queryFn = async () => {
|
||||||
const response = await client.auth.getUser();
|
const response = await requireUser(client);
|
||||||
|
|
||||||
// this is most likely a session error or the user is not logged in
|
|
||||||
if (response.error) {
|
if (response.error) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.data?.user) {
|
return response.data;
|
||||||
return response.data.user;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.reject(new Error('Unexpected result format'));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
|
|||||||
@@ -1,19 +1,45 @@
|
|||||||
import type { SupabaseClient, User } from '@supabase/supabase-js';
|
import type { SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
import { checkRequiresMultiFactorAuthentication } from './check-requires-mfa';
|
import { checkRequiresMultiFactorAuthentication } from './check-requires-mfa';
|
||||||
|
import { JWTUserData } from './types';
|
||||||
|
|
||||||
const MULTI_FACTOR_AUTH_VERIFY_PATH = '/auth/verify';
|
const MULTI_FACTOR_AUTH_VERIFY_PATH = '/auth/verify';
|
||||||
const SIGN_IN_PATH = '/auth/sign-in';
|
const SIGN_IN_PATH = '/auth/sign-in';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @name UserClaims
|
||||||
|
* @description The user claims returned from the Supabase auth API.
|
||||||
|
*/
|
||||||
|
type UserClaims = {
|
||||||
|
aud: string;
|
||||||
|
exp: number;
|
||||||
|
iat: number;
|
||||||
|
iss: string;
|
||||||
|
sub: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
app_metadata: Record<string, unknown>;
|
||||||
|
user_metadata: Record<string, unknown>;
|
||||||
|
role: string;
|
||||||
|
aal: `aal1` | `aal2`;
|
||||||
|
session_id: string;
|
||||||
|
is_anonymous: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @name requireUser
|
* @name requireUser
|
||||||
* @description Require a session to be present in the request
|
* @description Require a session to be present in the request
|
||||||
* @param client
|
* @param client
|
||||||
*/
|
*/
|
||||||
export async function requireUser(client: SupabaseClient): Promise<
|
export async function requireUser(
|
||||||
|
client: SupabaseClient,
|
||||||
|
options?: {
|
||||||
|
verifyMfa?: boolean;
|
||||||
|
},
|
||||||
|
): Promise<
|
||||||
| {
|
| {
|
||||||
error: null;
|
error: null;
|
||||||
data: User;
|
data: JWTUserData;
|
||||||
}
|
}
|
||||||
| (
|
| (
|
||||||
| {
|
| {
|
||||||
@@ -28,9 +54,9 @@ export async function requireUser(client: SupabaseClient): Promise<
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
> {
|
> {
|
||||||
const { data, error } = await client.auth.getUser();
|
const { data, error } = await client.auth.getClaims();
|
||||||
|
|
||||||
if (!data.user || error) {
|
if (!data?.claims || error) {
|
||||||
return {
|
return {
|
||||||
data: null,
|
data: null,
|
||||||
error: new AuthenticationError(),
|
error: new AuthenticationError(),
|
||||||
@@ -38,21 +64,36 @@ export async function requireUser(client: SupabaseClient): Promise<
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const requiresMfa = await checkRequiresMultiFactorAuthentication(client);
|
const { verifyMfa = true } = options ?? {};
|
||||||
|
|
||||||
// If the user requires multi-factor authentication,
|
if (verifyMfa) {
|
||||||
// redirect them to the page where they can verify their identity.
|
const requiresMfa = await checkRequiresMultiFactorAuthentication(client);
|
||||||
if (requiresMfa) {
|
|
||||||
return {
|
// If the user requires multi-factor authentication,
|
||||||
data: null,
|
// redirect them to the page where they can verify their identity.
|
||||||
error: new MultiFactorAuthError(),
|
if (requiresMfa) {
|
||||||
redirectTo: MULTI_FACTOR_AUTH_VERIFY_PATH,
|
return {
|
||||||
};
|
data: null,
|
||||||
|
error: new MultiFactorAuthError(),
|
||||||
|
redirectTo: MULTI_FACTOR_AUTH_VERIFY_PATH,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the client doesn't type the claims, so we need to cast it to the User type
|
||||||
|
const user = data.claims as UserClaims;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
error: null,
|
error: null,
|
||||||
data: data.user,
|
data: {
|
||||||
|
is_anonymous: user.is_anonymous,
|
||||||
|
aal: user.aal,
|
||||||
|
email: user.email,
|
||||||
|
phone: user.phone,
|
||||||
|
app_metadata: user.app_metadata,
|
||||||
|
user_metadata: user.user_metadata,
|
||||||
|
id: user.sub,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
13
packages/supabase/src/types.ts
Normal file
13
packages/supabase/src/types.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @name JWTUserData
|
||||||
|
* @description The user data mapped from the JWT claims.
|
||||||
|
*/
|
||||||
|
export type JWTUserData = {
|
||||||
|
is_anonymous: boolean;
|
||||||
|
aal: `aal1` | `aal2`;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
app_metadata: Record<string, unknown>;
|
||||||
|
user_metadata: Record<string, unknown>;
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user