Add OAuth flows and UI integration
- Implemented OAuth endpoints (providers list, authorization, callback, linked accounts management). - Added UI translations for OAuth workflows (auth process messages, linked accounts management). - Extended TypeScript types and React hooks to support OAuth features. - Updated app configuration with OAuth-specific settings and provider details. - Introduced skeleton implementations for authorization and token endpoints in provider mode. - Included unit test and integration hooks for OAuth capabilities.
This commit is contained in:
@@ -143,6 +143,18 @@
|
||||
"hasNumber": "Contains a number",
|
||||
"hasUppercase": "Contains an uppercase letter"
|
||||
}
|
||||
},
|
||||
"oauth": {
|
||||
"divider": "Or continue with",
|
||||
"loading": "Loading providers...",
|
||||
"continueWith": "Continue with {provider}",
|
||||
"signUpWith": "Sign up with {provider}",
|
||||
"processing": "Completing authentication...",
|
||||
"authFailed": "Authentication Failed",
|
||||
"providerError": "The authentication provider returned an error",
|
||||
"missingParams": "Missing authentication parameters",
|
||||
"unexpectedError": "An unexpected error occurred during authentication",
|
||||
"backToLogin": "Back to Login"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
@@ -218,6 +230,17 @@
|
||||
"themeLight": "Light",
|
||||
"themeDark": "Dark",
|
||||
"themeSystem": "System"
|
||||
},
|
||||
"linkedAccounts": {
|
||||
"pageTitle": "Linked Accounts",
|
||||
"pageSubtitle": "Manage your linked social accounts",
|
||||
"title": "Connected Accounts",
|
||||
"description": "Connect your account with social providers for easier sign-in",
|
||||
"linked": "Connected",
|
||||
"link": "Connect",
|
||||
"unlink": "Disconnect",
|
||||
"linkError": "Failed to connect account",
|
||||
"unlinkError": "Failed to disconnect account"
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
|
||||
@@ -143,6 +143,18 @@
|
||||
"hasNumber": "Contiene un numero",
|
||||
"hasUppercase": "Contiene una lettera maiuscola"
|
||||
}
|
||||
},
|
||||
"oauth": {
|
||||
"divider": "Oppure continua con",
|
||||
"loading": "Caricamento provider...",
|
||||
"continueWith": "Continua con {provider}",
|
||||
"signUpWith": "Registrati con {provider}",
|
||||
"processing": "Completamento autenticazione...",
|
||||
"authFailed": "Autenticazione Fallita",
|
||||
"providerError": "Il provider di autenticazione ha restituito un errore",
|
||||
"missingParams": "Parametri di autenticazione mancanti",
|
||||
"unexpectedError": "Si è verificato un errore durante l'autenticazione",
|
||||
"backToLogin": "Torna al Login"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
@@ -218,6 +230,17 @@
|
||||
"themeLight": "Chiaro",
|
||||
"themeDark": "Scuro",
|
||||
"themeSystem": "Sistema"
|
||||
},
|
||||
"linkedAccounts": {
|
||||
"pageTitle": "Account Collegati",
|
||||
"pageSubtitle": "Gestisci i tuoi account social collegati",
|
||||
"title": "Account Connessi",
|
||||
"description": "Collega il tuo account con i provider social per un accesso più semplice",
|
||||
"linked": "Connesso",
|
||||
"link": "Connetti",
|
||||
"unlink": "Scollega",
|
||||
"linkError": "Impossibile connettere l'account",
|
||||
"unlinkError": "Impossibile scollegare l'account"
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* OAuth Callback Page
|
||||
* Handles the redirect from OAuth providers after authentication
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { useParams, useSearchParams } from 'next/navigation';
|
||||
import { useRouter } from '@/lib/i18n/routing';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Alert } from '@/components/ui/alert';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useOAuthCallback } from '@/lib/api/hooks/useOAuth';
|
||||
import config from '@/config/app.config';
|
||||
|
||||
export default function OAuthCallbackPage() {
|
||||
const params = useParams();
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
const t = useTranslations('auth.oauth');
|
||||
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const oauthCallback = useOAuthCallback();
|
||||
const hasProcessed = useRef(false);
|
||||
|
||||
const provider = params.provider as string;
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
const errorParam = searchParams.get('error');
|
||||
const errorDescription = searchParams.get('error_description');
|
||||
|
||||
useEffect(() => {
|
||||
// Prevent double processing in StrictMode
|
||||
if (hasProcessed.current) return;
|
||||
|
||||
// Handle OAuth provider error
|
||||
if (errorParam) {
|
||||
setError(errorDescription || t('providerError'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate required parameters
|
||||
if (!code || !state) {
|
||||
setError(t('missingParams'));
|
||||
return;
|
||||
}
|
||||
|
||||
hasProcessed.current = true;
|
||||
|
||||
// Process the OAuth callback
|
||||
oauthCallback.mutate(
|
||||
{ provider, code, state },
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
// Get the stored mode to determine redirect
|
||||
const mode = sessionStorage.getItem('oauth_mode');
|
||||
|
||||
if (data?.tokens?.is_new_user) {
|
||||
// New user - redirect to profile to complete setup
|
||||
router.push(config.routes.profile);
|
||||
} else if (mode === 'link') {
|
||||
// Account linking - redirect to settings
|
||||
router.push('/settings/profile');
|
||||
} else {
|
||||
// Regular login - redirect to dashboard
|
||||
router.push(config.routes.dashboard);
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
const errorMessage = err instanceof Error ? err.message : t('unexpectedError');
|
||||
setError(errorMessage);
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [provider, code, state, errorParam, errorDescription, oauthCallback, router, t]);
|
||||
|
||||
// Show error state
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<div className="w-full max-w-md space-y-4">
|
||||
<Alert variant="destructive">
|
||||
<p className="font-medium">{t('authFailed')}</p>
|
||||
<p className="text-sm mt-1">{error}</p>
|
||||
</Alert>
|
||||
<div className="flex gap-2 justify-center">
|
||||
<Button variant="outline" onClick={() => router.push(config.routes.login)}>
|
||||
{t('backToLogin')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Show loading state
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<div className="text-center space-y-4">
|
||||
<Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
|
||||
<p className="text-muted-foreground">{t('processing')}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Linked Accounts Settings Page
|
||||
* Manage linked OAuth provider accounts
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { LinkedAccountsSettings } from '@/components/settings';
|
||||
|
||||
export default function LinkedAccountsPage() {
|
||||
const t = useTranslations('settings.linkedAccounts');
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold text-foreground">{t('pageTitle')}</h2>
|
||||
<p className="text-muted-foreground mt-1">{t('pageSubtitle')}</p>
|
||||
</div>
|
||||
|
||||
<LinkedAccountsSettings />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { Alert } from '@/components/ui/alert';
|
||||
import { useLogin } from '@/lib/api/hooks/useAuth';
|
||||
import { getGeneralError, getFieldErrors, isAPIErrorArray } from '@/lib/api/errors';
|
||||
import config from '@/config/app.config';
|
||||
import { OAuthButtons } from './OAuthButtons';
|
||||
|
||||
// ============================================================================
|
||||
// Validation Schema
|
||||
@@ -49,6 +50,8 @@ interface LoginFormProps {
|
||||
showRegisterLink?: boolean;
|
||||
/** Show password reset link */
|
||||
showPasswordResetLink?: boolean;
|
||||
/** Show OAuth provider buttons */
|
||||
showOAuthButtons?: boolean;
|
||||
/** Custom className for form container */
|
||||
className?: string;
|
||||
}
|
||||
@@ -75,6 +78,7 @@ export function LoginForm({
|
||||
onSuccess,
|
||||
showRegisterLink = true,
|
||||
showPasswordResetLink = true,
|
||||
showOAuthButtons = true,
|
||||
className,
|
||||
}: LoginFormProps) {
|
||||
const t = useTranslations('auth.login');
|
||||
@@ -216,6 +220,9 @@ export function LoginForm({
|
||||
{isSubmitting ? t('loginButtonLoading') : t('loginButton')}
|
||||
</Button>
|
||||
|
||||
{/* OAuth Buttons */}
|
||||
{showOAuthButtons && <OAuthButtons mode="login" showDivider />}
|
||||
|
||||
{/* Registration Link */}
|
||||
{showRegisterLink && config.features.enableRegistration && (
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
|
||||
158
frontend/src/components/auth/OAuthButtons.tsx
Normal file
158
frontend/src/components/auth/OAuthButtons.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* OAuthButtons Component
|
||||
* Displays OAuth provider buttons for login/registration
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useOAuthProviders, useOAuthStart } from '@/lib/api/hooks/useOAuth';
|
||||
import config from '@/config/app.config';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// ============================================================================
|
||||
// Provider Icons
|
||||
// ============================================================================
|
||||
|
||||
function GoogleIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
|
||||
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
|
||||
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
|
||||
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function GitHubIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const providerIcons: Record<string, React.ComponentType<{ className?: string }>> = {
|
||||
google: GoogleIcon,
|
||||
github: GitHubIcon,
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Component
|
||||
// ============================================================================
|
||||
|
||||
interface OAuthButtonsProps {
|
||||
/** Mode for OAuth flow */
|
||||
mode: 'login' | 'register';
|
||||
/** Show divider with "or" text */
|
||||
showDivider?: boolean;
|
||||
/** Custom className */
|
||||
className?: string;
|
||||
/** Called when OAuth flow starts */
|
||||
onStart?: (provider: string) => void;
|
||||
/** Called on error */
|
||||
onError?: (error: Error) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuthButtons - Display OAuth provider buttons
|
||||
*
|
||||
* Fetches available providers from the backend and displays
|
||||
* login/registration buttons for each enabled provider.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <OAuthButtons mode="login" showDivider />
|
||||
* ```
|
||||
*/
|
||||
export function OAuthButtons({
|
||||
mode,
|
||||
showDivider = true,
|
||||
className,
|
||||
onStart,
|
||||
onError,
|
||||
}: OAuthButtonsProps) {
|
||||
const t = useTranslations('auth.oauth');
|
||||
const { data: providersData, isLoading, error } = useOAuthProviders();
|
||||
const oauthStart = useOAuthStart();
|
||||
|
||||
// Don't render if OAuth is not enabled or no providers available
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className={cn('space-y-4', className)}>
|
||||
{showDivider && <Divider />}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button variant="outline" disabled className="w-full">
|
||||
<span className="h-5 w-5 mr-2 animate-pulse bg-muted rounded" />
|
||||
{t('loading')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !providersData?.enabled || !providersData?.providers?.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleOAuthClick = async (provider: string) => {
|
||||
try {
|
||||
onStart?.(provider);
|
||||
await oauthStart.mutateAsync({ provider, mode });
|
||||
} catch (err) {
|
||||
onError?.(err as Error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn('space-y-4', className)}>
|
||||
{showDivider && <Divider />}
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{providersData.providers.map((provider) => {
|
||||
const providerConfig = config.oauth.providers[provider.provider];
|
||||
const Icon = providerIcons[provider.provider];
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={provider.provider}
|
||||
variant="outline"
|
||||
type="button"
|
||||
className="w-full"
|
||||
disabled={oauthStart.isPending}
|
||||
onClick={() => handleOAuthClick(provider.provider)}
|
||||
>
|
||||
{Icon && <Icon className="h-5 w-5 mr-2" />}
|
||||
{mode === 'login'
|
||||
? t('continueWith', { provider: providerConfig?.name || provider.name })
|
||||
: t('signUpWith', { provider: providerConfig?.name || provider.name })}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Divider Component
|
||||
// ============================================================================
|
||||
|
||||
function Divider() {
|
||||
const t = useTranslations('auth.oauth');
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-background px-2 text-muted-foreground">{t('divider')}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default OAuthButtons;
|
||||
@@ -19,6 +19,7 @@ import { Alert } from '@/components/ui/alert';
|
||||
import { useRegister } from '@/lib/api/hooks/useAuth';
|
||||
import { getGeneralError, getFieldErrors, isAPIErrorArray } from '@/lib/api/errors';
|
||||
import config from '@/config/app.config';
|
||||
import { OAuthButtons } from './OAuthButtons';
|
||||
|
||||
// ============================================================================
|
||||
// Validation Schema
|
||||
@@ -58,6 +59,8 @@ interface RegisterFormProps {
|
||||
onSuccess?: () => void;
|
||||
/** Show login link */
|
||||
showLoginLink?: boolean;
|
||||
/** Show OAuth provider buttons */
|
||||
showOAuthButtons?: boolean;
|
||||
/** Custom className for form container */
|
||||
className?: string;
|
||||
}
|
||||
@@ -81,7 +84,12 @@ interface RegisterFormProps {
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export function RegisterForm({ onSuccess, showLoginLink = true, className }: RegisterFormProps) {
|
||||
export function RegisterForm({
|
||||
onSuccess,
|
||||
showLoginLink = true,
|
||||
showOAuthButtons = true,
|
||||
className,
|
||||
}: RegisterFormProps) {
|
||||
const t = useTranslations('auth.register');
|
||||
const tValidation = useTranslations('validation');
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
@@ -309,6 +317,9 @@ export function RegisterForm({ onSuccess, showLoginLink = true, className }: Reg
|
||||
{isSubmitting ? t('registerButtonLoading') : t('registerButton')}
|
||||
</Button>
|
||||
|
||||
{/* OAuth Buttons */}
|
||||
{showOAuthButtons && <OAuthButtons mode="register" showDivider />}
|
||||
|
||||
{/* Login Link */}
|
||||
{showLoginLink && (
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
|
||||
195
frontend/src/components/settings/LinkedAccountsSettings.tsx
Normal file
195
frontend/src/components/settings/LinkedAccountsSettings.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* LinkedAccountsSettings Component
|
||||
* Manage linked OAuth provider accounts
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Alert } from '@/components/ui/alert';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Loader2, Link as LinkIcon, Unlink, AlertTriangle } from 'lucide-react';
|
||||
import {
|
||||
useOAuthProviders,
|
||||
useOAuthAccounts,
|
||||
useOAuthLink,
|
||||
useOAuthUnlink,
|
||||
} from '@/lib/api/hooks/useOAuth';
|
||||
import config from '@/config/app.config';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// ============================================================================
|
||||
// Provider Icons
|
||||
// ============================================================================
|
||||
|
||||
function GoogleIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
|
||||
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
|
||||
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
|
||||
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function GitHubIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const providerIcons: Record<string, React.ComponentType<{ className?: string }>> = {
|
||||
google: GoogleIcon,
|
||||
github: GitHubIcon,
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Component
|
||||
// ============================================================================
|
||||
|
||||
interface LinkedAccountsSettingsProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LinkedAccountsSettings({ className }: LinkedAccountsSettingsProps) {
|
||||
const t = useTranslations('settings.linkedAccounts');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [unlinkingProvider, setUnlinkingProvider] = useState<string | null>(null);
|
||||
|
||||
const { data: providersData, isLoading: providersLoading } = useOAuthProviders();
|
||||
const { data: accountsData, isLoading: accountsLoading } = useOAuthAccounts();
|
||||
const linkMutation = useOAuthLink();
|
||||
const unlinkMutation = useOAuthUnlink();
|
||||
|
||||
const isLoading = providersLoading || accountsLoading;
|
||||
|
||||
// Don't render if OAuth is not enabled
|
||||
if (!isLoading && (!providersData?.enabled || !providersData?.providers?.length)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const linkedProviders = new Set(accountsData?.accounts?.map((a) => a.provider) || []);
|
||||
const availableProviders = providersData?.providers || [];
|
||||
|
||||
const handleLink = async (provider: string) => {
|
||||
try {
|
||||
setError(null);
|
||||
await linkMutation.mutateAsync({ provider });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t('linkError'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleUnlink = async (provider: string) => {
|
||||
try {
|
||||
setError(null);
|
||||
setUnlinkingProvider(provider);
|
||||
await unlinkMutation.mutateAsync({ provider });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t('unlinkError'));
|
||||
} finally {
|
||||
setUnlinkingProvider(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className={cn(className)}>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('title')}</CardTitle>
|
||||
<CardDescription>{t('description')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<p className="text-sm ml-2">{error}</p>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{availableProviders.map((provider) => {
|
||||
const providerConfig = config.oauth.providers[provider.provider];
|
||||
const Icon = providerIcons[provider.provider];
|
||||
const isLinked = linkedProviders.has(provider.provider);
|
||||
const linkedAccount = accountsData?.accounts?.find(
|
||||
(a) => a.provider === provider.provider
|
||||
);
|
||||
const isUnlinking = unlinkingProvider === provider.provider;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={provider.provider}
|
||||
className="flex items-center justify-between p-4 border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{Icon && <Icon className="h-6 w-6" />}
|
||||
<div>
|
||||
<p className="font-medium">{providerConfig?.name || provider.name}</p>
|
||||
{isLinked && linkedAccount?.provider_email && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{linkedAccount.provider_email}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{isLinked && (
|
||||
<Badge variant="secondary" className="ml-2">
|
||||
{t('linked')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isLinked ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleUnlink(provider.provider)}
|
||||
disabled={isUnlinking || unlinkMutation.isPending}
|
||||
>
|
||||
{isUnlinking ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Unlink className="h-4 w-4 mr-2" />
|
||||
{t('unlink')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleLink(provider.provider)}
|
||||
disabled={linkMutation.isPending}
|
||||
>
|
||||
{linkMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<LinkIcon className="h-4 w-4 mr-2" />
|
||||
{t('link')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default LinkedAccountsSettings;
|
||||
@@ -5,3 +5,4 @@ export { ProfileSettingsForm } from './ProfileSettingsForm';
|
||||
export { PasswordChangeForm } from './PasswordChangeForm';
|
||||
export { SessionCard } from './SessionCard';
|
||||
export { SessionsManager } from './SessionsManager';
|
||||
export { LinkedAccountsSettings } from './LinkedAccountsSettings';
|
||||
|
||||
@@ -115,6 +115,24 @@ export const config = {
|
||||
enableSessionManagement: parseBool(ENV.ENABLE_SESSION_MANAGEMENT, true),
|
||||
},
|
||||
|
||||
oauth: {
|
||||
// OAuth callback URL (for redirects after OAuth provider auth)
|
||||
callbackPath: '/auth/callback',
|
||||
// Providers configuration (icons and display names)
|
||||
providers: {
|
||||
google: {
|
||||
name: 'Google',
|
||||
icon: 'google',
|
||||
color: '#4285F4',
|
||||
},
|
||||
github: {
|
||||
name: 'GitHub',
|
||||
icon: 'github',
|
||||
color: '#24292F',
|
||||
},
|
||||
} as Record<string, { name: string; icon: string; color: string }>,
|
||||
},
|
||||
|
||||
debug: {
|
||||
api: parseBool(ENV.DEBUG_API, false) && ENV.NODE_ENV === 'development',
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import { type Client, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AdminActivateUserData, AdminActivateUserErrors, AdminActivateUserResponses, AdminAddOrganizationMemberData, AdminAddOrganizationMemberErrors, AdminAddOrganizationMemberResponses, AdminBulkUserActionData, AdminBulkUserActionErrors, AdminBulkUserActionResponses, AdminCreateOrganizationData, AdminCreateOrganizationErrors, AdminCreateOrganizationResponses, AdminCreateUserData, AdminCreateUserErrors, AdminCreateUserResponses, AdminDeactivateUserData, AdminDeactivateUserErrors, AdminDeactivateUserResponses, AdminDeleteOrganizationData, AdminDeleteOrganizationErrors, AdminDeleteOrganizationResponses, AdminDeleteUserData, AdminDeleteUserErrors, AdminDeleteUserResponses, AdminGetOrganizationData, AdminGetOrganizationErrors, AdminGetOrganizationResponses, AdminGetStatsData, AdminGetStatsResponses, AdminGetUserData, AdminGetUserErrors, AdminGetUserResponses, AdminListOrganizationMembersData, AdminListOrganizationMembersErrors, AdminListOrganizationMembersResponses, AdminListOrganizationsData, AdminListOrganizationsErrors, AdminListOrganizationsResponses, AdminListSessionsData, AdminListSessionsErrors, AdminListSessionsResponses, AdminListUsersData, AdminListUsersErrors, AdminListUsersResponses, AdminRemoveOrganizationMemberData, AdminRemoveOrganizationMemberErrors, AdminRemoveOrganizationMemberResponses, AdminUpdateOrganizationData, AdminUpdateOrganizationErrors, AdminUpdateOrganizationResponses, AdminUpdateUserData, AdminUpdateUserErrors, AdminUpdateUserResponses, ChangeCurrentUserPasswordData, ChangeCurrentUserPasswordErrors, ChangeCurrentUserPasswordResponses, CleanupExpiredSessionsData, CleanupExpiredSessionsResponses, ConfirmPasswordResetData, ConfirmPasswordResetErrors, ConfirmPasswordResetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, GetCurrentUserProfileData, GetCurrentUserProfileResponses, GetMyOrganizationsData, GetMyOrganizationsErrors, GetMyOrganizationsResponses, GetOrganizationData, GetOrganizationErrors, GetOrganizationMembersData, GetOrganizationMembersErrors, GetOrganizationMembersResponses, GetOrganizationResponses, GetUserByIdData, GetUserByIdErrors, GetUserByIdResponses, HealthCheckData, HealthCheckResponses, ListMySessionsData, ListMySessionsResponses, ListUsersData, ListUsersErrors, ListUsersResponses, LoginData, LoginErrors, LoginOauthData, LoginOauthErrors, LoginOauthResponses, LoginResponses, LogoutAllData, LogoutAllResponses, LogoutData, LogoutErrors, LogoutResponses, RefreshTokenData, RefreshTokenErrors, RefreshTokenResponses, RegisterData, RegisterErrors, RegisterResponses, RequestPasswordResetData, RequestPasswordResetErrors, RequestPasswordResetResponses, RevokeSessionData, RevokeSessionErrors, RevokeSessionResponses, RootGetData, RootGetResponses, UpdateCurrentUserData, UpdateCurrentUserErrors, UpdateCurrentUserResponses, UpdateOrganizationData, UpdateOrganizationErrors, UpdateOrganizationResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses } from './types.gen';
|
||||
import type { AdminActivateUserData, AdminActivateUserErrors, AdminActivateUserResponses, AdminAddOrganizationMemberData, AdminAddOrganizationMemberErrors, AdminAddOrganizationMemberResponses, AdminBulkUserActionData, AdminBulkUserActionErrors, AdminBulkUserActionResponses, AdminCreateOrganizationData, AdminCreateOrganizationErrors, AdminCreateOrganizationResponses, AdminCreateUserData, AdminCreateUserErrors, AdminCreateUserResponses, AdminDeactivateUserData, AdminDeactivateUserErrors, AdminDeactivateUserResponses, AdminDeleteOrganizationData, AdminDeleteOrganizationErrors, AdminDeleteOrganizationResponses, AdminDeleteUserData, AdminDeleteUserErrors, AdminDeleteUserResponses, AdminGetOrganizationData, AdminGetOrganizationErrors, AdminGetOrganizationResponses, AdminGetStatsData, AdminGetStatsResponses, AdminGetUserData, AdminGetUserErrors, AdminGetUserResponses, AdminListOrganizationMembersData, AdminListOrganizationMembersErrors, AdminListOrganizationMembersResponses, AdminListOrganizationsData, AdminListOrganizationsErrors, AdminListOrganizationsResponses, AdminListSessionsData, AdminListSessionsErrors, AdminListSessionsResponses, AdminListUsersData, AdminListUsersErrors, AdminListUsersResponses, AdminRemoveOrganizationMemberData, AdminRemoveOrganizationMemberErrors, AdminRemoveOrganizationMemberResponses, AdminUpdateOrganizationData, AdminUpdateOrganizationErrors, AdminUpdateOrganizationResponses, AdminUpdateUserData, AdminUpdateUserErrors, AdminUpdateUserResponses, ChangeCurrentUserPasswordData, ChangeCurrentUserPasswordErrors, ChangeCurrentUserPasswordResponses, CleanupExpiredSessionsData, CleanupExpiredSessionsResponses, ConfirmPasswordResetData, ConfirmPasswordResetErrors, ConfirmPasswordResetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, GetCurrentUserProfileData, GetCurrentUserProfileResponses, GetMyOrganizationsData, GetMyOrganizationsErrors, GetMyOrganizationsResponses, GetOauthAuthorizationUrlData, GetOauthAuthorizationUrlErrors, GetOauthAuthorizationUrlResponses, GetOauthServerMetadataData, GetOauthServerMetadataResponses, GetOrganizationData, GetOrganizationErrors, GetOrganizationMembersData, GetOrganizationMembersErrors, GetOrganizationMembersResponses, GetOrganizationResponses, GetUserByIdData, GetUserByIdErrors, GetUserByIdResponses, HandleOauthCallbackData, HandleOauthCallbackErrors, HandleOauthCallbackResponses, HealthCheckData, HealthCheckResponses, ListMySessionsData, ListMySessionsResponses, ListOauthAccountsData, ListOauthAccountsResponses, ListOauthProvidersData, ListOauthProvidersResponses, ListUsersData, ListUsersErrors, ListUsersResponses, LoginData, LoginErrors, LoginOauthData, LoginOauthErrors, LoginOauthResponses, LoginResponses, LogoutAllData, LogoutAllResponses, LogoutData, LogoutErrors, LogoutResponses, OauthProviderAuthorizeData, OauthProviderAuthorizeErrors, OauthProviderAuthorizeResponses, OauthProviderRevokeData, OauthProviderRevokeErrors, OauthProviderRevokeResponses, OauthProviderTokenData, OauthProviderTokenErrors, OauthProviderTokenResponses, RefreshTokenData, RefreshTokenErrors, RefreshTokenResponses, RegisterData, RegisterErrors, RegisterOauthClientData, RegisterOauthClientErrors, RegisterOauthClientResponses, RegisterResponses, RequestPasswordResetData, RequestPasswordResetErrors, RequestPasswordResetResponses, RevokeSessionData, RevokeSessionErrors, RevokeSessionResponses, RootGetData, RootGetResponses, StartOauthLinkData, StartOauthLinkErrors, StartOauthLinkResponses, UnlinkOauthAccountData, UnlinkOauthAccountErrors, UnlinkOauthAccountResponses, UpdateCurrentUserData, UpdateCurrentUserErrors, UpdateCurrentUserResponses, UpdateOrganizationData, UpdateOrganizationErrors, UpdateOrganizationResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = Options2<TData, ThrowOnError> & {
|
||||
/**
|
||||
@@ -224,6 +224,240 @@ export const logoutAll = <ThrowOnError extends boolean = false>(options?: Option
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* List OAuth Providers
|
||||
*
|
||||
* Get list of enabled OAuth providers for the login/register UI.
|
||||
*
|
||||
* Returns:
|
||||
* List of enabled providers with display info.
|
||||
*/
|
||||
export const listOauthProviders = <ThrowOnError extends boolean = false>(options?: Options<ListOauthProvidersData, ThrowOnError>) => {
|
||||
return (options?.client ?? client).get<ListOauthProvidersResponses, unknown, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/providers',
|
||||
...options
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Get OAuth Authorization URL
|
||||
*
|
||||
* Get the authorization URL to redirect the user to the OAuth provider.
|
||||
*
|
||||
* The frontend should redirect the user to the returned URL.
|
||||
* After authentication, the provider will redirect back to the callback URL.
|
||||
*
|
||||
* **Rate Limit**: 10 requests/minute
|
||||
*/
|
||||
export const getOauthAuthorizationUrl = <ThrowOnError extends boolean = false>(options: Options<GetOauthAuthorizationUrlData, ThrowOnError>) => {
|
||||
return (options.client ?? client).get<GetOauthAuthorizationUrlResponses, GetOauthAuthorizationUrlErrors, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/authorize/{provider}',
|
||||
...options
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuth Callback
|
||||
*
|
||||
* Handle OAuth callback from provider.
|
||||
*
|
||||
* The frontend should call this endpoint with the code and state
|
||||
* parameters received from the OAuth provider redirect.
|
||||
*
|
||||
* Returns:
|
||||
* JWT tokens for the authenticated user.
|
||||
*
|
||||
* **Rate Limit**: 10 requests/minute
|
||||
*/
|
||||
export const handleOauthCallback = <ThrowOnError extends boolean = false>(options: Options<HandleOauthCallbackData, ThrowOnError>) => {
|
||||
return (options.client ?? client).post<HandleOauthCallbackResponses, HandleOauthCallbackErrors, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/callback/{provider}',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* List Linked OAuth Accounts
|
||||
*
|
||||
* Get list of OAuth accounts linked to the current user.
|
||||
*
|
||||
* Requires authentication.
|
||||
*/
|
||||
export const listOauthAccounts = <ThrowOnError extends boolean = false>(options?: Options<ListOauthAccountsData, ThrowOnError>) => {
|
||||
return (options?.client ?? client).get<ListOauthAccountsResponses, unknown, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
security: [
|
||||
{
|
||||
scheme: 'bearer',
|
||||
type: 'http'
|
||||
}
|
||||
],
|
||||
url: '/api/v1/oauth/accounts',
|
||||
...options
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Unlink OAuth Account
|
||||
*
|
||||
* Unlink an OAuth provider from the current user.
|
||||
*
|
||||
* The user must have either a password set or another OAuth provider
|
||||
* linked to ensure they can still log in.
|
||||
*
|
||||
* **Rate Limit**: 5 requests/minute
|
||||
*/
|
||||
export const unlinkOauthAccount = <ThrowOnError extends boolean = false>(options: Options<UnlinkOauthAccountData, ThrowOnError>) => {
|
||||
return (options.client ?? client).delete<UnlinkOauthAccountResponses, UnlinkOauthAccountErrors, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
security: [
|
||||
{
|
||||
scheme: 'bearer',
|
||||
type: 'http'
|
||||
}
|
||||
],
|
||||
url: '/api/v1/oauth/accounts/{provider}',
|
||||
...options
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Start Account Linking
|
||||
*
|
||||
* Start the OAuth flow to link a new provider to the current user.
|
||||
*
|
||||
* This is a convenience endpoint that redirects to /authorize/{provider}
|
||||
* with the current user context.
|
||||
*
|
||||
* **Rate Limit**: 10 requests/minute
|
||||
*/
|
||||
export const startOauthLink = <ThrowOnError extends boolean = false>(options: Options<StartOauthLinkData, ThrowOnError>) => {
|
||||
return (options.client ?? client).post<StartOauthLinkResponses, StartOauthLinkErrors, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
security: [
|
||||
{
|
||||
scheme: 'bearer',
|
||||
type: 'http'
|
||||
}
|
||||
],
|
||||
url: '/api/v1/oauth/link/{provider}',
|
||||
...options
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuth Server Metadata
|
||||
*
|
||||
* OAuth 2.0 Authorization Server Metadata (RFC 8414).
|
||||
*
|
||||
* Returns server metadata including supported endpoints, scopes,
|
||||
* and capabilities for MCP clients.
|
||||
*/
|
||||
export const getOauthServerMetadata = <ThrowOnError extends boolean = false>(options?: Options<GetOauthServerMetadataData, ThrowOnError>) => {
|
||||
return (options?.client ?? client).get<GetOauthServerMetadataResponses, unknown, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/.well-known/oauth-authorization-server',
|
||||
...options
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Authorization Endpoint (Skeleton)
|
||||
*
|
||||
* OAuth 2.0 Authorization Endpoint.
|
||||
*
|
||||
* **NOTE**: This is a skeleton implementation. In a full implementation,
|
||||
* this would:
|
||||
* 1. Validate client_id and redirect_uri
|
||||
* 2. Display consent screen to user
|
||||
* 3. Generate authorization code
|
||||
* 4. Redirect back to client with code
|
||||
*
|
||||
* Currently returns a 501 Not Implemented response.
|
||||
*/
|
||||
export const oauthProviderAuthorize = <ThrowOnError extends boolean = false>(options: Options<OauthProviderAuthorizeData, ThrowOnError>) => {
|
||||
return (options.client ?? client).get<OauthProviderAuthorizeResponses, OauthProviderAuthorizeErrors, ThrowOnError>({
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/provider/authorize',
|
||||
...options
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Token Endpoint (Skeleton)
|
||||
*
|
||||
* OAuth 2.0 Token Endpoint.
|
||||
*
|
||||
* **NOTE**: This is a skeleton implementation. In a full implementation,
|
||||
* this would exchange authorization codes for access tokens.
|
||||
*
|
||||
* Currently returns a 501 Not Implemented response.
|
||||
*/
|
||||
export const oauthProviderToken = <ThrowOnError extends boolean = false>(options: Options<OauthProviderTokenData, ThrowOnError>) => {
|
||||
return (options.client ?? client).post<OauthProviderTokenResponses, OauthProviderTokenErrors, ThrowOnError>({
|
||||
...urlSearchParamsBodySerializer,
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/provider/token',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Token Revocation Endpoint (Skeleton)
|
||||
*
|
||||
* OAuth 2.0 Token Revocation Endpoint (RFC 7009).
|
||||
*
|
||||
* **NOTE**: This is a skeleton implementation.
|
||||
*
|
||||
* Currently returns a 501 Not Implemented response.
|
||||
*/
|
||||
export const oauthProviderRevoke = <ThrowOnError extends boolean = false>(options: Options<OauthProviderRevokeData, ThrowOnError>) => {
|
||||
return (options.client ?? client).post<OauthProviderRevokeResponses, OauthProviderRevokeErrors, ThrowOnError>({
|
||||
...urlSearchParamsBodySerializer,
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/provider/revoke',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Register OAuth Client (Admin)
|
||||
*
|
||||
* Register a new OAuth client (admin only).
|
||||
*
|
||||
* This endpoint allows creating MCP clients that can authenticate
|
||||
* against this API.
|
||||
*
|
||||
* **NOTE**: This is a minimal implementation.
|
||||
*/
|
||||
export const registerOauthClient = <ThrowOnError extends boolean = false>(options: Options<RegisterOauthClientData, ThrowOnError>) => {
|
||||
return (options.client ?? client).post<RegisterOauthClientResponses, RegisterOauthClientErrors, ThrowOnError>({
|
||||
...urlSearchParamsBodySerializer,
|
||||
responseType: 'json',
|
||||
url: '/api/v1/oauth/provider/clients',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* List Users
|
||||
*
|
||||
|
||||
@@ -145,6 +145,108 @@ export type BodyLoginOauth = {
|
||||
client_secret?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Body_oauth_provider_revoke
|
||||
*/
|
||||
export type BodyOauthProviderRevoke = {
|
||||
/**
|
||||
* Token
|
||||
*
|
||||
* Token to revoke
|
||||
*/
|
||||
token: string;
|
||||
/**
|
||||
* Token Type Hint
|
||||
*
|
||||
* Token type hint (access_token, refresh_token)
|
||||
*/
|
||||
token_type_hint?: string | null;
|
||||
/**
|
||||
* Client Id
|
||||
*
|
||||
* Client ID
|
||||
*/
|
||||
client_id?: string | null;
|
||||
/**
|
||||
* Client Secret
|
||||
*
|
||||
* Client secret
|
||||
*/
|
||||
client_secret?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Body_oauth_provider_token
|
||||
*/
|
||||
export type BodyOauthProviderToken = {
|
||||
/**
|
||||
* Grant Type
|
||||
*
|
||||
* Grant type (authorization_code)
|
||||
*/
|
||||
grant_type: string;
|
||||
/**
|
||||
* Code
|
||||
*
|
||||
* Authorization code
|
||||
*/
|
||||
code?: string | null;
|
||||
/**
|
||||
* Redirect Uri
|
||||
*
|
||||
* Redirect URI
|
||||
*/
|
||||
redirect_uri?: string | null;
|
||||
/**
|
||||
* Client Id
|
||||
*
|
||||
* Client ID
|
||||
*/
|
||||
client_id?: string | null;
|
||||
/**
|
||||
* Client Secret
|
||||
*
|
||||
* Client secret
|
||||
*/
|
||||
client_secret?: string | null;
|
||||
/**
|
||||
* Code Verifier
|
||||
*
|
||||
* PKCE code verifier
|
||||
*/
|
||||
code_verifier?: string | null;
|
||||
/**
|
||||
* Refresh Token
|
||||
*
|
||||
* Refresh token
|
||||
*/
|
||||
refresh_token?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Body_register_oauth_client
|
||||
*/
|
||||
export type BodyRegisterOauthClient = {
|
||||
/**
|
||||
* Client Name
|
||||
*
|
||||
* Client application name
|
||||
*/
|
||||
client_name: string;
|
||||
/**
|
||||
* Redirect Uris
|
||||
*
|
||||
* Comma-separated list of redirect URIs
|
||||
*/
|
||||
redirect_uris: string;
|
||||
/**
|
||||
* Client Type
|
||||
*
|
||||
* public or confidential
|
||||
*/
|
||||
client_type?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* BulkAction
|
||||
*
|
||||
@@ -256,6 +358,230 @@ export type MessageResponse = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthAccountResponse
|
||||
*
|
||||
* Schema for OAuth account response to clients.
|
||||
*/
|
||||
export type OAuthAccountResponse = {
|
||||
/**
|
||||
* Provider
|
||||
*
|
||||
* OAuth provider name
|
||||
*/
|
||||
provider: string;
|
||||
/**
|
||||
* Provider Email
|
||||
*
|
||||
* Email from OAuth provider
|
||||
*/
|
||||
provider_email?: string | null;
|
||||
/**
|
||||
* Id
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* Created At
|
||||
*/
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthAccountsListResponse
|
||||
*
|
||||
* Response containing list of linked OAuth accounts.
|
||||
*/
|
||||
export type OAuthAccountsListResponse = {
|
||||
/**
|
||||
* Accounts
|
||||
*/
|
||||
accounts: Array<OAuthAccountResponse>;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthCallbackRequest
|
||||
*
|
||||
* Request parameters for OAuth callback.
|
||||
*/
|
||||
export type OAuthCallbackRequest = {
|
||||
/**
|
||||
* Code
|
||||
*
|
||||
* Authorization code from provider
|
||||
*/
|
||||
code: string;
|
||||
/**
|
||||
* State
|
||||
*
|
||||
* State parameter for CSRF protection
|
||||
*/
|
||||
state: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthCallbackResponse
|
||||
*
|
||||
* Response after successful OAuth authentication.
|
||||
*/
|
||||
export type OAuthCallbackResponse = {
|
||||
/**
|
||||
* Access Token
|
||||
*
|
||||
* JWT access token
|
||||
*/
|
||||
access_token: string;
|
||||
/**
|
||||
* Refresh Token
|
||||
*
|
||||
* JWT refresh token
|
||||
*/
|
||||
refresh_token: string;
|
||||
/**
|
||||
* Token Type
|
||||
*/
|
||||
token_type?: string;
|
||||
/**
|
||||
* Expires In
|
||||
*
|
||||
* Token expiration in seconds
|
||||
*/
|
||||
expires_in: number;
|
||||
/**
|
||||
* Is New User
|
||||
*
|
||||
* Whether a new user was created
|
||||
*/
|
||||
is_new_user?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthProviderInfo
|
||||
*
|
||||
* Information about an available OAuth provider.
|
||||
*/
|
||||
export type OAuthProviderInfo = {
|
||||
/**
|
||||
* Provider
|
||||
*
|
||||
* Provider identifier (google, github)
|
||||
*/
|
||||
provider: string;
|
||||
/**
|
||||
* Name
|
||||
*
|
||||
* Human-readable provider name
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Icon
|
||||
*
|
||||
* Icon identifier for frontend
|
||||
*/
|
||||
icon?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthProvidersResponse
|
||||
*
|
||||
* Response containing list of enabled OAuth providers.
|
||||
*/
|
||||
export type OAuthProvidersResponse = {
|
||||
/**
|
||||
* Enabled
|
||||
*
|
||||
* Whether OAuth is globally enabled
|
||||
*/
|
||||
enabled: boolean;
|
||||
/**
|
||||
* Providers
|
||||
*
|
||||
* List of enabled providers
|
||||
*/
|
||||
providers?: Array<OAuthProviderInfo>;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthServerMetadata
|
||||
*
|
||||
* OAuth 2.0 Authorization Server Metadata (RFC 8414).
|
||||
*/
|
||||
export type OAuthServerMetadata = {
|
||||
/**
|
||||
* Issuer
|
||||
*
|
||||
* Authorization server issuer URL
|
||||
*/
|
||||
issuer: string;
|
||||
/**
|
||||
* Authorization Endpoint
|
||||
*
|
||||
* Authorization endpoint URL
|
||||
*/
|
||||
authorization_endpoint: string;
|
||||
/**
|
||||
* Token Endpoint
|
||||
*
|
||||
* Token endpoint URL
|
||||
*/
|
||||
token_endpoint: string;
|
||||
/**
|
||||
* Registration Endpoint
|
||||
*
|
||||
* Dynamic client registration endpoint
|
||||
*/
|
||||
registration_endpoint?: string | null;
|
||||
/**
|
||||
* Revocation Endpoint
|
||||
*
|
||||
* Token revocation endpoint
|
||||
*/
|
||||
revocation_endpoint?: string | null;
|
||||
/**
|
||||
* Scopes Supported
|
||||
*
|
||||
* Supported scopes
|
||||
*/
|
||||
scopes_supported?: Array<string>;
|
||||
/**
|
||||
* Response Types Supported
|
||||
*
|
||||
* Supported response types
|
||||
*/
|
||||
response_types_supported?: Array<string>;
|
||||
/**
|
||||
* Grant Types Supported
|
||||
*
|
||||
* Supported grant types
|
||||
*/
|
||||
grant_types_supported?: Array<string>;
|
||||
/**
|
||||
* Code Challenge Methods Supported
|
||||
*
|
||||
* Supported PKCE methods
|
||||
*/
|
||||
code_challenge_methods_supported?: Array<string>;
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuthUnlinkResponse
|
||||
*
|
||||
* Response after unlinking an OAuth account.
|
||||
*/
|
||||
export type OAuthUnlinkResponse = {
|
||||
/**
|
||||
* Success
|
||||
*
|
||||
* Whether the unlink was successful
|
||||
*/
|
||||
success: boolean;
|
||||
/**
|
||||
* Message
|
||||
*
|
||||
* Status message
|
||||
*/
|
||||
message: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* OrgDistributionData
|
||||
*/
|
||||
@@ -1097,6 +1423,352 @@ export type LogoutAllResponses = {
|
||||
|
||||
export type LogoutAllResponse = LogoutAllResponses[keyof LogoutAllResponses];
|
||||
|
||||
export type ListOauthProvidersData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/api/v1/oauth/providers';
|
||||
};
|
||||
|
||||
export type ListOauthProvidersResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: OAuthProvidersResponse;
|
||||
};
|
||||
|
||||
export type ListOauthProvidersResponse = ListOauthProvidersResponses[keyof ListOauthProvidersResponses];
|
||||
|
||||
export type GetOauthAuthorizationUrlData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* Provider
|
||||
*/
|
||||
provider: string;
|
||||
};
|
||||
query: {
|
||||
/**
|
||||
* Redirect Uri
|
||||
*
|
||||
* Frontend callback URL after OAuth completes
|
||||
*/
|
||||
redirect_uri: string;
|
||||
};
|
||||
url: '/api/v1/oauth/authorize/{provider}';
|
||||
};
|
||||
|
||||
export type GetOauthAuthorizationUrlErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type GetOauthAuthorizationUrlError = GetOauthAuthorizationUrlErrors[keyof GetOauthAuthorizationUrlErrors];
|
||||
|
||||
export type GetOauthAuthorizationUrlResponses = {
|
||||
/**
|
||||
* Response Get Oauth Authorization Url
|
||||
*
|
||||
* Successful Response
|
||||
*/
|
||||
200: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
export type GetOauthAuthorizationUrlResponse = GetOauthAuthorizationUrlResponses[keyof GetOauthAuthorizationUrlResponses];
|
||||
|
||||
export type HandleOauthCallbackData = {
|
||||
body: OAuthCallbackRequest;
|
||||
path: {
|
||||
/**
|
||||
* Provider
|
||||
*/
|
||||
provider: string;
|
||||
};
|
||||
query: {
|
||||
/**
|
||||
* Redirect Uri
|
||||
*
|
||||
* Must match the redirect_uri used in authorization
|
||||
*/
|
||||
redirect_uri: string;
|
||||
};
|
||||
url: '/api/v1/oauth/callback/{provider}';
|
||||
};
|
||||
|
||||
export type HandleOauthCallbackErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type HandleOauthCallbackError = HandleOauthCallbackErrors[keyof HandleOauthCallbackErrors];
|
||||
|
||||
export type HandleOauthCallbackResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: OAuthCallbackResponse;
|
||||
};
|
||||
|
||||
export type HandleOauthCallbackResponse = HandleOauthCallbackResponses[keyof HandleOauthCallbackResponses];
|
||||
|
||||
export type ListOauthAccountsData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/api/v1/oauth/accounts';
|
||||
};
|
||||
|
||||
export type ListOauthAccountsResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: OAuthAccountsListResponse;
|
||||
};
|
||||
|
||||
export type ListOauthAccountsResponse = ListOauthAccountsResponses[keyof ListOauthAccountsResponses];
|
||||
|
||||
export type UnlinkOauthAccountData = {
|
||||
body?: never;
|
||||
path: {
|
||||
/**
|
||||
* Provider
|
||||
*/
|
||||
provider: string;
|
||||
};
|
||||
query?: never;
|
||||
url: '/api/v1/oauth/accounts/{provider}';
|
||||
};
|
||||
|
||||
export type UnlinkOauthAccountErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type UnlinkOauthAccountError = UnlinkOauthAccountErrors[keyof UnlinkOauthAccountErrors];
|
||||
|
||||
export type UnlinkOauthAccountResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: OAuthUnlinkResponse;
|
||||
};
|
||||
|
||||
export type UnlinkOauthAccountResponse = UnlinkOauthAccountResponses[keyof UnlinkOauthAccountResponses];
|
||||
|
||||
export type StartOauthLinkData = {
|
||||
body?: never;
|
||||
path: {
|
||||
/**
|
||||
* Provider
|
||||
*/
|
||||
provider: string;
|
||||
};
|
||||
query: {
|
||||
/**
|
||||
* Redirect Uri
|
||||
*
|
||||
* Frontend callback URL after OAuth completes
|
||||
*/
|
||||
redirect_uri: string;
|
||||
};
|
||||
url: '/api/v1/oauth/link/{provider}';
|
||||
};
|
||||
|
||||
export type StartOauthLinkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type StartOauthLinkError = StartOauthLinkErrors[keyof StartOauthLinkErrors];
|
||||
|
||||
export type StartOauthLinkResponses = {
|
||||
/**
|
||||
* Response Start Oauth Link
|
||||
*
|
||||
* Successful Response
|
||||
*/
|
||||
200: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
export type StartOauthLinkResponse = StartOauthLinkResponses[keyof StartOauthLinkResponses];
|
||||
|
||||
export type GetOauthServerMetadataData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/api/v1/oauth/.well-known/oauth-authorization-server';
|
||||
};
|
||||
|
||||
export type GetOauthServerMetadataResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: OAuthServerMetadata;
|
||||
};
|
||||
|
||||
export type GetOauthServerMetadataResponse = GetOauthServerMetadataResponses[keyof GetOauthServerMetadataResponses];
|
||||
|
||||
export type OauthProviderAuthorizeData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
query: {
|
||||
/**
|
||||
* Response Type
|
||||
*
|
||||
* Must be 'code'
|
||||
*/
|
||||
response_type: string;
|
||||
/**
|
||||
* Client Id
|
||||
*
|
||||
* OAuth client ID
|
||||
*/
|
||||
client_id: string;
|
||||
/**
|
||||
* Redirect Uri
|
||||
*
|
||||
* Redirect URI
|
||||
*/
|
||||
redirect_uri: string;
|
||||
/**
|
||||
* Scope
|
||||
*
|
||||
* Requested scopes
|
||||
*/
|
||||
scope?: string;
|
||||
/**
|
||||
* State
|
||||
*
|
||||
* CSRF state parameter
|
||||
*/
|
||||
state?: string;
|
||||
/**
|
||||
* Code Challenge
|
||||
*
|
||||
* PKCE code challenge
|
||||
*/
|
||||
code_challenge?: string | null;
|
||||
/**
|
||||
* Code Challenge Method
|
||||
*
|
||||
* PKCE method (S256)
|
||||
*/
|
||||
code_challenge_method?: string | null;
|
||||
};
|
||||
url: '/api/v1/oauth/provider/authorize';
|
||||
};
|
||||
|
||||
export type OauthProviderAuthorizeErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type OauthProviderAuthorizeError = OauthProviderAuthorizeErrors[keyof OauthProviderAuthorizeErrors];
|
||||
|
||||
export type OauthProviderAuthorizeResponses = {
|
||||
/**
|
||||
* Response Oauth Provider Authorize
|
||||
*
|
||||
* Successful Response
|
||||
*/
|
||||
200: unknown;
|
||||
};
|
||||
|
||||
export type OauthProviderTokenData = {
|
||||
body: BodyOauthProviderToken;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/api/v1/oauth/provider/token';
|
||||
};
|
||||
|
||||
export type OauthProviderTokenErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type OauthProviderTokenError = OauthProviderTokenErrors[keyof OauthProviderTokenErrors];
|
||||
|
||||
export type OauthProviderTokenResponses = {
|
||||
/**
|
||||
* Response Oauth Provider Token
|
||||
*
|
||||
* Successful Response
|
||||
*/
|
||||
200: unknown;
|
||||
};
|
||||
|
||||
export type OauthProviderRevokeData = {
|
||||
body: BodyOauthProviderRevoke;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/api/v1/oauth/provider/revoke';
|
||||
};
|
||||
|
||||
export type OauthProviderRevokeErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type OauthProviderRevokeError = OauthProviderRevokeErrors[keyof OauthProviderRevokeErrors];
|
||||
|
||||
export type OauthProviderRevokeResponses = {
|
||||
/**
|
||||
* Response Oauth Provider Revoke
|
||||
*
|
||||
* Successful Response
|
||||
*/
|
||||
200: unknown;
|
||||
};
|
||||
|
||||
export type RegisterOauthClientData = {
|
||||
body: BodyRegisterOauthClient;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/api/v1/oauth/provider/clients';
|
||||
};
|
||||
|
||||
export type RegisterOauthClientErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type RegisterOauthClientError = RegisterOauthClientErrors[keyof RegisterOauthClientErrors];
|
||||
|
||||
export type RegisterOauthClientResponses = {
|
||||
/**
|
||||
* Response Register Oauth Client
|
||||
*
|
||||
* Successful Response
|
||||
*/
|
||||
200: unknown;
|
||||
};
|
||||
|
||||
export type ListUsersData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
|
||||
235
frontend/src/lib/api/hooks/useOAuth.ts
Normal file
235
frontend/src/lib/api/hooks/useOAuth.ts
Normal file
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* OAuth React Query Hooks
|
||||
* Provides hooks for OAuth authentication flows
|
||||
*/
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
listOauthProviders,
|
||||
getOauthAuthorizationUrl,
|
||||
handleOauthCallback,
|
||||
listOauthAccounts,
|
||||
unlinkOauthAccount,
|
||||
startOauthLink,
|
||||
getCurrentUserProfile,
|
||||
} from '@/lib/api/generated';
|
||||
import type {
|
||||
OAuthProvidersResponse,
|
||||
OAuthAccountsListResponse,
|
||||
OAuthCallbackResponse,
|
||||
UserResponse,
|
||||
} from '@/lib/api/generated';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import config from '@/config/app.config';
|
||||
|
||||
// ============================================================================
|
||||
// Query Keys
|
||||
// ============================================================================
|
||||
|
||||
export const oauthKeys = {
|
||||
all: ['oauth'] as const,
|
||||
providers: () => [...oauthKeys.all, 'providers'] as const,
|
||||
accounts: () => [...oauthKeys.all, 'accounts'] as const,
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Provider Queries
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Fetch available OAuth providers
|
||||
* Returns which providers are enabled for login/registration
|
||||
*/
|
||||
export function useOAuthProviders() {
|
||||
return useQuery({
|
||||
queryKey: oauthKeys.providers(),
|
||||
queryFn: async () => {
|
||||
const response = await listOauthProviders();
|
||||
return response.data as OAuthProvidersResponse;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // Providers don't change often
|
||||
gcTime: 30 * 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// OAuth Flow Mutations
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Start OAuth login/registration flow
|
||||
* Redirects user to the OAuth provider
|
||||
*/
|
||||
export function useOAuthStart() {
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
provider,
|
||||
mode,
|
||||
}: {
|
||||
provider: string;
|
||||
mode: 'login' | 'register' | 'link';
|
||||
}) => {
|
||||
const redirectUri = `${config.app.url}${config.oauth.callbackPath}/${provider}`;
|
||||
|
||||
const response = await getOauthAuthorizationUrl({
|
||||
path: { provider },
|
||||
query: { redirect_uri: redirectUri },
|
||||
});
|
||||
|
||||
if (response.data) {
|
||||
// Store mode in sessionStorage for callback handling
|
||||
sessionStorage.setItem('oauth_mode', mode);
|
||||
sessionStorage.setItem('oauth_provider', provider);
|
||||
|
||||
// Response is { [key: string]: unknown }, so cast authorization_url
|
||||
const authUrl = (response.data as { authorization_url: string }).authorization_url;
|
||||
// Redirect to OAuth provider
|
||||
window.location.href = authUrl;
|
||||
}
|
||||
|
||||
return response.data;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle OAuth callback after provider redirect
|
||||
* Exchanges the code for tokens and logs the user in
|
||||
*/
|
||||
export function useOAuthCallback() {
|
||||
const { setAuth } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
provider,
|
||||
code,
|
||||
state,
|
||||
}: {
|
||||
provider: string;
|
||||
code: string;
|
||||
state: string;
|
||||
}) => {
|
||||
const redirectUri = `${config.app.url}${config.oauth.callbackPath}/${provider}`;
|
||||
|
||||
// Exchange code for tokens
|
||||
const response = await handleOauthCallback({
|
||||
path: { provider },
|
||||
query: { redirect_uri: redirectUri },
|
||||
body: {
|
||||
code,
|
||||
state,
|
||||
},
|
||||
});
|
||||
|
||||
const tokenData = response.data as OAuthCallbackResponse;
|
||||
|
||||
// Fetch user profile using the new access token
|
||||
// We need to make this request with the new token
|
||||
const userResponse = await getCurrentUserProfile({
|
||||
headers: {
|
||||
authorization: `Bearer ${tokenData.access_token}`,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
tokens: tokenData,
|
||||
user: userResponse.data as UserResponse,
|
||||
};
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data?.tokens && data?.user) {
|
||||
// Set auth state with tokens and user from OAuth
|
||||
setAuth(
|
||||
data.user,
|
||||
data.tokens.access_token,
|
||||
data.tokens.refresh_token,
|
||||
data.tokens.expires_in
|
||||
);
|
||||
|
||||
// Invalidate relevant queries
|
||||
queryClient.invalidateQueries({ queryKey: ['user'] });
|
||||
}
|
||||
|
||||
// Clean up session storage
|
||||
sessionStorage.removeItem('oauth_mode');
|
||||
sessionStorage.removeItem('oauth_provider');
|
||||
},
|
||||
onError: () => {
|
||||
// Clean up session storage on error too
|
||||
sessionStorage.removeItem('oauth_mode');
|
||||
sessionStorage.removeItem('oauth_provider');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Account Management
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Fetch linked OAuth accounts for the current user
|
||||
*/
|
||||
export function useOAuthAccounts() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
|
||||
return useQuery({
|
||||
queryKey: oauthKeys.accounts(),
|
||||
queryFn: async () => {
|
||||
const response = await listOauthAccounts();
|
||||
return response.data as OAuthAccountsListResponse;
|
||||
},
|
||||
enabled: isAuthenticated,
|
||||
staleTime: 60 * 1000, // 1 minute
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Start OAuth account linking flow
|
||||
* For users who want to add another OAuth provider to their account
|
||||
*/
|
||||
export function useOAuthLink() {
|
||||
return useMutation({
|
||||
mutationFn: async ({ provider }: { provider: string }) => {
|
||||
const redirectUri = `${config.app.url}${config.oauth.callbackPath}/${provider}`;
|
||||
|
||||
const response = await startOauthLink({
|
||||
path: { provider },
|
||||
query: { redirect_uri: redirectUri },
|
||||
});
|
||||
|
||||
if (response.data) {
|
||||
// Store mode in sessionStorage for callback handling
|
||||
sessionStorage.setItem('oauth_mode', 'link');
|
||||
sessionStorage.setItem('oauth_provider', provider);
|
||||
|
||||
// Response is { [key: string]: unknown }, so cast authorization_url
|
||||
const authUrl = (response.data as { authorization_url: string }).authorization_url;
|
||||
// Redirect to OAuth provider
|
||||
window.location.href = authUrl;
|
||||
}
|
||||
|
||||
return response.data;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlink an OAuth account from the current user
|
||||
*/
|
||||
export function useOAuthUnlink() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ provider }: { provider: string }) => {
|
||||
const response = await unlinkOauthAccount({
|
||||
path: { provider },
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Invalidate accounts query to refresh the list
|
||||
queryClient.invalidateQueries({ queryKey: oauthKeys.accounts() });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* For custom handler behavior, use src/mocks/handlers/overrides.ts
|
||||
*
|
||||
* Generated: 2025-11-24T17:58:16.943Z
|
||||
* Generated: 2025-11-25T00:22:46.981Z
|
||||
*/
|
||||
|
||||
import { http, HttpResponse, delay } from 'msw';
|
||||
@@ -93,7 +93,6 @@ export const generatedHandlers = [
|
||||
refresh_token: refreshToken,
|
||||
token_type: 'bearer',
|
||||
expires_in: 900,
|
||||
user: user,
|
||||
});
|
||||
}),
|
||||
|
||||
|
||||
Reference in New Issue
Block a user