can link google accounts!

This commit is contained in:
2026-01-20 15:54:11 +10:30
parent 87c143a332
commit e7c2c873c2
10 changed files with 1682 additions and 102 deletions
+2
View File
@@ -18,6 +18,7 @@ import ResetPasswordPage from "@/pages/auth/ResetPasswordPage";
import InviteAcceptPage from "@/pages/auth/InviteAcceptPage";
import OIDCConsentPage from "@/pages/auth/OIDCConsentPage";
import OIDCErrorPage from "@/pages/auth/OIDCErrorPage";
import OAuthCallbackPage from "@/pages/auth/OAuthCallbackPage";
// User pages
import ProfilePage from "@/pages/user/ProfilePage";
@@ -83,6 +84,7 @@ function AppRoutes() {
<Route path="/invite" element={<InviteAcceptPage />} />
<Route path="/consent" element={<OIDCConsentPage />} />
<Route path="/error" element={<OIDCErrorPage />} />
<Route path="/oauth/callback" element={<OAuthCallbackPage />} />
</Route>
{/* Protected routes - handles auth and MFA enforcement */}
+148
View File
@@ -131,6 +131,62 @@ export interface WebAuthnLoginCompleteResponse {
expires_at: string;
}
export interface ExternalProviderListResponse {
providers: ExternalProvider[];
}
export interface LinkedAccountsResponse {
linked_accounts: LinkedAccount[];
unlink_available: boolean;
}
export interface ExternalProvider {
id: ExternalProviderId;
name: string;
is_active: boolean;
scopes: string[];
}
export interface ExternalProviderConfig {
client_id?: string;
client_secret?: string;
auth_url: string;
token_url: string;
userinfo_url: string;
scopes: string[];
redirect_uris: string[];
is_active: boolean;
settings?: Record<string, unknown>;
}
export interface LinkedAccount {
id: string;
provider_type: ExternalProviderId;
name: string;
email: string;
picture?: string;
provider_user_id?: string;
linked_at: string;
last_used_at?: string;
verified?: boolean;
}
export interface OAuthAuthorizeResponse {
authorization_url: string;
state: string;
}
export interface OAuthCallbackResponse {
success: boolean;
token?: string;
user?: User;
expires_in?: number;
requires_mfa?: boolean;
mfa_token?: string;
error?: string;
error_type?: string;
}
class ApiError extends Error {
code: number;
type: string;
@@ -384,6 +440,21 @@ export const api = {
return response;
},
// Verify TOTP code with an mfa_token (used after OAuth callback when MFA is required)
verifyWithMfaToken: async (code: string, mfaToken: string, isBackupCode = false): Promise<TotpVerifyResponse> => {
const response = await request<TotpVerifyResponse>('/auth/totp/verify', {
method: 'POST',
body: JSON.stringify({ code, mfa_token: mfaToken, is_backup_code: isBackupCode }),
credentials: 'include',
}, false);
if (response.token) {
tokenManager.setToken(response.token, response.expires_at ?? null);
}
return response;
},
// Get TOTP status
status: () =>
request<TotpStatusResponse>('/auth/totp/status'),
@@ -531,6 +602,83 @@ export const api = {
getMyCompliance: () =>
request<MfaComplianceSummary>('/users/me/mfa-compliance'),
},
externalAuth: {
// Provider management (admin)
listProviders: () =>
request<ExternalProviderListResponse>('/auth/external/providers'),
getProviderConfig: (provider: ExternalProviderId) =>
request<ExternalProviderConfig | null>(`/auth/external/providers/${provider}/config`),
updateProviderConfig: (provider: ExternalProviderId, config: Partial<ExternalProviderConfig>) =>
request<void>(`/auth/external/providers/${provider}/config`, {
method: 'POST',
body: JSON.stringify(config),
credentials: 'include',
}),
deleteProviderConfig: (provider: ExternalProviderId) =>
request<void>(`/auth/external/providers/${provider}/config`, {
method: 'DELETE',
credentials: 'include',
}),
// User account management
listLinkedAccounts: () =>
request<LinkedAccountsResponse>('/auth/external/linked-accounts'),
unlinkAccount: (provider: ExternalProviderId) =>
request<void>(`/auth/external/${provider}/unlink`, {
method: 'DELETE',
credentials: 'include',
}),
// OAuth flow initiation
initiateLogin: (provider: ExternalProviderId, state: string) => {
const params = new URLSearchParams({ state });
return request<OAuthAuthorizeResponse>(
`/auth/external/${provider}/authorize?${params.toString()}`,
{
method: 'GET',
credentials: 'include',
},
false
);
},
initiateRegister: (provider: ExternalProviderId, state: string) => {
const params = new URLSearchParams({ state });
return request<OAuthAuthorizeResponse>(
`/auth/external/${provider}/authorize?${params.toString()}`,
{
method: 'GET',
credentials: 'include',
},
false
);
},
initiateLink: (provider: ExternalProviderId, state: string) =>
request<OAuthAuthorizeResponse>(`/auth/external/${provider}/link`, {
method: 'POST',
body: JSON.stringify({ state }),
credentials: 'include',
}),
// OAuth callback (called after redirect from provider)
handleCallback: (provider: ExternalProviderId, code: string, state: string) => {
const params = new URLSearchParams({ code, state });
return request<OAuthCallbackResponse>(
`/auth/external/${provider}/callback?${params.toString()}`,
{
method: 'GET',
credentials: 'include',
},
false
);
},
},
};
// Policy types
+42
View File
@@ -0,0 +1,42 @@
/**
* Encoding utilities for OAuth and cryptographic operations.
*/
/**
* Encodes a Uint8Array to a base64url-encoded string without padding.
* This encoding is URL-safe and commonly used in OAuth and JWT operations.
*
* @param data - The byte array to encode
* @returns A base64url-encoded string
*/
export function base64UrlEncode(data: Uint8Array): string {
const base64 = btoa(String.fromCharCode(...data));
// Replace URL-unsafe characters to make it base64url
return base64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, ''); // Remove padding
}
/**
* Decodes a base64url-encoded string to a Uint8Array.
*
* @param base64Url - The base64url-encoded string
* @returns The decoded byte array
*/
export function base64UrlDecode(base64Url: string): Uint8Array {
// Add padding if necessary
let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const padding = base64.length % 4;
if (padding) {
base64 += '='.repeat(4 - padding);
}
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
+201
View File
@@ -0,0 +1,201 @@
/**
* PKCE (Proof Key for Code Exchange) utilities for OAuth authentication.
* Provides secure code_verifier/code_challenge generation and state management.
*/
import { base64UrlEncode } from './encoding';
/**
* OAuth flow types supported by the application.
*/
export type OAuthFlowType = 'login' | 'register' | 'link';
/**
* OAuth provider types.
*/
export type OAuthProvider = 'google' | 'github' | 'microsoft';
/**
* Interface representing stored OAuth state in sessionStorage.
*/
export interface OAuthState {
/** The state parameter for CSRF protection */
state: string;
/** The code_verifier for PKCE exchange */
codeVerifier: string;
/** The type of OAuth flow */
flowType: OAuthFlowType;
/** The OAuth provider */
provider: OAuthProvider;
/** The redirect URI for the callback */
redirectUri: string;
/** Timestamp when the state expires */
expiresAt: number;
}
/**
* Storage key prefix for OAuth state in sessionStorage.
*/
const OAUTH_STATE_PREFIX = 'oauth_state_';
/**
* Default expiry time for OAuth state in milliseconds (10 minutes).
*/
const DEFAULT_OAUTH_STATE_EXPIRY = 10 * 60 * 1000;
/**
* Generates a cryptographically secure code_verifier.
* Per RFC 7636, the code_verifier should be 43-128 characters
* consisting of [A-Z], [a-z], [0-9], "-", ".", "_", "~".
*
* @returns A random URL-safe code_verifier string
*/
export function generateCodeVerifier(): string {
// Generate 32 random bytes (256 bits) for the verifier
const array = new Uint8Array(32);
crypto.getRandomValues(array);
// Encode as base64url without padding
return base64UrlEncode(array);
}
/**
* Generates a cryptographically secure state parameter for CSRF protection.
*
* @returns A random URL-safe state string
*/
export function generateState(): string {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return base64UrlEncode(array);
}
/**
* Computes the S256 code_challenge from a code_verifier.
* Uses SHA-256 hash followed by base64url encoding without padding.
*
* @param verifier - The code_verifier to compute the challenge from
* @returns The S256 code_challenge as a base64url-encoded string
*/
export async function computeCodeChallenge(verifier: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(verifier);
const hash = await crypto.subtle.digest('SHA-256', data);
return base64UrlEncode(new Uint8Array(hash));
}
/**
* Stores OAuth state in sessionStorage with an expiry time.
*
* @param stateData - Object containing OAuth state parameters
*/
export function storeOAuthState(stateData: {
state: string;
codeVerifier: string;
flow: OAuthFlowType;
provider: OAuthProvider;
redirectUri: string;
}): void {
const expiresAt = Date.now() + DEFAULT_OAUTH_STATE_EXPIRY;
const oauthState: OAuthState = {
state: stateData.state,
codeVerifier: stateData.codeVerifier,
flowType: stateData.flow,
provider: stateData.provider,
redirectUri: stateData.redirectUri,
expiresAt,
};
const storageKey = `${OAUTH_STATE_PREFIX}${stateData.state}`;
sessionStorage.setItem(storageKey, JSON.stringify(oauthState));
}
/**
* Retrieves OAuth state from sessionStorage if it exists and hasn't expired.
*
* @param state - The state parameter to look up
* @returns The OAuthState if found and valid, null otherwise
*/
export function getOAuthState(state: string): OAuthState | null {
const storageKey = `${OAUTH_STATE_PREFIX}${state}`;
const stored = sessionStorage.getItem(storageKey);
if (!stored) {
return null;
}
try {
const oauthState: OAuthState = JSON.parse(stored);
// Check if the state has expired
if (Date.now() > oauthState.expiresAt) {
// Clean up expired state
clearOAuthState(state);
return null;
}
return oauthState;
} catch {
// Invalid JSON, clean up and return null
clearOAuthState(state);
return null;
}
}
/**
* Clears OAuth state from sessionStorage.
*
* @param state - The state parameter to clear
*/
export function clearOAuthState(state: string): void {
const storageKey = `${OAUTH_STATE_PREFIX}${state}`;
sessionStorage.removeItem(storageKey);
}
/**
* Clears all expired OAuth states from sessionStorage.
* Useful for cleanup operations.
*/
export function cleanupExpiredOAuthStates(): void {
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i);
if (key && key.startsWith(OAUTH_STATE_PREFIX)) {
try {
const stored = sessionStorage.getItem(key);
if (stored) {
const oauthState: OAuthState = JSON.parse(stored);
if (Date.now() > oauthState.expiresAt) {
sessionStorage.removeItem(key);
}
}
} catch {
// Invalid entry, remove it
sessionStorage.removeItem(key);
}
}
}
}
/**
* Validates that a code_verifier meets PKCE requirements.
* Per RFC 7636, the code_verifier must be 43-128 characters
* and match the character set [A-Z], [a-z], [0-9], "-", ".", "_", "~".
*
* @param verifier - The code_verifier to validate
* @returns true if valid, false otherwise
*/
export function isValidCodeVerifier(verifier: string): boolean {
// RFC 7636 defines the character set for code_verifier
const validPattern = /^[A-Za-z0-9\-._~]+$/;
// Check length requirements (43-128 characters)
if (verifier.length < 43 || verifier.length > 128) {
return false;
}
// Check character set
return validPattern.test(verifier);
}
+257 -10
View File
@@ -1,5 +1,5 @@
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { Mail, Lock, ArrowRight, Fingerprint, ArrowLeft, ShieldCheck, Loader2, Smartphone, AlertTriangle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -23,13 +23,15 @@ import {
} from "@/lib/webauthn";
import { AddPasskeyWizard } from "@/components/security/AddPasskeyWizard";
import { TotpEnrollmentWizard } from "@/components/security/TotpEnrollmentWizard";
import { generateCodeVerifier, computeCodeChallenge, generateState, storeOAuthState, OAuthProvider } from "@/lib/oauth";
type LoginStep = 'credentials' | 'totp' | 'webauthn' | 'passkey-email' | 'mfa-enrollment';
type LoginStep = 'credentials' | 'totp' | 'webauthn' | 'passkey-email' | 'mfa-enrollment' | 'mfa';
export default function LoginPage() {
const { login, verifyTotp, refreshUser } = useAuth();
const navigate = useNavigate();
const { toast } = useToast();
const [searchParams] = useSearchParams();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [rememberMe, setRememberMe] = useState(false);
@@ -38,6 +40,28 @@ export default function LoginPage() {
const [totpCode, setTotpCode] = useState("");
const [useBackupCode, setUseBackupCode] = useState(false);
const [passkeyEmail, setPasskeyEmail] = useState("");
const [mfaToken, setMfaToken] = useState<string | null>(null);
// Check for MFA step from OAuth callback
useEffect(() => {
if (searchParams.get('step') === 'mfa') {
const storedMfaToken = sessionStorage.getItem('mfa_token');
const mfaFlow = sessionStorage.getItem('mfa_flow');
if (storedMfaToken && mfaFlow === 'external_auth') {
setMfaToken(storedMfaToken);
setStep('mfa');
} else {
// No valid MFA token, redirect to credentials
toast({
variant: "destructive",
title: "Error",
description: "MFA verification session expired. Please try signing in again.",
});
navigate('/login', { replace: true });
}
}
}, [searchParams, navigate, toast]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -76,6 +100,63 @@ export default function LoginPage() {
}
};
const handleMfaSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (totpCode.length < 6 && !useBackupCode) {
toast({
variant: "destructive",
title: "Invalid code",
description: "Please enter your complete verification code.",
});
return;
}
setIsLoading(true);
try {
if (mfaToken) {
// Use MFA token verification for OAuth callback flow
const response = await api.totp.verifyWithMfaToken(totpCode, mfaToken, useBackupCode);
// Store token and update user
if (response.token) {
tokenManager.setToken(response.token, response.expires_at ?? null);
}
// Clear MFA session data
sessionStorage.removeItem('mfa_token');
sessionStorage.removeItem('mfa_flow');
// Refresh user context and navigate
await refreshUser();
navigate('/profile');
} else {
// Fallback to regular TOTP verification
await verifyTotp(totpCode, useBackupCode);
}
} catch (error) {
if (import.meta.env.DEV) {
console.error("[Gatehouse] MFA verification failed:", error);
}
const message = error instanceof ApiError
? error.message
: import.meta.env.DEV && error instanceof Error
? error.message
: "Invalid verification code";
toast({
variant: "destructive",
title: "Verification failed",
description: message,
});
setTotpCode("");
} finally {
setIsLoading(false);
}
};
const handleTotpSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -269,6 +350,62 @@ export default function LoginPage() {
setPasskeyEmail("");
};
/**
* Initiate OAuth login flow for external provider
*/
const handleOAuthLogin = async (provider: OAuthProvider) => {
setIsLoading(true);
try {
// Generate PKCE parameters
const codeVerifier = generateCodeVerifier();
const codeChallenge = await computeCodeChallenge(codeVerifier);
const state = generateState();
// Store OAuth state for callback validation
storeOAuthState({
state,
codeVerifier,
flow: 'login',
provider,
redirectUri: `${window.location.origin}/oauth/callback`,
});
// Get authorization URL from backend
const response = await api.externalAuth.initiateLogin(provider, state);
// Redirect to provider authorization page
const authUrl = new URL(response.authorization_url);
authUrl.searchParams.set('state', response.state || state);
// Add PKCE parameters
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
window.location.href = authUrl.toString();
} catch (error) {
if (import.meta.env.DEV) {
console.error("[Gatehouse] OAuth login failed:", error);
}
let message = `Failed to initiate ${provider} sign in`;
if (error instanceof ApiError) {
message = error.message;
} else if (error instanceof Error) {
message = error.message;
}
toast({
variant: "destructive",
title: "Sign in failed",
description: message,
});
} finally {
setIsLoading(false);
}
};
// Auto-submit when OTP is complete
const handleOtpChange = (value: string) => {
setTotpCode(value);
@@ -412,6 +549,95 @@ export default function LoginPage() {
);
}
// MFA verification step (after OAuth callback)
if (step === 'mfa') {
return (
<div className="auth-card">
<div className="text-center mb-8">
<div className="mx-auto w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-4">
<ShieldCheck className="w-6 h-6 text-primary" />
</div>
<h1 className="text-2xl font-semibold text-foreground tracking-tight">
Two-factor authentication
</h1>
<p className="text-muted-foreground mt-2">
Enter the 6-digit code from your authenticator app to complete sign in
</p>
</div>
<form id="mfa-form" onSubmit={handleMfaSubmit} className="space-y-6">
{useBackupCode ? (
<div className="space-y-2">
<Label htmlFor="mfa-backup-code">Backup code</Label>
<Input
id="mfa-backup-code"
type="text"
placeholder="Enter 16-character backup code"
value={totpCode}
onChange={(e) => setTotpCode(e.target.value.toUpperCase())}
className="text-center font-mono tracking-widest"
maxLength={16}
autoFocus
/>
</div>
) : (
<div className="flex justify-center">
<InputOTP
maxLength={6}
value={totpCode}
onChange={handleOtpChange}
autoFocus
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
</div>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
"Verifying..."
) : (
<>
Verify
<ArrowRight className="w-4 h-4 ml-2" />
</>
)}
</Button>
</form>
<div className="mt-6 space-y-3">
<Button
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => setUseBackupCode(!useBackupCode)}
>
{useBackupCode ? "Use authenticator app" : "Use a backup code instead"}
</Button>
<Button
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => {
sessionStorage.removeItem('mfa_token');
sessionStorage.removeItem('mfa_flow');
navigate('/login', { replace: true });
}}
>
<ArrowLeft className="w-4 h-4 mr-2" />
Cancel and return to sign in
</Button>
</div>
</div>
);
}
// TOTP verification step
if (step === 'totp') {
return (
@@ -667,7 +893,14 @@ export default function LoginPage() {
</Button>
<div className="grid grid-cols-3 gap-3">
<Button variant="outline" className="w-full" type="button">
<Button
variant="outline"
className="w-full"
type="button"
onClick={() => handleOAuthLogin('google')}
disabled={isLoading}
title="Sign in with Google"
>
<svg className="w-4 h-4" viewBox="0 0 24 24">
<path
fill="currentColor"
@@ -687,7 +920,14 @@ export default function LoginPage() {
/>
</svg>
</Button>
<Button variant="outline" className="w-full" type="button">
<Button
variant="outline"
className="w-full"
type="button"
onClick={() => handleOAuthLogin('github')}
disabled={isLoading}
title="Sign in with GitHub"
>
<svg className="w-4 h-4" viewBox="0 0 24 24">
<path
fill="currentColor"
@@ -695,12 +935,19 @@ export default function LoginPage() {
/>
</svg>
</Button>
<Button variant="outline" className="w-full" type="button">
<Button
variant="outline"
className="w-full"
type="button"
onClick={() => handleOAuthLogin('microsoft')}
disabled={isLoading}
title="Sign in with Microsoft"
>
<svg className="w-4 h-4" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M21.35 11.1h-9.17v2.73h6.51c-.33 3.81-3.5 5.44-6.5 5.44C8.36 19.27 5 16.25 5 12c0-4.1 3.2-7.27 7.2-7.27 3.09 0 4.9 1.97 4.9 1.97L19 4.72S16.56 2 12.1 2C6.42 2 2.03 6.8 2.03 12c0 5.05 4.13 10 10.22 10 5.35 0 9.25-3.67 9.25-9.09 0-1.15-.15-1.81-.15-1.81z"
/>
<path fill="#f25022" d="M1 1h10v10H1z" />
<path fill="#00a4ef" d="M1 13h10v10H1z" />
<path fill="#7fba00" d="M13 1h10v10H13z" />
<path fill="#ffb900" d="M13 13h10v10H13z" />
</svg>
</Button>
</div>
+211
View File
@@ -0,0 +1,211 @@
import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Loader2, AlertCircle, CheckCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { useAuth } from "@/contexts/AuthContext";
import { api, ApiError, tokenManager, OAuthCallbackResponse } from "@/lib/api";
import { getOAuthState, clearOAuthState } from "@/lib/oauth";
import { useToast } from "@/hooks/use-toast";
type CallbackState = 'loading' | 'success' | 'error';
/**
* OAuth callback page that handles the redirect from external OAuth providers.
* Extracts the authorization code and state from the URL, validates the state,
* exchanges the code for tokens, and handles MFA requirements.
*/
export default function OAuthCallbackPage() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { refreshUser } = useAuth();
const { toast } = useToast();
const [status, setStatus] = useState<CallbackState>('loading');
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const handleCallback = async () => {
// 1. Extract query parameters from URL
const code = searchParams.get("code");
const callbackState = searchParams.get("state");
const errorParam = searchParams.get("error");
const errorDescription = searchParams.get("error_description");
// 2. Handle OAuth errors from provider
if (errorParam) {
setStatus('error');
// User denied access
if (errorParam === 'access_denied') {
setError("You denied the authorization request. Please try again if you wish to sign in.");
} else {
setError(errorDescription || `Authorization failed: ${errorParam}`);
}
return;
}
// Validate required parameters
if (!code || !callbackState) {
setStatus('error');
setError("Missing authorization code or state parameter. Please try signing in again.");
return;
}
// 3. Validate state parameter (CSRF protection)
const storedState = getOAuthState(callbackState);
if (!storedState) {
setStatus('error');
setError("Invalid or expired OAuth state. Please try signing in again.");
return;
}
try {
// 4. Exchange authorization code for tokens using the API
const response = await api.externalAuth.handleCallback(
storedState.provider,
code,
callbackState
);
// Handle error response from backend
if (response.error) {
setStatus('error');
// Map error types to user-friendly messages
switch (response.error_type) {
case 'ACCESS_DENIED':
setError("You denied the authorization request. Please try again if you wish to sign in.");
break;
case 'INVALID_REQUEST':
setError("Invalid request. Please try signing in again.");
break;
case 'SERVER_ERROR':
setError("The authentication server encountered an error. Please try again later.");
break;
default:
setError(response.error || "An error occurred during authentication.");
}
clearOAuthState(callbackState);
return;
}
// 5. Handle MFA requirement
if (response.requires_mfa && response.mfa_token) {
// Store MFA token for the MFA verification flow
sessionStorage.setItem('mfa_token', response.mfa_token);
sessionStorage.setItem('mfa_flow', 'external_auth');
clearOAuthState(callbackState);
// Redirect to login page with MFA step
navigate('/login?step=mfa', { replace: true });
return;
}
// 6. Store authentication tokens
if (response.token && response.expires_in) {
tokenManager.setToken(response.token, new Date(Date.now() + response.expires_in * 1000).toISOString());
}
// Clear OAuth state (single-use)
clearOAuthState(callbackState);
// Refresh user context
await refreshUser();
setStatus('success');
// Show success toast and redirect
toast({
title: "Sign in successful",
description: response.user ? `Welcome, ${response.user.email}` : "You have been signed in successfully.",
});
// 7. Redirect based on flow type
setTimeout(() => {
switch (storedState.flowType) {
case 'link':
navigate('/linked-accounts', { replace: true });
break;
case 'register':
navigate('/profile', { replace: true });
break;
case 'login':
default:
navigate('/profile', { replace: true });
}
}, 1500);
} catch (err) {
setStatus('error');
clearOAuthState(callbackState);
if (err instanceof ApiError) {
// Handle specific error types
if (err.type === 'STATE_MISMATCH') {
setError("CSRF protection check failed. Please try signing in again.");
} else if (err.code === 401) {
setError("Authentication failed. The authorization code may have expired.");
} else {
setError(err.message || "An unexpected error occurred during authentication.");
}
} else {
setError("An unexpected error occurred. Please try signing in again.");
}
}
};
handleCallback();
}, [searchParams, navigate, refreshUser, toast]);
if (status === 'loading') {
return (
<div className="auth-card">
<div className="text-center">
<Loader2 className="w-12 h-12 animate-spin text-primary mx-auto mb-4" />
<h1 className="text-2xl font-semibold">Completing sign in...</h1>
<p className="text-muted-foreground mt-2">
Please wait while we verify your credentials
</p>
</div>
</div>
);
}
if (status === 'error') {
return (
<div className="auth-card">
<Card className="border-destructive/50">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-destructive">
<AlertCircle className="w-5 h-5" />
Authentication Failed
</CardTitle>
<CardDescription>
{error}
</CardDescription>
</CardHeader>
<CardContent>
<Button onClick={() => navigate('/login', { replace: true })} className="w-full">
Return to Sign In
</Button>
</CardContent>
</Card>
</div>
);
}
// Success state (briefly shown before redirect)
return (
<div className="auth-card">
<div className="text-center">
<CheckCircle className="w-12 h-12 text-green-500 mx-auto mb-4" />
<h1 className="text-2xl font-semibold">Sign in successful!</h1>
<p className="text-muted-foreground mt-2">
Redirecting you to your profile...
</p>
</div>
</div>
);
}
+246 -91
View File
@@ -1,67 +1,155 @@
import { Link2, Unlink, AlertCircle } from "lucide-react";
import { useState, useEffect } from "react";
import { Link2, Unlink, AlertCircle, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
const socialProviders = [
{
id: "google",
name: "Google",
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path
fill="currentColor"
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
fill="currentColor"
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
fill="currentColor"
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
fill="currentColor"
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>
),
linked: true,
email: "john.doe@gmail.com",
},
{
id: "github",
name: "GitHub",
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.87 8.17 6.84 9.5.5.08.66-.23.66-.5v-1.69c-2.77.6-3.36-1.34-3.36-1.34-.46-1.16-1.11-1.47-1.11-1.47-.91-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.87 1.52 2.34 1.07 2.91.83.09-.65.35-1.09.63-1.34-2.22-.25-4.55-1.11-4.55-4.92 0-1.11.38-2 1.03-2.71-.1-.25-.45-1.29.1-2.64 0 0 .84-.27 2.75 1.02.79-.22 1.65-.33 2.5-.33.85 0 1.71.11 2.5.33 1.91-1.29 2.75-1.02 2.75-1.02.55 1.35.2 2.39.1 2.64.65.71 1.03 1.6 1.03 2.71 0 3.82-2.34 4.66-4.57 4.91.36.31.69.92.69 1.85V21c0 .27.16.59.67.5C19.14 20.16 22 16.42 22 12A10 10 0 0012 2z"
/>
</svg>
),
linked: true,
email: "johndoe",
},
{
id: "microsoft",
name: "Microsoft",
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path fill="#f25022" d="M1 1h10v10H1z" />
<path fill="#00a4ef" d="M1 13h10v10H1z" />
<path fill="#7fba00" d="M13 1h10v10H13z" />
<path fill="#ffb900" d="M13 13h10v10H13z" />
</svg>
),
linked: false,
email: null,
},
];
import { api, LinkedAccount, ExternalProvider, ExternalProviderId, ApiError } from "@/lib/api";
import { storeOAuthState, generateState, generateCodeVerifier } from "@/lib/oauth";
import { useToast } from "@/hooks/use-toast";
export default function LinkedAccountsPage() {
const { toast } = useToast();
const [linkedAccounts, setLinkedAccounts] = useState<LinkedAccount[]>([]);
const [providers, setProviders] = useState<ExternalProvider[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isLinking, setIsLinking] = useState<ExternalProviderId | null>(null);
const [isUnlinking, setIsUnlinking] = useState<ExternalProviderId | null>(null);
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
try {
const [accountsRes, providersRes] = await Promise.all([
api.externalAuth.listLinkedAccounts(),
api.externalAuth.listProviders(),
]);
// API returns standardized wrapper: { data: { linked_accounts: [], unlink_available: false } }
// The request function extracts json.data, so accountsRes is { linked_accounts: [], unlink_available: false }
setLinkedAccounts(accountsRes.linked_accounts || []);
// API returns standardized wrapper: { data: { providers: [...] } }
// The request function extracts json.data, so providersRes is { providers: [...] }
setProviders(providersRes.providers || []);
} catch (error) {
if (import.meta.env.DEV) {
console.error("[LinkedAccounts] Failed to load:", error);
}
toast({
variant: "destructive",
title: "Error",
description: "Failed to load linked accounts",
});
} finally {
setIsLoading(false);
}
};
const isLinked = (providerId: string): boolean => {
return linkedAccounts.some(
(account) => account.provider_type.toLowerCase() === providerId.toLowerCase()
);
};
const getLinkedEmail = (providerId: string): string | null => {
const account = linkedAccounts.find(
(a) => a.provider_type.toLowerCase() === providerId.toLowerCase()
);
return account?.email || null;
};
const getLinkedDate = (providerId: string): string | null => {
const account = linkedAccounts.find(
(a) => a.provider_type.toLowerCase() === providerId.toLowerCase()
);
return account?.linked_at || null;
};
const handleConnect = async (provider: ExternalProviderId) => {
setIsLinking(provider);
try {
const state = generateState();
const codeVerifier = await generateCodeVerifier();
const response = await api.externalAuth.initiateLink(provider, state);
// Store OAuth state for callback
storeOAuthState({
state,
codeVerifier,
flow: 'link',
provider,
redirectUri: `${window.location.origin}/oauth/callback`,
});
// Redirect to authorization
window.location.href = response.authorization_url;
} catch (error) {
if (import.meta.env.DEV) {
console.error("[LinkedAccounts] Connect failed:", error);
}
toast({
variant: "destructive",
title: "Connection failed",
description: error instanceof ApiError
? error.message
: "Failed to connect account",
});
} finally {
setIsLinking(null);
}
};
const handleDisconnect = async (provider: ExternalProviderId) => {
if (!confirm(`Are you sure you want to disconnect ${provider}?`)) {
return;
}
setIsUnlinking(provider);
try {
await api.externalAuth.unlinkAccount(provider);
setLinkedAccounts((prev) =>
prev.filter((a) => a.provider_type.toLowerCase() !== provider.toLowerCase())
);
toast({
title: "Account disconnected",
description: `${provider} has been removed from your account`,
});
} catch (error) {
if (import.meta.env.DEV) {
console.error("[LinkedAccounts] Disconnect failed:", error);
}
toast({
variant: "destructive",
title: "Error",
description: error instanceof ApiError
? error.message
: "Failed to disconnect account",
});
} finally {
setIsUnlinking(null);
}
};
if (isLoading) {
return (
<div className="page-container">
<div className="flex items-center justify-center min-h-[400px]">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
</div>
);
}
return (
<div className="page-container">
<div className="page-header">
@@ -80,42 +168,109 @@ export default function LinkedAccountsPage() {
</Alert>
<div className="space-y-4">
{socialProviders.map((provider) => (
<Card key={provider.id}>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-lg bg-secondary flex items-center justify-center">
{provider.icon}
{providers.map((provider) => {
const linked = isLinked(provider.id);
const email = getLinkedEmail(provider.id);
const linkedDate = getLinkedDate(provider.id);
const isConnecting = isLinking === provider.id;
const isDisconnecting = isUnlinking === provider.id;
return (
<Card key={provider.id}>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-lg bg-secondary flex items-center justify-center">
{getProviderIcon(provider.id)}
</div>
<div>
<p className="font-medium text-foreground">{provider.name}</p>
{linked ? (
<div className="flex flex-col">
<p className="text-sm text-muted-foreground">{email}</p>
{linkedDate && (
<p className="text-xs text-muted-foreground/70">
Connected since {new Date(linkedDate).toLocaleDateString()}
</p>
)}
</div>
) : (
<p className="text-sm text-muted-foreground">
{provider.is_active ? "Not connected" : "Not configured"}
</p>
)}
</div>
</div>
<div>
<p className="font-medium text-foreground">{provider.name}</p>
{provider.linked ? (
<p className="text-sm text-muted-foreground">{provider.email}</p>
) : (
<p className="text-sm text-muted-foreground">Not connected</p>
)}
</div>
</div>
{provider.linked ? (
<div className="flex items-center gap-3">
<Badge className="bg-success/10 text-success border-0">Connected</Badge>
<Button variant="outline" size="sm">
<Unlink className="w-4 h-4 mr-2" />
Disconnect
{linked ? (
<div className="flex items-center gap-3">
<Badge className="bg-success/10 text-success border-0">Connected</Badge>
<Button
variant="outline"
size="sm"
disabled={isDisconnecting}
onClick={() => handleDisconnect(provider.id)}
>
{isDisconnecting ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
) : (
<Unlink className="w-4 h-4 mr-2" />
)}
Disconnect
</Button>
</div>
) : (
<Button
size="sm"
disabled={!provider.is_active || isConnecting}
onClick={() => handleConnect(provider.id)}
>
{isConnecting ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
) : (
<Link2 className="w-4 h-4 mr-2" />
)}
Connect
</Button>
</div>
) : (
<Button size="sm">
<Link2 className="w-4 h-4 mr-2" />
Connect
</Button>
)}
</div>
</CardContent>
</Card>
))}
)}
</div>
</CardContent>
</Card>
);
})}
</div>
</div>
);
}
// Helper function to get provider icon
function getProviderIcon(providerId: string) {
switch (providerId.toLowerCase()) {
case 'google':
return (
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path fill="#4285F4" 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 fill="#34A853" 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 fill="#FBBC05" 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 fill="#EA4335" 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>
);
case 'github':
return (
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path fill="currentColor" d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.87 8.17 6.84 9.5.5.08.66-.23.66-.5v-1.69c-2.77.6-3.36-1.34-3.36-1.34-.46-1.16-1.11-1.47-1.11-1.47-.91-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.87 1.52 2.34 1.07 2.91.83.09-.65.35-1.09.63-1.34-2.22-.25-4.55-1.11-4.55-4.92 0-1.11.38-2 1.03-2.71-.1-.25-.45-1.29.1-2.64 0 0 .84-.27 2.75 1.02.79-.22 1.65-.33 2.5-.33.85 0 1.71.11 2.5.33 1.91-1.29 2.75-1.02 2.75-1.02.55 1.35.2 2.39.1 2.64.65.71 1.03 1.6 1.03 2.71 0 3.82-2.34 4.66-4.57 4.91.36.31.69.92.69 1.85V21c0 .27.16.59.67.5C19.14 20.16 22 16.42 22 12A10 10 0 0012 2z"/>
</svg>
);
case 'microsoft':
return (
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path fill="#f25022" d="M1 1h10v10H1z" />
<path fill="#00a4ef" d="M1 13h10v10H1z" />
<path fill="#7fba00" d="M13 1h10v10H13z" />
<path fill="#ffb900" d="M13 13h10v10H13z" />
</svg>
);
default:
return null;
}
}