Skip to content

Commit

Permalink
feat(next): add sign in callback route (#348)
Browse files Browse the repository at this point in the history
  • Loading branch information
wangsijie authored Jul 18, 2022
1 parent f17364a commit 80c9e34
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
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();
19 changes: 19 additions & 0 deletions packages/next/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,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 @@ -41,6 +42,7 @@ jest.mock('@logto/node', () =>
navigate(signInUrl);
signIn();
},
handleSignInCallback,
}))
);

Expand Down Expand Up @@ -69,4 +71,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: '/api/sign-in-callback',
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 @@ -21,6 +21,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 80c9e34

Please sign in to comment.