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
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@seamless-auth/react",
"version": "0.0.7",
"version": "0.0.8",
"description": "A drop-in authentication solution for modern React applications.",
"type": "module",
"exports": {
Expand Down
12 changes: 3 additions & 9 deletions src/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
} from 'react';

import { AuthMode, createFetchWithAuth } from './fetchWithAuth';
import LoadingSpinner from './components/LoadingSpinner';
import { usePreviousSignIn } from './hooks/usePreviousSignIn';
import {
AuthenticatorTransportFuture,
Expand Down Expand Up @@ -42,6 +41,7 @@
credentials: Credential[];
updateCredential: (credential: Credential) => Promise<Credential>;
deleteCredential: (credentialId: string) => Promise<void>;
loading: boolean;
}

export interface Credential {
Expand Down Expand Up @@ -136,6 +136,7 @@
const hasRole = (role: string) => user?.roles?.includes(role);

const validateToken = async () => {
setLoading(true);
try {
const response = await fetchWithAuth(`users/me`, {
method: 'GET',
Expand Down Expand Up @@ -189,7 +190,7 @@

useEffect(() => {
validateToken();
}, []);

Check warning on line 193 in src/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / test

React Hook useEffect has a missing dependency: 'validateToken'. Either include it or remove the dependency array

useEffect(() => {
if (user && isAuthenticated) {
Expand All @@ -197,19 +198,12 @@
}
}, [user, isAuthenticated, markSignedIn]);

if (loading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<LoadingSpinner />;
</div>
);
}

return (
<AuthContext.Provider
value={{
user,
logout,
loading,
deleteUser,
isAuthenticated,
hasRole,
Expand Down
14 changes: 0 additions & 14 deletions src/components/LoadingSpinner.tsx

This file was deleted.

18 changes: 15 additions & 3 deletions src/components/OtpInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,28 @@ import styles from '@/styles/otpInput.module.css';
interface Props {
length?: number;
value: string;
inputMode?: 'numeric' | 'text';
onChange: (value: string) => void;
}

const OtpInput: React.FC<Props> = ({ length = 6, value, onChange }) => {
const OtpInput: React.FC<Props> = ({
length = 6,
value,
inputMode = 'numeric',
onChange,
}) => {
const inputs = useRef<Array<HTMLInputElement | null>>([]);

const values = value.split('').concat(Array(length).fill('')).slice(0, length);

const handleChange = (index: number, char: string) => {
if (!/^\d?$/.test(char)) return;
if (inputMode === 'numeric') {
if (!/^\d?$/.test(char)) return;
}

if (inputMode === 'text') {
if (!/[a-z]/i.test(char)) return;
}

const newValue = value.substring(0, index) + char + value.substring(index + 1);

Expand Down Expand Up @@ -48,7 +60,7 @@ const OtpInput: React.FC<Props> = ({ length = 6, value, onChange }) => {
key={i}
ref={el => (inputs.current[i] = el)}
type="text"
inputMode="numeric"
inputMode={inputMode}
maxLength={1}
value={digit || ''}
className={styles.otpInput}
Expand Down
14 changes: 5 additions & 9 deletions src/views/EmailRegistration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import styles from '@/styles/verifyOTP.module.css';
import { createFetchWithAuth } from '@/fetchWithAuth';
import { isPasskeySupported } from '@/utils';
import { useInternalAuth } from '@/context/InternalAuthContext';
import OtpInput from '@/components/OtpInput';

const EmailRegistration: React.FC = () => {
const navigate = useNavigate();
Expand Down Expand Up @@ -129,16 +130,11 @@ const EmailRegistration: React.FC = () => {
— Code expires in {formatTime(emailTimeLeft)}
</span>
</label>

<input
id="emailCode"
type="text"
maxLength={6}
<OtpInput
length={6}
value={emailOtp}
autoComplete="off"
onChange={e => setEmailOtp(e.target.value)}
className={styles.input}
required
onChange={setEmailOtp}
inputMode="text"
/>

<button type="button" onClick={onResendEmail} className={styles.resend}>
Expand Down
15 changes: 14 additions & 1 deletion src/views/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const Login: React.FC = () => {
const [identifierError, setIdentifierError] = useState<string>('');
const [passkeyAvailable, setPasskeyAvailable] = useState(false);
const [showFallbackOptions, setShowFallbackOptions] = useState(false);
const [bootstrapToken, setBootstrapToken] = useState<string | null>(null);

const fetchWithAuth = createFetchWithAuth({
authMode,
Expand All @@ -41,6 +42,14 @@ const Login: React.FC = () => {
if (hasSignedInBefore) {
setMode('login');
}

const params = new URLSearchParams(window.location.search);
const token = params.get('bootstrapToken');

if (token && token.length > 10) {
setBootstrapToken(token);
console.log('Bootstrap token detected in URL');
}
}, [hasSignedInBefore]);

const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
Expand Down Expand Up @@ -134,7 +143,11 @@ const Login: React.FC = () => {
try {
const response = await fetchWithAuth(`/registration/register`, {
method: 'POST',
body: JSON.stringify({ email, phone }),
body: JSON.stringify({
email,
phone,
...(bootstrapToken ? { bootstrapToken } : {}),
}),
});

if (!response.ok) {
Expand Down
25 changes: 16 additions & 9 deletions tests/EmailRegistration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ jest.mock('react-router-dom', () => ({
useNavigate: jest.fn(),
}));

jest.mock('@/components/OtpInput', () => (props: any) => (
<input
data-testid="otp-input"
value={props.value}
onChange={e => props.onChange(e.target.value)}
/>
));

describe('EmailRegistration', () => {
const navigate = jest.fn();
const validateToken = jest.fn();
Expand Down Expand Up @@ -57,12 +65,11 @@ describe('EmailRegistration', () => {
test('shows validation error if OTP is not 6 digits', async () => {
render(<EmailRegistration />);

fireEvent.change(screen.getByLabelText(/email verification code/i), {
target: { value: '123' },
fireEvent.change(screen.getByTestId('otp-input'), {
target: { value: 'ABC' },
});

fireEvent.click(screen.getByRole('button', { name: /verify & continue/i }));

expect(screen.getByText(/please enter a valid code/i)).toBeInTheDocument();
});

Expand All @@ -71,8 +78,8 @@ describe('EmailRegistration', () => {

render(<EmailRegistration />);

fireEvent.change(screen.getByLabelText(/email verification code/i), {
target: { value: '123456' },
fireEvent.change(screen.getByTestId('otp-input'), {
target: { value: 'ABCDEF' },
});

await act(async () => {
Expand Down Expand Up @@ -124,8 +131,8 @@ describe('EmailRegistration', () => {
expect(isPasskeySupported).toHaveBeenCalled();
});

fireEvent.change(screen.getByLabelText(/email verification code/i), {
target: { value: '123456' },
fireEvent.change(screen.getByTestId('otp-input'), {
target: { value: 'ABCDEF' },
});

await act(async () => {
Expand All @@ -145,8 +152,8 @@ describe('EmailRegistration', () => {

render(<EmailRegistration />);

fireEvent.change(screen.getByLabelText(/email verification code/i), {
target: { value: '123456' },
fireEvent.change(screen.getByTestId('otp-input'), {
target: { value: 'ABCDEF' },
});

await act(async () => {
Expand Down
File renamed without changes.
12 changes: 0 additions & 12 deletions tests/authProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { AuthProvider, useAuth } from '../src/AuthProvider';
import { createFetchWithAuth } from '../src/fetchWithAuth';

jest.mock('../src/fetchWithAuth');
jest.mock('../src/components/LoadingSpinner', () => () => <div>Loading...</div>);
jest.mock('@/context/InternalAuthContext', () => ({
InternalAuthProvider: ({ children }: any) => <div>{children}</div>,
}));
Expand Down Expand Up @@ -31,17 +30,6 @@ describe('AuthProvider', () => {
jest.clearAllMocks();
});

it('renders loading spinner initially', async () => {
await act(async () => {
render(
<AuthProvider apiHost={apiHost}>
<div>Child</div>
</AuthProvider>
);
});
expect(screen.getByText('Child')).toBeInTheDocument();
});

it('loads user and token successfully', async () => {
mockFetchWithAuthImpl.mockResolvedValueOnce({
ok: true,
Expand Down
18 changes: 0 additions & 18 deletions tests/loadingSpinner.test.tsx

This file was deleted.

Loading