Create Discord OAuth callback page

cgen-968f482f11f544bfae37d5e8e042a33d
This commit is contained in:
Builder.io 2025-11-09 08:14:40 +00:00
parent bb88f22021
commit 0c65234087

View file

@ -1,81 +1,137 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from "react-router-dom";
import LoadingScreen from '@/components/LoadingScreen'; import { useAuth } from "@/contexts/AuthContext";
import { useToast } from '@/hooks/use-toast'; import Layout from "@/components/Layout";
import SEO from "@/components/SEO";
import { Card, CardContent } from "@/components/ui/card";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Loader, AlertTriangle, CheckCircle } from "lucide-react";
export default function DiscordOAuthCallback() { export default function DiscordOAuthCallback() {
const navigate = useNavigate(); const navigate = useNavigate();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const { toast } = useToast(); const { user, signIn } = useAuth();
const [isProcessing, setIsProcessing] = useState(true);
const [status, setStatus] = useState<"loading" | "success" | "error">("loading");
const [message, setMessage] = useState("Connecting to Discord...");
useEffect(() => { useEffect(() => {
const handleCallback = async () => { const handleCallback = async () => {
const code = searchParams.get("code");
const state = searchParams.get("state");
const error = searchParams.get("error");
if (error) {
setStatus("error");
setMessage(`Discord authorization failed: ${error}`);
return;
}
if (!code) {
setStatus("error");
setMessage("No authorization code received from Discord");
return;
}
try { try {
const code = searchParams.get('code'); setMessage("Processing authentication...");
const state = searchParams.get('state');
const error = searchParams.get('error');
if (error) { // Call backend to handle OAuth exchange
throw new Error(`Discord OAuth error: ${error}`); const response = await fetch("/api/discord/oauth/callback", {
} method: "POST",
headers: { "Content-Type": "application/json" },
if (!code) { body: JSON.stringify({
throw new Error('No authorization code received from Discord'); code,
} state: state || "/dashboard",
}),
// Send code to backend to exchange for token
const response = await fetch('/api/discord/oauth/callback', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
}); });
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to process Discord OAuth');
}
const data = await response.json(); const data = await response.json();
// Store the Discord token if provided if (!response.ok) {
if (data.access_token) { setStatus("error");
localStorage.setItem('discord_access_token', data.access_token); setMessage(data.message || "Failed to authenticate with Discord");
return;
} }
toast({ // Success
title: 'Discord connected', setStatus("success");
description: 'Welcome to AeThex!', setMessage("Successfully linked! Redirecting...");
});
// Redirect to dashboard or home // The backend handles session setup, so just redirect
navigate('/dashboard', { replace: true }); const nextPath = state && state.startsWith("/") ? state : "/dashboard";
setTimeout(() => {
navigate(nextPath);
}, 2000);
} catch (error) { } catch (error) {
console.error('Discord OAuth callback error:', error); setStatus("error");
toast({ setMessage(
variant: 'destructive', error instanceof Error
title: 'Authentication failed', ? error.message
description: error instanceof Error ? error.message : 'Failed to connect Discord', : "An unexpected error occurred"
}); );
// Redirect back to login
setTimeout(() => navigate('/login', { replace: true }), 2000);
} finally {
setIsProcessing(false);
} }
}; };
handleCallback(); handleCallback();
}, [searchParams, navigate, toast]); }, [searchParams, navigate]);
if (isProcessing) { return (
return ( <Layout>
<LoadingScreen <SEO title="Discord Authentication | AeThex" />
message="Connecting with Discord..."
showProgress
duration={1000}
/>
);
}
return null; <div className="min-h-screen flex items-center justify-center pt-20 pb-12 px-4">
<Card className="bg-card/60 border-border/40 backdrop-blur max-w-md w-full">
<CardContent className="pt-8 space-y-6">
{status === "loading" && (
<div className="flex flex-col items-center gap-4">
<Loader className="h-8 w-8 animate-spin text-blue-500" />
<div className="text-center space-y-2">
<p className="font-semibold text-foreground">{message}</p>
<p className="text-sm text-muted-foreground">
Please wait while we secure your account...
</p>
</div>
</div>
)}
{status === "success" && (
<div className="flex flex-col items-center gap-4">
<CheckCircle className="h-8 w-8 text-green-500" />
<div className="text-center space-y-2">
<p className="font-semibold text-foreground">{message}</p>
<p className="text-sm text-muted-foreground">
You'll be taken to your dashboard shortly...
</p>
</div>
</div>
)}
{status === "error" && (
<div className="space-y-4">
<div className="flex items-start gap-3">
<AlertTriangle className="h-6 w-6 text-red-500 flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="font-semibold text-red-600">
Authentication Failed
</p>
<p className="text-sm text-red-500/80">{message}</p>
</div>
</div>
<div className="flex gap-2">
<button
onClick={() => navigate("/login")}
className="flex-1 px-4 py-2 rounded-lg bg-primary hover:bg-primary/90 text-primary-foreground font-medium transition-colors"
>
Back to Login
</button>
</div>
</div>
)}
</CardContent>
</Card>
</div>
</Layout>
);
} }