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(next): handleAuthRoutes #367

Merged
merged 1 commit into from
Jul 25, 2022
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
3 changes: 3 additions & 0 deletions packages/next-sample/pages/api/logto/[action].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { logtoClient } from '../../../libraries/logto';

export default logtoClient.handleAuthRoutes();
3 changes: 0 additions & 3 deletions packages/next-sample/pages/api/sign-in-callback.ts

This file was deleted.

3 changes: 0 additions & 3 deletions packages/next-sample/pages/api/sign-in.ts

This file was deleted.

3 changes: 0 additions & 3 deletions packages/next-sample/pages/api/sign-out.ts

This file was deleted.

3 changes: 0 additions & 3 deletions packages/next-sample/pages/api/user.ts

This file was deleted.

6 changes: 3 additions & 3 deletions packages/next-sample/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useMemo } from 'react';
import useSWR from 'swr';

const Home = () => {
const { data } = useSWR<LogtoUser>('/api/user');
const { data } = useSWR<LogtoUser>('/api/logto/user');
const { data: protectedResource } = useSWR<{ data: string }>('/api/protected-resource');

const userInfo = useMemo(() => {
Expand Down Expand Up @@ -42,11 +42,11 @@ const Home = () => {
</header>
<nav>
{data?.isAuthenticated ? (
<Link href="/api/sign-out">
<Link href="/api/logto/sign-out">
<a>Sign Out</a>
</Link>
) : (
<Link href="/api/sign-in">
<Link href="/api/logto/sign-in">
<a>Sign In</a>
</Link>
)}
Expand Down
2 changes: 1 addition & 1 deletion packages/next-sample/pages/profile-ssr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const getServerSideProps = logtoClient.withLogtoSsr(async function ({ req
const { user } = req;

if (!user.isAuthenticated) {
res.setHeader('location', '/api/login');
res.setHeader('location', '/api/logto/login');
// eslint-disable-next-line @silverhand/fp/no-mutation
res.statusCode = 302;
res.end();
Expand Down
2 changes: 1 addition & 1 deletion packages/next-sample/pages/protected.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const Protected = () => {
useEffect(() => {
if (error?.message === 'Unauthorized') {
// eslint-disable-next-line @silverhand/fp/no-mutating-methods
void Router.push('/api/sign-in');
void Router.push('/api/logto/sign-in');
}
}, [error]);

Expand Down
77 changes: 74 additions & 3 deletions packages/next/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { NextApiResponse } from 'next';
import { testApiHandler } from 'next-test-api-route-handler';

import LogtoClient from '.';
Expand Down Expand Up @@ -26,6 +27,10 @@ const getIdTokenClaims = jest.fn(() => ({
const signOut = jest.fn();
const getAccessToken = jest.fn(async () => true);

const mockResponse = (_: unknown, response: NextApiResponse) => {
response.status(200).end();
};

jest.mock('./storage', () =>
jest.fn(() => ({
setItem,
Expand Down Expand Up @@ -72,7 +77,7 @@ describe('Next', () => {
const client = new LogtoClient(configs);
await testApiHandler({
handler: client.handleSignIn(),
url: '/api/sign-in',
url: '/api/logto/sign-in',
test: async ({ fetch }) => {
const response = await fetch({ method: 'GET', redirect: 'manual' });
const headers = response.headers as Map<string, string>;
Expand All @@ -89,7 +94,7 @@ describe('Next', () => {
const client = new LogtoClient(configs);
await testApiHandler({
handler: client.handleSignInCallback(),
url: '/api/sign-in-callback',
url: '/api/logto/sign-in-callback',
test: async ({ fetch }) => {
const response = await fetch({ method: 'GET', redirect: 'manual' });
const headers = response.headers as Map<string, string>;
Expand Down Expand Up @@ -142,7 +147,7 @@ describe('Next', () => {
const client = new LogtoClient(configs);
await testApiHandler({
handler: client.handleSignOut(),
url: '/api/sign-out',
url: '/api/logto/sign-out',
test: async ({ fetch }) => {
const response = await fetch({ method: 'GET', redirect: 'manual' });
const headers = response.headers as Map<string, string>;
Expand All @@ -153,4 +158,70 @@ describe('Next', () => {
expect(signOut).toHaveBeenCalled();
});
});

describe('handleAuthRoutes', () => {
it('should call handleSignIn for "sign-in"', async () => {
const client = new LogtoClient(configs);
jest.spyOn(client, 'handleSignIn').mockImplementation(() => mockResponse);
await testApiHandler({
handler: client.handleAuthRoutes(),
paramsPatcher: (parameters) => {
// eslint-disable-next-line @silverhand/fp/no-mutation
parameters.action = 'sign-in';
},
test: async ({ fetch }) => {
await fetch({ method: 'GET', redirect: 'manual' });
expect(client.handleSignIn).toHaveBeenCalled();
},
});
});

it('should call handleSignInCallback for "sign-in-callback"', async () => {
const client = new LogtoClient(configs);
jest.spyOn(client, 'handleSignInCallback').mockImplementation(() => mockResponse);
await testApiHandler({
handler: client.handleAuthRoutes(),
paramsPatcher: (parameters) => {
// eslint-disable-next-line @silverhand/fp/no-mutation
parameters.action = 'sign-in-callback';
},
test: async ({ fetch }) => {
await fetch({ method: 'GET', redirect: 'manual' });
expect(client.handleSignInCallback).toHaveBeenCalled();
},
});
});

it('should call handleSignOut for "sign-out"', async () => {
const client = new LogtoClient(configs);
jest.spyOn(client, 'handleSignOut').mockImplementation(() => mockResponse);
await testApiHandler({
handler: client.handleAuthRoutes(),
paramsPatcher: (parameters) => {
// eslint-disable-next-line @silverhand/fp/no-mutation
parameters.action = 'sign-out';
},
test: async ({ fetch }) => {
await fetch({ method: 'GET', redirect: 'manual' });
expect(client.handleSignOut).toHaveBeenCalled();
},
});
});

it('should call handleUser for "user"', async () => {
const client = new LogtoClient(configs);
jest.spyOn(client, 'handleUser').mockImplementation(() => mockResponse);
await testApiHandler({
handler: client.handleAuthRoutes(),
paramsPatcher: (parameters) => {
// eslint-disable-next-line @silverhand/fp/no-mutation
parameters.action = 'user';
},
test: async ({ fetch }) => {
await fetch({ method: 'GET', redirect: 'manual' });
expect(client.handleUser).toHaveBeenCalled();
},
});
});
});
});
28 changes: 27 additions & 1 deletion packages/next/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ export default class LogtoClient {
private storage?: NextStorage;
constructor(private readonly config: LogtoNextConfig) {}

handleSignIn = (redirectUri = `${this.config.baseUrl}/api/sign-in-callback`): NextApiHandler =>
handleSignIn = (
redirectUri = `${this.config.baseUrl}/api/logto/sign-in-callback`
): NextApiHandler =>
withIronSessionApiRoute(async (request, response) => {
const nodeClient = this.createNodeClient(request);
await nodeClient.signIn(redirectUri);
Expand Down Expand Up @@ -54,6 +56,30 @@ export default class LogtoClient {
response.json(request.user);
}, config);

handleAuthRoutes =
(configs?: WithLogtoConfig): NextApiHandler =>
(request, response) => {
const { action } = request.query;

if (action === 'sign-in') {
return this.handleSignIn()(request, response);
}

if (action === 'sign-in-callback') {
return this.handleSignInCallback()(request, response);
}

if (action === 'sign-out') {
return this.handleSignOut()(request, response);
}

if (action === 'user') {
return this.handleUser(configs)(request, response);
}

response.status(404).end();
};

withLogtoApiRoute = (handler: NextApiHandler, config: WithLogtoConfig = {}): NextApiHandler =>
withIronSessionApiRoute(async (request, response) => {
const user = await this.getLogtoUserFromRequest(request, config.getAccessToken);
Expand Down