Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add endpoints - authenticate [passkeys] #4

Open
wants to merge 21 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions app/auth/callback/apple/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { createServerClient } from "@/server/utils/supabase/supabase-server-client";

export default function AppleAuthCallback() {
const router = useRouter();

useEffect(() => {
const handleAuthCallback = async () => {
try {
const supabase = await createServerClient();
// Get the auth code from the URL
const { error } = await supabase.auth.exchangeCodeForSession(
window.location.href
);

if (error) {
console.error("Error exchanging code for session:", error);
throw error;
}

// Redirect to the dashboard or home page after successful authentication
router.push("/dashboard");
} catch (error) {
console.error("Error during Apple authentication callback:", error);
// Redirect to login page if there's an error
router.push("/?error=Authentication failed");
}
};

handleAuthCallback();
}, [router]);

return (
<div className="flex min-h-screen items-center justify-center">
<div className="text-center">
<h2 className="text-2xl font-semibold mb-4">Authenticating with Apple...</h2>
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-gray-900 mx-auto"></div>
</div>
</div>
);
}
88 changes: 88 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,21 @@ import { useRouter } from "next/navigation"
import { trpc } from "@/client/utils/trpc/trpc-client"
import { useAuth } from "@/client/hooks/useAuth"
import { AuthProviderType } from "@prisma/client"
import { startRegistration, startAuthentication } from "@simplewebauthn/browser";

export default function Login() {
const router = useRouter();
const { user, isLoading: isAuthLoading } = useAuth();
const loginMutation = trpc.authenticate.useMutation();
const startRegistrationMutation = trpc.startRegistration.useMutation();
const verifyRegistrationMutation = trpc.verifyRegistration.useMutation();
const startAuthenticationMutation = trpc.startAuthentication.useMutation();
const verifyAuthenticationMutation = trpc.verifyAuthentication.useMutation();
const [isLoading, setIsLoading] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showEmailForm, setShowEmailForm] = useState(false);
const [errorMessage, setErrorMessage] = useState("");

const handleGoogleSignIn = async () => {
try {
Expand Down Expand Up @@ -71,6 +77,70 @@ export default function Login() {
}
}

// Handle passkey registration
const handlePasskeySignUp = async () => {
try {
setIsLoading(true);
setErrorMessage("");

// Start registration process
const { options, tempUserId } = await startRegistrationMutation.mutateAsync();

// Get attestation from browser
const attestationResponse = await startRegistration({ optionsJSON: options });

// Verify registration with server
const verificationResult = await verifyRegistrationMutation.mutateAsync({
tempUserId,
attestationResponse,
});

if (verificationResult.verified) {
// Registration successful, user should be logged in now
router.push("/dashboard");
} else {
setErrorMessage("Passkey registration failed");
setIsLoading(false);
}
} catch (error) {
console.error("Passkey registration failed:", error);
setErrorMessage(error instanceof Error ? error.message : "Passkey registration failed");
setIsLoading(false);
}
};

// Handle passkey authentication
const handlePasskeySignIn = async () => {
try {
setIsLoading(true);
setErrorMessage("");

// Start authentication process
const { options, tempId } = await startAuthenticationMutation.mutateAsync();

// Get assertion from browser
const authenticationResponse = await startAuthentication({ optionsJSON: options });

// Verify authentication with server
const verificationResult = await verifyAuthenticationMutation.mutateAsync({
tempId,
authenticationResponse,
});

if (verificationResult.verified) {
// Authentication successful, user should be logged in now
router.push("/dashboard");
} else {
setErrorMessage("Passkey authentication failed");
setIsLoading(false);
}
} catch (error) {
console.error("Passkey authentication failed:", error);
setErrorMessage(error instanceof Error ? error.message : "Passkey authentication failed");
setIsLoading(false);
}
};

useEffect(() => {
if (user) {
router.push("/dashboard")
Expand Down Expand Up @@ -133,6 +203,23 @@ export default function Login() {
Sign in with Email & Password
</button>

{/* Passkey buttons */}
<button
onClick={handlePasskeySignUp}
disabled={isLoading}
className="bg-green-500 text-white font-semibold py-2 px-4 border border-green-600 rounded shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
>
Sign Up with Passkey
</button>

<button
onClick={handlePasskeySignIn}
disabled={isLoading}
className="bg-purple-500 text-white font-semibold py-2 px-4 border border-purple-600 rounded shadow-sm hover:bg-purple-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500"
>
Sign In with Passkey
</button>

<button
onClick={handleGoogleSignIn}
disabled={loginMutation.isLoading || isLoading}
Expand Down Expand Up @@ -168,6 +255,7 @@ export default function Login() {
)}
</div>

{errorMessage ? (<p className="mt-4 text-red-500">{errorMessage}</p>) : null}
{loginMutation.error ? (<p className="mt-4 text-red-500">{loginMutation.error.message}</p>) : null}
</div>
)
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
},
"dependencies": {
"@prisma/client": "6.2.1",
"@simplewebauthn/browser": "^13.1.0",
"@simplewebauthn/server": "^13.1.0",
"@supabase/ssr": "^0.5.2",
"@supabase/supabase-js": "^2.48.1",
"@tanstack/react-query": "4.36.1",
Expand All @@ -33,17 +35,20 @@
"next": "14.2.16",
"react": "^18",
"react-dom": "^18",
"server": "link:@types/@simplewebauthn/server",
"superjson": "^2.2.2",
"zod": "^3.24.1"
},
"devDependencies": {
"@mermaid-js/mermaid-cli": "^11.4.2",
"@types/jsonwebtoken": "^9.0.7",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.2.16",
"prisma": "6.2.1",
"prisma-erd-generator": "^1.11.2",
"ts-node": "^10.9.2",
"tsup": "^8.3.6",
"typescript": "^5.7.3"
Expand Down
Loading