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: handle callback error #64

Merged
merged 1 commit into from
Oct 29, 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
30 changes: 26 additions & 4 deletions packages/client/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ const CLIENT_ID = 'client1';
const SUBJECT = 'subject1';
const REDIRECT_URI = 'http://localhost:3000';
const SESSEION_MANAGER_KEY = 'LOGTO_SESSION_MANAGER';
const REDIRECT_CALLBACK = `${REDIRECT_URI}?code=authorization_code`;
const REDIRECT_CALLBACK_WITH_ERROR = `${REDIRECT_CALLBACK}&error=invalid_request&error_description=code_challenge%20must%20be%20a%20string%20with%20a%20minimum%20length%20of%2043%20characters`;

const discoverResponse = {
authorization_endpoint: `${BASE_URL}/oidc/auth`,
Expand Down Expand Up @@ -170,7 +172,27 @@ describe('LogtoClient', () => {
clientId: CLIENT_ID,
storage,
});
await expect(logto.handleCallback('code')).rejects.toThrowError();
await expect(logto.handleCallback(REDIRECT_CALLBACK)).rejects.toThrowError();
});

test('no code in url should fail', async () => {
const storage = new MemoryStorage();
const logto = await LogtoClient.create({
domain: DOMAIN,
clientId: CLIENT_ID,
storage,
});
await expect(logto.handleCallback('')).rejects.toThrowError();
});

test('should throw response error', async () => {
const storage = new MemoryStorage();
const logto = await LogtoClient.create({
domain: DOMAIN,
clientId: CLIENT_ID,
storage,
});
await expect(logto.handleCallback(REDIRECT_CALLBACK_WITH_ERROR)).rejects.toThrowError();
});

test('verifyIdToken should be called', async () => {
Expand All @@ -181,7 +203,7 @@ describe('LogtoClient', () => {
storage,
});
await logto.loginWithRedirect(REDIRECT_URI);
await logto.handleCallback('code');
await logto.handleCallback(REDIRECT_CALLBACK);
expect(verifyIdToken).toHaveBeenCalled();
});

Expand All @@ -193,7 +215,7 @@ describe('LogtoClient', () => {
storage,
});
await logto.loginWithRedirect(REDIRECT_URI);
await logto.handleCallback('code');
await logto.handleCallback(REDIRECT_CALLBACK);
expect(storage.getItem('LOGTO_SESSION_MANAGER')).toBeUndefined();
});

Expand All @@ -205,7 +227,7 @@ describe('LogtoClient', () => {
storage,
});
await logto.loginWithRedirect(REDIRECT_URI);
await logto.handleCallback('code');
await logto.handleCallback(REDIRECT_CALLBACK);
expect(logto.isAuthenticated()).toBeTruthy();
});
});
Expand Down
13 changes: 12 additions & 1 deletion packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Optional } from '@silverhand/essentials';

import discover, { OIDCConfiguration } from './discover';
import { grantTokenByAuthorizationCode, TokenSetParameters } from './grant-token';
import { parseRedirectCallback } from './parse-callback';
import { getLoginUrlAndCodeVerifier } from './request-login';
import { getLogoutUrl } from './request-logout';
import SessionManager from './session-manager';
Expand Down Expand Up @@ -57,7 +58,17 @@ export default class LogtoClient {
window.location.assign(url);
}

public async handleCallback(code: string) {
public async handleCallback(url: string) {
const { code, error, error_description } = parseRedirectCallback(url);

if (error) {
throw new Error(error_description ?? error);
}

if (!code) {
throw new Error(`Can not found authorization_code in url: ${url}`);
}

const session = this.sessionManager.get();

if (!session) {
Expand Down
16 changes: 16 additions & 0 deletions packages/client/src/parse-callback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { parseRedirectCallback } from './parse-callback';

describe('parseRedirectCallback', () => {
test('get result', () => {
const url =
'http://localhost:3000/callback?code=random-code&error=error&error_description=some%20description';
const result = parseRedirectCallback(url);
expect(result.code).toEqual('random-code');
expect(result.error).toEqual('error');
expect(result.error_description).toEqual('some description');
});

test('no query params should fail', () => {
expect(() => parseRedirectCallback('http://localhost:3000')).toThrow();
});
});
18 changes: 18 additions & 0 deletions packages/client/src/parse-callback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import qs from 'query-string';

export interface AuthenticationResult {
code?: string;
error?: string;
error_description?: string;
}

export const parseRedirectCallback = (url: string) => {
const [, queryString] = url.split('?');
if (!queryString) {
throw new Error('There are no query params available for parsing.');
}

const result = qs.parse(queryString) as AuthenticationResult;

return result;
};