Skip to content
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
12 changes: 6 additions & 6 deletions packages/nextjs/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,16 @@ const refreshTokenEmbedded = async (headers: Record<string, string>) => {
*/
const refreshTokenHostedLogin = async (
headers: Record<string, string>,
refresh_token: string,
cliendId?: string,
refreshToken: string,
clientId?: string,
clientSecret?: string
) => {
return Post({
url: `${config.baseUrl}${CommonUrls.refreshToken.hosted}`,
body: JSON.stringify({
grant_type: 'refresh_token',
refresh_token,
client_id: cliendId,
refresh_token: refreshToken,
client_id: clientId,
client_secret: clientSecret,
}),
headers: buildRequestHeaders(headers),
Expand Down Expand Up @@ -132,7 +132,7 @@ export const getMeAuthorization = async (
headers: Record<string, string>
): Promise<IGetUserAuthorizationResponse | undefined> => {
const res = await Get({
//TODO: replace this with rest/api route
// TODO: replace this with rest/api route
url: `${config.baseUrl}/frontegg/identity/resources/users/v1/me/authorization`,
headers: buildRequestHeaders(headers),
});
Expand All @@ -143,7 +143,7 @@ export const getPublicSettings = async (
headers: Record<string, string>
): Promise<IPublicSettingsResponse | undefined> => {
const res = await Get({
//TODO: export the route url from rest-api and import from there
// TODO: export the route url from rest-api and import from there
url: `${config.baseUrl}/frontegg/tenants/resources/account-settings/v1/public`,
headers: buildRequestHeaders(headers),
});
Expand Down
6 changes: 5 additions & 1 deletion packages/nextjs/src/edge/shouldBypassMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { defaultFronteggRoutes } from '../utils/routing';
const staticFilesRegex = new RegExp('^/(_next/static).*');
const imageOptimizationRegex = new RegExp('^/(_next/image).*');
const headerRequestsRegex = new RegExp('^/(favicon.ico).*');
const willKnownRequestsRegex = new RegExp('^/(.well-known)/.*');
Comment thread
frontegg-david marked this conversation as resolved.
const fronteggMiddlewareRegex = new RegExp('^/(api/frontegg).*');

interface ByPassOptions {
Expand Down Expand Up @@ -36,6 +37,7 @@ export const shouldByPassMiddleware = (
bypassStaticFiles: true,
bypassImageOptimization: true,
bypassHeaderRequests: true,
bypassWillKnownRoutes: true,
...options,
bypassFronteggMiddleware: true,
bypassFronteggRoutes: true,
Expand All @@ -45,6 +47,7 @@ export const shouldByPassMiddleware = (
const isStaticFiles = staticFilesRegex.test(pathname);
const isImageOptimization = imageOptimizationRegex.test(pathname);
const isHeaderRequests = headerRequestsRegex.test(pathname);
const isWillKnownRoutes = willKnownRequestsRegex.test(pathname);
const isFronteggMiddleware = fronteggMiddlewareRegex.test(pathname);

const { authenticatedUrl, ...authRoutes } = defaultFronteggRoutes;
Expand All @@ -54,6 +57,7 @@ export const shouldByPassMiddleware = (
if (isImageOptimization) return _options.bypassImageOptimization;
if (isHeaderRequests) return _options.bypassHeaderRequests;
if (isFronteggMiddleware) return _options.bypassFronteggMiddleware;
if (isWillKnownRoutes) return _options.bypassWillKnownRoutes;
if (isFronteggRoutes) return _options.bypassFronteggRoutes;

const isPrefetchRequest = headers.has('next-router-prefetch') || headers.get('purpose') === 'prefetch';
Expand All @@ -65,7 +69,7 @@ export const shouldByPassMiddleware = (

// noinspection RedundantIfStatementJS
if (isPrefetchRequest && !isBrowserAddressBarPrefetch) {
/** bypass prefetch requests on hovering links that leads to SSG pages **/
/* bypass prefetch requests on hovering links that leads to SSG pages */
return true;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { IncomingHttpHeaders } from 'http';
import fronteggLogger from '../../utils/fronteggLogger';

const nextJsFilesRegex = new RegExp('^/(_next/).*');
const headerRequestsRegex = new RegExp('^/(favicon.ico).*');
const willKnownRequestsRegex = new RegExp('^/(.well-known)/.*');

interface ByPassOptions {
bypassNextJsFiles?: boolean;
bypassWillKnownRoutes?: boolean; // default: true
bypassHeaderRequests?: boolean; // default: true
}

/**
* Use `shouldBypassGetInitialProps` in the withFronteggApp.ts file
* to protect all application's routes.
* You can override whitelist by passing options parameter
* NOTE: this will slow down your application due to session check on each
* static files and image request
*/
export const shouldBypassGetInitialProps = (
pathname: string,
headers?: IncomingHttpHeaders,
options?: ByPassOptions
): boolean => {
const logger = fronteggLogger.child({ tag: 'shouldBypassGetInitialProps' });
const _options = {
bypassNextJsFiles: true,
bypassHeaderRequests: true,
bypassWillKnownRoutes: true,
...options,
};

const isNextJsFiles = nextJsFilesRegex.test(pathname);
const isHeaderRequests = headerRequestsRegex.test(pathname);
const isWillKnownRoutes = willKnownRequestsRegex.test(pathname);

logger.debug(`${pathname}`, { options, checks: { isNextJsFiles, isHeaderRequests, isWillKnownRoutes } });

if (isNextJsFiles) return _options.bypassNextJsFiles;
if (isHeaderRequests) return _options.bypassHeaderRequests;
if (isWillKnownRoutes) return _options.bypassWillKnownRoutes;

if (!headers) {
return false;
}
const isPrefetchRequest = headers['next-router-prefetch'] || headers.purpose === 'prefetch';
const secFetchModeHeader = headers['sec-fetch-mode'];
const secFetchDestHeader = headers['sec-fetch-dest'];

const isBrowserAddressBarPrefetch =
isPrefetchRequest && secFetchModeHeader === 'navigate' && secFetchDestHeader === 'document';

// noinspection RedundantIfStatementJS
if (isPrefetchRequest && !isBrowserAddressBarPrefetch) {
return true;
}

return false;
};
17 changes: 14 additions & 3 deletions packages/nextjs/src/pages/withFronteggApp/withFronteggApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,34 @@ import fetchUserData from '../../utils/fetchUserData';
import config from '../../config';
import { AllUserData } from '../../types';
import { removeJwtSignatureFrom } from '../../middleware/helpers';
import { shouldBypassGetInitialProps } from './shouldBypassGetInitialProps';
import fronteggLogger from '../../utils/fronteggLogger';

export const withFronteggApp = (app: FronteggCustomAppClass, options?: WithFronteggAppOptions): FronteggCustomApp => {
const originalGetInitialProps = app.getInitialProps;

app.getInitialProps = async (appContext: AppContext & AllUserData): Promise<AppInitialProps> => {
const { ctx, router, Component } = appContext;

const logger = fronteggLogger.child({ tag: 'withFronteggApp' });
const isSSG = router.isReady == false && router.isPreview == false;

config.checkHostedLoginConfig(options);

let appEnvConfig = {};
let appContextSessionData: AllUserData = {
const appContextSessionData: AllUserData = {
session: null,
user: null,
tenants: null,
};
if (shouldBypassGetInitialProps(ctx.req?.url ?? '/', ctx.req?.headers)) {
logger.debug('Bypassing get initial props for url: ' + (ctx.req?.url ?? ''));
return {
pageProps: {
...(originalGetInitialProps ? await originalGetInitialProps(appContext) : {}),
...(Component.getInitialProps ? await Component.getInitialProps(ctx) : {}),
},
};
}

let shouldRequestAuthorize = false;

if (ctx.req) {
Expand Down
13 changes: 4 additions & 9 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4107,15 +4107,10 @@ camelcase@^6.2.0:
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.3.0.tgz#5685b95eb209ac9c0c177467778c9c84df58ba9a"
integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==

caniuse-lite@^1.0.30001406, caniuse-lite@^1.0.30001449, caniuse-lite@^1.0.30001669:
version "1.0.30001712"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001712.tgz"
integrity sha512-MBqPpGYYdQ7/hfKiet9SCI+nmN5/hp4ZzveOJubl5DTAMa5oggjAuoi0Z4onBpKPFI2ePGnQuQIzF3VxDjDJig==

caniuse-lite@^1.0.30001579:
version "1.0.30001715"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001715.tgz#bd325a37ad366e3fe90827d74062807a34fbaeb2"
integrity sha512-7ptkFGMm2OAOgvZpwgA4yjQ5SQbrNVGdRjzH0pBdy1Fasvcr+KAeECmbCAECzTuDuoX0FCY8KzUxjf9+9kfZEw==
caniuse-lite@^1.0.30001406, caniuse-lite@^1.0.30001449, caniuse-lite@^1.0.30001579, caniuse-lite@^1.0.30001669:
version "1.0.30001751"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001751.tgz"
integrity sha512-A0QJhug0Ly64Ii3eIqHu5X51ebln3k4yTUkY1j8drqpWHVreg/VLijN48cZ1bYPiqOQuqpkIKnzr/Ul8V+p6Cw==

chalk@4.1.0, chalk@^4.0.0, chalk@^4.1.0:
version "4.1.0"
Expand Down
Loading