Skip to content

Commit

Permalink
fix: merge cookieOptions correctly. (#33)
Browse files Browse the repository at this point in the history
* fix: merge cookieOptions correctly.

* chore: update changelog.
  • Loading branch information
thorwebdev authored Mar 9, 2022
1 parent ad3c71a commit 2f800f6
Show file tree
Hide file tree
Showing 9 changed files with 39 additions and 17 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## 1.2.1 - 2022-03-09

- [#33](https://github.com/supabase-community/supabase-auth-helpers/pull/33): fix: merge cookieOptions correctly.

## 1.2.0 - 2022-03-01

- [BREAKING CHANGE][#32](https://github.com/supabase-community/supabase-auth-helpers/pull/32): feat: add logout api route. Note that this includes a breaking change to the options parameter for `handleAuth(options: HandleAuthOptions)` See [the docs](./src/nextjs/README.md#basic-setup) for more details.
Expand Down
5 changes: 4 additions & 1 deletion examples/nextjs/pages/api/auth/[...supabase].ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { handleAuth } from '@supabase/supabase-auth-helpers/nextjs';

export default handleAuth({ logout: { returnTo: '/' } });
export default handleAuth({
logout: { returnTo: '/signin' },
cookieOptions: { lifetime: 1 * 365 * 24 * 60 * 60 } // Keep the user logged in for a year.
});
3 changes: 2 additions & 1 deletion src/nextjs/handlers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ export interface HandleAuthOptions {

export default function handleAuth(options: HandleAuthOptions = {}) {
return async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const { cookieOptions = COOKIE_OPTIONS, logout } = options;
const { logout } = options;
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };
let {
query: { supabase: route }
} = req;
Expand Down
2 changes: 1 addition & 1 deletion src/nextjs/handlers/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default function handelCallback(
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
const { cookieOptions = COOKIE_OPTIONS } = options;
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };
const { event, session } = req.body;

if (!event) throw new Error('Auth event missing!');
Expand Down
2 changes: 1 addition & 1 deletion src/nextjs/handlers/logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default function handleLogout(
if (!returnTo) returnTo = options?.returnTo ?? '/';
returnTo = Array.isArray(returnTo) ? returnTo[0] : returnTo;
returnTo = returnTo.charAt(0) === '/' ? returnTo : `/${returnTo}`;
const { cookieOptions = COOKIE_OPTIONS } = options;
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };

// Logout request to Gotrue
const access_token = req.cookies[`${cookieOptions.name}-access-token`];
Expand Down
6 changes: 3 additions & 3 deletions src/nextjs/handlers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default async function handleUser(
if (!req.cookies) {
throw new Error('Not able to parse cookies!');
}
const { cookieOptions = COOKIE_OPTIONS } = options;
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };
const access_token = req.cookies[`${cookieOptions.name}-access-token`];

if (!access_token) {
Expand All @@ -32,7 +32,7 @@ export default async function handleUser(
const timeNow = Math.round(Date.now() / 1000);
if (jwtUser.exp < timeNow) {
// JWT is expired, let's refresh from Gotrue
const response = await getUser({ req, res }, cookieOptions);
const response = await getUser({ req, res }, { cookieOptions });
res.status(200).json(response);
} else {
// Transform JWT and add note that it ise cached from JWT.
Expand All @@ -59,7 +59,7 @@ export default async function handleUser(
} catch (e) {
const error = e as ApiError;
res
.status(400)
.status(200)
.json({ user: null, accessToken: null, error: error.message });
}
}
12 changes: 8 additions & 4 deletions src/nextjs/utils/getAccessToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,22 @@ import {
import getUser from './getUser';
import { jwtDecoder } from '../../shared/utils/jwt';
import { CookieOptions } from '../types';
import { COOKIE_OPTIONS } from '../../shared/utils/constants';

export interface GetAccessTokenOptions {
cookieOptions?: CookieOptions;
}

export default async function getAccessToken(
context:
| GetServerSidePropsContext
| { req: NextApiRequest; res: NextApiResponse },
cookieOptions: CookieOptions = {
name: 'sb'
}
options: GetAccessTokenOptions = {}
): Promise<string | null> {
if (!context.req.cookies) {
throw new Error('Not able to parse cookies!');
}
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };
const access_token =
context.req.cookies[`${cookieOptions.name}-access-token`];

Expand All @@ -33,7 +37,7 @@ export default async function getAccessToken(
const timeNow = Math.round(Date.now() / 1000);
if (jwtUser.exp < timeNow) {
// JWT is expired, let's refresh from Gotrue
const { accessToken } = await getUser(context, cookieOptions);
const { accessToken } = await getUser(context, { cookieOptions });
return accessToken;
} else {
return access_token;
Expand Down
7 changes: 6 additions & 1 deletion src/nextjs/utils/getUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@ import {
NextResponseAdapter
} from '../../shared/adapters/NextAdapter';

export interface GetUserOptions {
cookieOptions?: CookieOptions;
}

export default async function getUser(
context:
| GetServerSidePropsContext
| { req: NextApiRequest; res: NextApiResponse },
cookieOptions: CookieOptions = COOKIE_OPTIONS
options: GetUserOptions = {}
): Promise<{ user: User | null; accessToken: string | null }> {
try {
if (
Expand All @@ -35,6 +39,7 @@ export default async function getUser(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
);
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };
const access_token =
context.req.cookies[`${cookieOptions.name}-access-token`];
const refresh_token =
Expand Down
15 changes: 10 additions & 5 deletions src/nextjs/utils/withAuthRequired.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,16 @@ export type WithAuthRequiredArg =

export default function withAuthRequired(
arg?: WithAuthRequiredArg,
cookieOptions = COOKIE_OPTIONS
options: { cookieOptions?: CookieOptions } = {}
) {
if (typeof arg === 'function') {
return async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
try {
const accessToken = await getAccessToken({ req, res }, cookieOptions);
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };
const accessToken = await getAccessToken(
{ req, res },
{ cookieOptions }
);
if (!accessToken) throw new Error('No access token!');
await arg(req, res);
} catch (error) {
Expand All @@ -98,16 +102,17 @@ export default function withAuthRequired(
}
};
} else {
const {
let {
getServerSideProps = undefined,
redirectTo = '/',
cookieOptions = COOKIE_OPTIONS
cookieOptions = {}
} = arg ? arg : {};
return async (context: GetServerSidePropsContext) => {
try {
if (!context.req.cookies) {
throw new Error('Not able to parse cookies!');
}
cookieOptions = { ...COOKIE_OPTIONS, ...cookieOptions };
const access_token =
context.req.cookies[`${cookieOptions.name}-access-token`];
if (!access_token) {
Expand All @@ -123,7 +128,7 @@ export default function withAuthRequired(
const timeNow = Math.round(Date.now() / 1000);
if (jwtUser.exp < timeNow) {
// JWT is expired, let's refresh from Gotrue
const response = await getUser(context, cookieOptions);
const response = await getUser(context, { cookieOptions });
user = response.user;
accessToken = response.accessToken;
} else {
Expand Down

0 comments on commit 2f800f6

Please sign in to comment.