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(react): auto handle callback #92

Merged
merged 2 commits into from
Nov 11, 2021
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
28 changes: 21 additions & 7 deletions packages/react/src/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,42 @@ export const LogtoProvider = ({ logtoConfig, children }: LogtoProviderProperties
const createClient = async () => {
try {
const client = await LogtoClient.create(logtoConfig);
dispatch({ type: 'INITIALIZE', isAuthenticated: client.isAuthenticated() });
setLogtoClient(client);
const isLoginRedirect = client.isLoginRedirect(window.location.href);
// If is login redirect, should set isLoading and isInitialized at the same time
dispatch({
type: 'INITIALIZE',
payload: {
isAuthenticated: client.isAuthenticated(),
isLoading: isLoginRedirect,
},
});
} catch (error: unknown) {
dispatch({ type: 'ERROR', error });
dispatch({ type: 'ERROR', payload: { error } });
}
};

void createClient();
}, [logtoConfig]);

useEffect(() => {
if (logtoClient?.isLoginRedirect(window.location.href)) {
void handleCallback(window.location.href);
}
}, [logtoClient]);

const loginWithRedirect = useCallback(
async (redirectUri: string) => {
if (!logtoClient) {
dispatch({ type: 'ERROR', error: new Error('Should init first') });
dispatch({ type: 'ERROR', payload: { error: new Error('Should init first') } });
return;
}

dispatch({ type: 'LOGIN_WITH_REDIRECT' });
try {
await logtoClient.loginWithRedirect(redirectUri);
} catch (error: unknown) {
dispatch({ type: 'ERROR', error });
dispatch({ type: 'ERROR', payload: { error } });
}
},
[logtoClient]
Expand All @@ -48,7 +62,7 @@ export const LogtoProvider = ({ logtoConfig, children }: LogtoProviderProperties
const handleCallback = useCallback(
async (uri: string) => {
if (!logtoClient) {
dispatch({ type: 'ERROR', error: new Error('Should init first') });
dispatch({ type: 'ERROR', payload: { error: new Error('Should init first') } });
return;
}

Expand All @@ -57,7 +71,7 @@ export const LogtoProvider = ({ logtoConfig, children }: LogtoProviderProperties
await logtoClient.handleCallback(uri);
dispatch({ type: 'HANDLE_CALLBACK_SUCCESS' });
} catch (error: unknown) {
dispatch({ type: 'ERROR', error });
dispatch({ type: 'ERROR', payload: { error } });
}
},
[logtoClient]
Expand All @@ -66,7 +80,7 @@ export const LogtoProvider = ({ logtoConfig, children }: LogtoProviderProperties
const logout = useCallback(
(redirectUri: string) => {
if (!logtoClient) {
dispatch({ type: 'ERROR', error: new Error('Should init first') });
dispatch({ type: 'ERROR', payload: { error: new Error('Should init first') } });
return;
}

Expand Down
14 changes: 10 additions & 4 deletions packages/react/src/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { AuthState } from './auth-state';

type Action =
| { type: 'INITIALIZE'; isAuthenticated: boolean }
| { type: 'INITIALIZE'; payload: { isAuthenticated: boolean; isLoading: boolean } }
| { type: 'LOGIN_WITH_REDIRECT' }
| { type: 'HANDLE_CALLBACK_REQUEST' }
| { type: 'HANDLE_CALLBACK_SUCCESS' }
| { type: 'LOGOUT' }
| { type: 'ERROR'; error: unknown };
| { type: 'ERROR'; payload: { error: unknown } };

export const reducer = (state: AuthState, action: Action): AuthState => {
if (action.type === 'INITIALIZE') {
return { ...state, isInitialized: true, isAuthenticated: action.isAuthenticated };
const { isAuthenticated, isLoading } = action.payload;
return {
...state,
isInitialized: true,
isAuthenticated,
isLoading,
};
}

if (action.type === 'LOGIN_WITH_REDIRECT') {
Expand All @@ -30,7 +36,7 @@ export const reducer = (state: AuthState, action: Action): AuthState => {
}

if (action.type === 'ERROR') {
const { error } = action;
const { error } = action.payload;
if (!(error instanceof Error)) {
throw error;
}
Expand Down
44 changes: 43 additions & 1 deletion packages/react/src/use-logto.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import { LogtoProvider } from './provider';
import useLogto from './use-logto';

const isAuthenticated = jest.fn();
const isLoginRedirect = jest.fn();
const handleCallback = jest.fn(async () => Promise.resolve());

jest.mock('@logto/client', () => {
const Mocked = jest.fn(() => {
return {
isAuthenticated,
handleCallback: jest.fn(),
handleCallback,
logout: jest.fn(),
isLoginRedirect,
};
});
return {
Expand All @@ -22,6 +25,8 @@ jest.mock('@logto/client', () => {

afterEach(() => {
isAuthenticated.mockClear();
isLoginRedirect.mockClear();
handleCallback.mockClear();
});

const DOMAIN = 'logto.dev';
Expand Down Expand Up @@ -58,6 +63,7 @@ describe('useLogto', () => {
expect(isInitialized).toBeTruthy();
});
expect(isAuthenticated).toBeFalsy();
expect(result.current.error).toBeUndefined();
});

test('change from not authenticated to authenticated', async () => {
Expand All @@ -75,6 +81,7 @@ describe('useLogto', () => {
expect(isLoading).toBeFalsy();
});
expect(result.current.isAuthenticated).toBeTruthy();
expect(result.current.error).toBeUndefined();
});

test('change from authenticated to not authenticated', async () => {
Expand All @@ -96,5 +103,40 @@ describe('useLogto', () => {
result.current.logout('url');
});
expect(result.current.isAuthenticated).toBeFalsy();
expect(result.current.error).toBeUndefined();
});

describe('auto handle callback', () => {
test('not in callback url should not call `handleCallback`', async () => {
isLoginRedirect.mockImplementation(() => false);
const { result, waitFor } = renderHook(() => useLogto(), {
wrapper: createHookWrapper(),
});
await waitFor(() => {
const { isInitialized } = result.current;
expect(isInitialized).toBeTruthy();
});
expect(handleCallback).not.toHaveBeenCalled();
expect(result.current.error).toBeUndefined();
});

test('in callback url should call `handleCallback`, and isLoading should be true before complete', async () => {
isLoginRedirect.mockImplementation(() => true);
const { result, waitFor } = renderHook(() => useLogto(), {
wrapper: createHookWrapper(),
});
await waitFor(() => {
const { isInitialized, isLoading } = result.current;
expect(isInitialized).toBeTruthy();
expect(isLoading).toBeTruthy();
});
await waitFor(() => {
const { isAuthenticated } = result.current;
expect(isAuthenticated).toBeTruthy();
});
expect(result.current.error).toBeUndefined();
expect(handleCallback).toHaveBeenCalledTimes(1);
expect(result.current.isLoading).toBeFalsy();
});
});
});