Skip to content

Commit

Permalink
fix: await on parse cookie result to work around #271
Browse files Browse the repository at this point in the history
  • Loading branch information
awinogrodzki committed Nov 6, 2024
1 parent 3e4af80 commit f6b5106
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 75 deletions.
4 changes: 2 additions & 2 deletions examples/next-typescript-starter/config/server-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ export const authConfig = {
},
serviceAccount: serverConfig.serviceAccount,
// Set to false in Firebase Hosting environment due to https://stackoverflow.com/questions/44929653/firebase-cloud-function-wont-store-cookie-named-other-than-session
enableMultipleCookies: false,
enableMultipleCookies: true,
// Set to false if you're not planning to use `signInWithCustomToken` Firebase Client SDK method
enableCustomToken: false,
enableCustomToken: true,
experimental_enableTokenRefreshOnExpiredKidHeader: true,
debug: true,
tenantId: clientConfig.tenantId
Expand Down
107 changes: 39 additions & 68 deletions examples/next-typescript-starter/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,81 +6,52 @@ import {
redirectToLogin
} from 'next-firebase-auth-edge';
import {authConfig} from './config/server-config';
import {
InvalidTokenError,
InvalidTokenReason
} from 'next-firebase-auth-edge/auth';

const PUBLIC_PATHS = ['/register', '/login', '/reset-password'];

async function iWillThrowAnError() {
throw new InvalidTokenError(InvalidTokenReason.INVALID_KID);
}

export async function middleware(request: NextRequest) {
console.log('REQUEST START', request.nextUrl.pathname);

try {
await iWillThrowAnError();
} catch (error) {
console.log("I didn't throw nothing!", {error: {...(error as Error)}});
}
return authMiddleware(request, {
loginPath: '/api/login',
logoutPath: '/api/logout',
refreshTokenPath: '/api/refresh-token',
debug: authConfig.debug,
enableMultipleCookies: authConfig.enableMultipleCookies,
enableCustomToken: authConfig.enableCustomToken,
apiKey: authConfig.apiKey,
cookieName: authConfig.cookieName,
cookieSerializeOptions: authConfig.cookieSerializeOptions,
cookieSignatureKeys: authConfig.cookieSignatureKeys,
serviceAccount: authConfig.serviceAccount,
experimental_enableTokenRefreshOnExpiredKidHeader:
authConfig.experimental_enableTokenRefreshOnExpiredKidHeader,
tenantId: authConfig.tenantId,
handleValidToken: async ({token, decodedToken, customToken}, headers) => {
// Authenticated user should not be able to access /login, /register and /reset-password routes
if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) {
return redirectToHome(request);
}

try {
console.log('BEFORE RUN MIDDLEWARE', request.nextUrl.pathname);
const response = await authMiddleware(request, {
loginPath: '/api/login',
logoutPath: '/api/logout',
refreshTokenPath: '/api/refresh-token',
debug: authConfig.debug,
enableMultipleCookies: authConfig.enableMultipleCookies,
enableCustomToken: authConfig.enableCustomToken,
apiKey: authConfig.apiKey,
cookieName: authConfig.cookieName,
cookieSerializeOptions: authConfig.cookieSerializeOptions,
cookieSignatureKeys: authConfig.cookieSignatureKeys,
serviceAccount: authConfig.serviceAccount,
experimental_enableTokenRefreshOnExpiredKidHeader:
authConfig.experimental_enableTokenRefreshOnExpiredKidHeader,
tenantId: authConfig.tenantId,
handleValidToken: async ({token, decodedToken, customToken}, headers) => {
// Authenticated user should not be able to access /login, /register and /reset-password routes
if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) {
return redirectToHome(request);
return NextResponse.next({
request: {
headers
}
});
},
handleInvalidToken: async (_reason) => {
return redirectToLogin(request, {
path: '/login',
publicPaths: PUBLIC_PATHS
});
},
handleError: async (error) => {
console.error('Unhandled authentication error', {error});

return NextResponse.next({
request: {
headers
}
});
},
handleInvalidToken: async (_reason) => {
console.log('HANDLE INVALID TOKEN');
return redirectToLogin(request, {
path: '/login',
publicPaths: PUBLIC_PATHS
});
},
handleError: async (error) => {
console.log('HANDLE ERROR');
return redirectToLogin(request, {
path: '/login',
publicPaths: PUBLIC_PATHS
});
}
});
console.log('RESPONSE GENERATED');
return response;
} catch (error) {
console.log('ERROR RESULTED FROM AUTH MIDDLEWARE', {
error: error?.toString(),
errorConstructorName: error?.constructor.name,
invalidTokenErrorConstructorName: InvalidTokenError.constructor.name,
InvalidTokenError
});
throw error;
}
return redirectToLogin(request, {
path: '/login',
publicPaths: PUBLIC_PATHS
});
}
});
}

export const config = {
Expand Down
2 changes: 1 addition & 1 deletion examples/next-typescript-starter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"firebase": "^10.4.0",
"firebase-admin": "^11.10.1",
"next": "15.0.0-rc.0",
"next-firebase-auth-edge": "1.8.2-canary.7",
"next-firebase-auth-edge": "1.8.2-canary.8",
"react": "19.0.0-rc-f994737d14-20240522",
"react-dom": "19.0.0-rc-f994737d14-20240522",
"react-loading-hook": "1.1.2",
Expand Down
8 changes: 4 additions & 4 deletions examples/next-typescript-starter/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3122,10 +3122,10 @@ natural-compare@^1.4.0:
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==

next-firebase-auth-edge@1.8.2-canary.7:
version "1.8.2-canary.7"
resolved "https://registry.yarnpkg.com/next-firebase-auth-edge/-/next-firebase-auth-edge-1.8.2-canary.7.tgz#0a7e120bd8089862c4f012fde4b2c2337cddfb6a"
integrity sha512-Mpqh9mmQzBqxN3qsjnEnmE4t8uQxUwCiZKZ3VTVsTborEsMs1Xf88MQ+tMtJ6+uBqmg/9HthMO1p4i34v/q09A==
next-firebase-auth-edge@1.8.2-canary.8:
version "1.8.2-canary.8"
resolved "https://registry.yarnpkg.com/next-firebase-auth-edge/-/next-firebase-auth-edge-1.8.2-canary.8.tgz#7e21e44b180e2402b1bf6b57590fb7ed0f2ecdfa"
integrity sha512-hLAuimIZShJJDw3Pg+v6xE3r+e+MJhQo9ncyfRek0yFqxYXnzzc51LHY8Zozc3fMAyd5/SgnRHVUYsl1LR5kxw==
dependencies:
cookie "^0.7.0"
encoding "^0.1.13"
Expand Down

0 comments on commit f6b5106

Please sign in to comment.