Skip to content

Commit

Permalink
feat(next): add sign in callback route
Browse files Browse the repository at this point in the history
  • Loading branch information
wangsijie committed Jul 15, 2022
1 parent 87822f9 commit 5f5ddc7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
3 changes: 3 additions & 0 deletions packages/next-sample/pages/api/sign-in-callback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { logtoClient } from '../../libraries/logto';

export default logtoClient.handleSignInCallback();
21 changes: 20 additions & 1 deletion packages/next/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const setItem = jest.fn((key, value) => {
const getItem = jest.fn();
const save = jest.fn();
const signIn = jest.fn();
const handleSignInCallback = jest.fn();

jest.mock('./storage', () =>
jest.fn(() => ({
Expand All @@ -45,6 +46,7 @@ jest.mock('@logto/node', () =>
navigate(signInUrl);
signIn();
},
handleSignInCallback,
}))
);

Expand All @@ -62,7 +64,7 @@ describe('Next', () => {
const client = new LogtoClient(configs);
await testApiHandler({
handler: client.handleSignIn(),
url: '/api/sign-in',
url: configs.signInEndpoint,
test: async ({ fetch }) => {
const response = await fetch({ method: 'GET', redirect: 'manual' });
const headers = response.headers as Map<string, string>;
Expand All @@ -73,4 +75,21 @@ describe('Next', () => {
expect(signIn).toHaveBeenCalled();
});
});

describe('handleSignInCallback', () => {
it('should call client.handleSignInCallback and redirect to home', async () => {
const client = new LogtoClient(configs);
await testApiHandler({
handler: client.handleSignInCallback(),
url: configs.signInCallbackEndpoint,
test: async ({ fetch }) => {
const response = await fetch({ method: 'GET', redirect: 'manual' });
const headers = response.headers as Map<string, string>;
expect(headers.get('location')).toEqual(`${configs.baseUrl}/`);
},
});
expect(handleSignInCallback).toHaveBeenCalled();
expect(save).toHaveBeenCalled();
});
});
});
11 changes: 11 additions & 0 deletions packages/next/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ export default class LogtoClient {
}
});

handleSignInCallback = (redirectTo = this.config.baseUrl): NextApiHandler =>
this.withIronSession(async (request, response) => {
const nodeClient = this.createNodeClient(request);

if (request.url) {
await nodeClient.handleSignInCallback(`${this.config.baseUrl}${request.url}`);
await this.storage?.save();
response.redirect(redirectTo);
}
});

private createNodeClient(request: NextApiRequest) {
this.storage = new NextStorage(request);

Expand Down

0 comments on commit 5f5ddc7

Please sign in to comment.