Skip to content
Merged
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
45 changes: 45 additions & 0 deletions src/client/createSeamlessAuthClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ export interface LoginInput {
passkeyAvailable: boolean;
}

export type LoginMethod = 'passkey' | 'magic_link' | 'email_otp' | 'phone_otp';

export interface LoginStartResult {
message?: string;
identifierType?: 'email' | 'phone';
loginMethods?: LoginMethod[];
}

export interface RegisterInput {
email: string;
phone: string;
Expand Down Expand Up @@ -109,8 +117,12 @@ export interface SeamlessAuthClient {
register: (input: RegisterInput) => Promise<Response>;
requestPhoneOtp: () => Promise<Response>;
verifyPhoneOtp: (verificationToken: string) => Promise<Response>;
requestLoginPhoneOtp: () => Promise<Response>;
verifyLoginPhoneOtp: (verificationToken: string) => Promise<Response>;
requestEmailOtp: () => Promise<Response>;
verifyEmailOtp: (verificationToken: string) => Promise<Response>;
requestLoginEmailOtp: () => Promise<Response>;
verifyLoginEmailOtp: (verificationToken: string) => Promise<Response>;
requestMagicLink: () => Promise<Response>;
checkMagicLink: () => Promise<Response>;
verifyMagicLink: (token: string) => Promise<Response>;
Expand Down Expand Up @@ -300,6 +312,23 @@ export const createSeamlessAuthClient = (
credentials: 'include',
}),

requestLoginPhoneOtp: () =>
fetchWithAuth(`/otp/generate-login-phone-otp`, {
method: 'GET',
}),

verifyLoginPhoneOtp: verificationToken =>
fetchWithAuth(`/otp/verify-login-phone-otp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
verificationToken,
}),
credentials: 'include',
}),

requestEmailOtp: () =>
fetchWithAuth(`/otp/generate-email-otp`, {
method: 'GET',
Expand All @@ -316,6 +345,22 @@ export const createSeamlessAuthClient = (
credentials: 'include',
}),

requestLoginEmailOtp: () =>
fetchWithAuth(`/otp/generate-login-email-otp`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
}),

verifyLoginEmailOtp: verificationToken =>
fetchWithAuth(`/otp/verify-login-email-otp`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
verificationToken,
}),
credentials: 'include',
}),

requestMagicLink: () =>
fetchWithAuth(`/magic-link`, {
method: 'GET',
Expand Down
44 changes: 37 additions & 7 deletions src/components/AuthFallbackOptions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,43 @@

import React from 'react';
import { isValidEmail, isValidPhoneNumber } from '../utils';
import type { LoginMethod } from '@/client/createSeamlessAuthClient';

import styles from '../styles/login.module.css';

interface AuthFallbackOptionsProps {
identifier: string;
onMagicLink: () => void;
onEmailOtp?: () => void;
onPhoneOtp: () => void;
onPasskeyRetry: () => void;
onPasskeyRetry?: () => void;
loginMethods?: LoginMethod[];
}

const AuthFallbackOptions: React.FC<AuthFallbackOptionsProps> = ({
identifier,
onMagicLink,
onEmailOtp,
onPhoneOtp,
onPasskeyRetry,
loginMethods,
}) => {
const showMagicLink = isValidEmail(identifier);
const showPhoneOtp = isValidPhoneNumber(identifier);
const allowedMethods = new Set<LoginMethod>(
loginMethods ?? ['passkey', 'magic_link', 'phone_otp']
);
const showMagicLink = allowedMethods.has('magic_link') && isValidEmail(identifier);
const showEmailOtp =
allowedMethods.has('email_otp') && Boolean(onEmailOtp) && isValidEmail(identifier);
const showPhoneOtp = allowedMethods.has('phone_otp') && isValidPhoneNumber(identifier);
const showPasskeyRetry = allowedMethods.has('passkey') && Boolean(onPasskeyRetry);

if (!showMagicLink && !showEmailOtp && !showPhoneOtp && !showPasskeyRetry) {
return null;
}

return (
<div className={styles.fallbackCard}>
<div className={styles.fallbackHeader}>Trouble with passkey login?</div>
<div className={styles.fallbackHeader}>Choose a sign-in method</div>

<p className={styles.fallbackDescription}>Choose another secure sign-in method.</p>

Expand All @@ -45,6 +60,19 @@ const AuthFallbackOptions: React.FC<AuthFallbackOptionsProps> = ({
</button>
)}

{showEmailOtp && (
<button
type="button"
className={styles.fallbackActionButton}
onClick={onEmailOtp}
>
<span className={styles.actionTitle}>Email Code</span>
<span className={styles.actionSubtext}>
Receive a one-time code by email
</span>
</button>
)}

{showPhoneOtp && (
<button
type="button"
Expand All @@ -57,9 +85,11 @@ const AuthFallbackOptions: React.FC<AuthFallbackOptionsProps> = ({
)}
</div>

<button type="button" className={styles.linkButton} onClick={onPasskeyRetry}>
Try passkey anyway
</button>
{showPasskeyRetry && (
<button type="button" className={styles.linkButton} onClick={onPasskeyRetry}>
Try passkey anyway
</button>
)}
</div>
);
};
Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
createSeamlessAuthClient,
CurrentUserResult,
LoginInput,
LoginMethod,
LoginStartResult,
PasskeyLoginResult,
PasskeyLoginWithPrfResult,
PasskeyMetadata,
Expand Down Expand Up @@ -52,6 +54,8 @@ export type {
Credential,
CurrentUserResult,
LoginInput,
LoginMethod,
LoginStartResult,
PasskeyLoginWithPrfResult,
PasskeyLoginResult,
PasskeyMetadata,
Expand Down
19 changes: 16 additions & 3 deletions src/views/EmailRegistration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,19 @@ import { useAuth } from '@/AuthProvider';
import React, { useEffect, useState } from 'react';
import { useAuthClient } from '@/hooks/useAuthClient';
import { usePasskeySupport } from '@/hooks/usePasskeySupport';
import { useNavigate } from 'react-router-dom';
import { useLocation, useNavigate } from 'react-router-dom';

import styles from '@/styles/verifyOTP.module.css';
import OtpInput from '@/components/OtpInput';

const EmailRegistration: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const { refreshSession } = useAuth();
const authClient = useAuthClient();
const { passkeySupported } = usePasskeySupport();
const isLoginFlow =
(location.state as { flow?: string } | null)?.flow === 'login';

const [loading, setLoading] = useState(false);
const [emailOtp, setEmailOtp] = useState('');
Expand All @@ -29,7 +32,9 @@ const EmailRegistration: React.FC = () => {
setError('');
setResendMsg('');

const response = await authClient.requestEmailOtp();
const response = isLoginFlow
? await authClient.requestLoginEmailOtp()
: await authClient.requestEmailOtp();

if (!response.ok) {
setError(
Expand All @@ -53,13 +58,21 @@ const EmailRegistration: React.FC = () => {
setLoading(true);

try {
const response = await authClient.verifyEmailOtp(emailOtp);
const response = isLoginFlow
? await authClient.verifyLoginEmailOtp(emailOtp)
: await authClient.verifyEmailOtp(emailOtp);

if (!response.ok) {
setError('Verification failed.');
return;
}

if (isLoginFlow) {
await refreshSession();
navigate('/');
return;
}

if (passkeySupported) {
navigate('/registerPasskey');
} else {
Expand Down
56 changes: 51 additions & 5 deletions src/views/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,23 @@ import { useNavigate } from 'react-router-dom';
import styles from '@/styles/login.module.css';
import { isValidEmail, isValidPhoneNumber } from '../utils';
import AuthFallbackOptions from '@/components/AuthFallbackOptions';
import type { LoginMethod, LoginStartResult } from '@/client/createSeamlessAuthClient';

const DEFAULT_LOGIN_METHODS: LoginMethod[] = ['passkey', 'magic_link', 'phone_otp'];

const parseLoginStartResult = async (
response: Response | null
): Promise<LoginStartResult | null> => {
if (!response || typeof response.json !== 'function') {
return null;
}

try {
return (await response.json()) as LoginStartResult;
} catch {
return null;
}
};

const Login: React.FC = () => {
const navigate = useNavigate();
Expand All @@ -28,6 +45,8 @@ const Login: React.FC = () => {
const [emailError, setEmailError] = useState<string>('');
const [identifierError, setIdentifierError] = useState<string>('');
const [showFallbackOptions, setShowFallbackOptions] = useState(false);
const [loginMethods, setLoginMethods] =
useState<LoginMethod[]>(DEFAULT_LOGIN_METHODS);
const [bootstrapToken, setBootstrapToken] = useState<string | null>(null);

useEffect(() => {
Expand Down Expand Up @@ -112,20 +131,36 @@ const Login: React.FC = () => {

const sendPhoneOtp = async () => {
try {
const response = await authClient.requestPhoneOtp();
const response = await authClient.requestLoginPhoneOtp();

if (!response.ok) {
setFormErrors('Failed to send OTP.');
return;
}

navigate('/verifyPhoneOTP');
navigate('/verifyPhoneOTP', { state: { flow: 'login' } });
} catch (err) {
console.error(err);
setFormErrors('Failed to send OTP.');
}
};

const sendEmailOtp = async () => {
try {
const response = await authClient.requestLoginEmailOtp();

if (!response.ok) {
setFormErrors('Failed to send email code.');
return;
}

navigate('/verifyEmailOTP', { state: { flow: 'login' } });
} catch (err) {
console.error(err);
setFormErrors('Failed to send email code.');
}
};

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setFormErrors('');
Expand All @@ -134,8 +169,17 @@ const Login: React.FC = () => {
try {
if (mode === 'login') {
const loginRes = await login(identifier, passkeySupported);

if (loginRes?.ok && passkeySupported) {
const loginStart = await parseLoginStartResult(loginRes);
const availableMethods = loginStart?.loginMethods?.length
? loginStart.loginMethods
: DEFAULT_LOGIN_METHODS;
setLoginMethods(availableMethods);

if (
loginRes?.ok &&
passkeySupported &&
availableMethods.includes('passkey')
) {
const passkeyResult = await handlePasskeyLogin();
if (passkeyResult) {
navigate('/');
Expand Down Expand Up @@ -207,8 +251,10 @@ const Login: React.FC = () => {
<AuthFallbackOptions
identifier={identifier}
onMagicLink={sendMagicLink}
onEmailOtp={sendEmailOtp}
onPhoneOtp={sendPhoneOtp}
onPasskeyRetry={handlePasskeyLogin}
onPasskeyRetry={passkeySupported ? handlePasskeyLogin : undefined}
loginMethods={loginMethods}
/>
)}

Expand Down
Loading
Loading