Skip to content

Commit

Permalink
feat(backend-core,edge): Add requireEdgeMiddlewareAuth
Browse files Browse the repository at this point in the history
  • Loading branch information
igneel64 committed Jul 7, 2022
1 parent 4e42a11 commit 9ce6a4e
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,33 @@ exports[`module exports should not change unless explicitly set 1`] = `
Object {
"API_KEY": "TEST_API_KEY",
"AllowlistIdentifier": [Function],
"AuthErrorReason": Object {
"CookieAndUATMissing": "cookie-and-uat-missing",
"CookieEarly": "cookie-early",
"CookieExpired": "cookie-expired",
"CookieInvalid": "cookie-invalid",
"CookieInvalidIssuer": "cookie-invalid-issuer",
"CookieMissing": "cookie-missing",
"CookieOutDated": "cookie-outdated",
"CookieUnauthorizedParty": "cookie-unauthorized-party",
"CookieVerificationFailed": "cookie-verification-failed",
"CrossOriginReferrer": "cross-origin-referrer",
"HeaderEarly": "header-early",
"HeaderExpired": "header-expired",
"HeaderInvalid": "header-invalid",
"HeaderInvalidIssuer": "header-invalid-issuer",
"HeaderMissingCORS": "header-missing-cors",
"HeaderMissingNonBrowser": "header-missing-non-browser",
"HeaderUnauthorizedParty": "header-unauthorized-party",
"HeaderVerificationFailed": "header-verification-failed",
"InlineKeyInvalid": "inline-key-invalid",
"InlineKeyMissing": "inline-key-missing",
"InternalError": "internal-error",
"PublicKeyFetchError": "pk-fetch-error",
"StandardOut": "standard-out",
"UATMissing": "uat-missing",
"Unknown": "unknown",
},
"AuthStatus": Object {
"Interstitial": "Interstitial",
"SignedIn": "Signed in",
Expand Down
2 changes: 1 addition & 1 deletion packages/backend-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export * from './Base';
export * from './api/ClerkBackendAPI';
export * from './api/resources';
export { createGetToken, createSignedOutState } from './util/createGetToken';
export { AuthStatus } from './types';
export { AuthStatus, AuthErrorReason } from './types';
export type { ClerkFetcher } from './api/utils/RestClient';
export type { Session } from './api/resources/Session';
export type { Nullable } from './util/nullable';
33 changes: 28 additions & 5 deletions packages/edge/src/vercel-edge/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AuthStatus, Base, createGetToken, createSignedOutState } from '@clerk/backend-core';
import { ClerkJWTClaims } from '@clerk/types';
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server';
import { NextFetchEvent, NextRequest } from 'next/server';

import { ClerkAPI } from './ClerkAPI';
import {
Expand All @@ -10,6 +10,7 @@ import {
WithEdgeMiddlewareAuthOptions,
} from './types';
import { injectAuthIntoRequest } from './utils';
import { interstitialResponse, signedOutResponse } from './utils/responses';

/**
*
Expand Down Expand Up @@ -68,6 +69,27 @@ export function withEdgeMiddlewareAuth<
): WithEdgeMiddlewareAuthMiddlewareResult<CallbackReturn, Options>;

export function withEdgeMiddlewareAuth(
handler: any,
options: any = {
loadSession: false,
loadUser: false,
strict: false,
},
): any {
return vercelMiddlewareAuth(handler, { strict: false, ...options });
}

export function requireEdgeMiddlewareAuth(
handler: any,
options: any = {
loadSession: false,
loadUser: false,
},
): any {
return vercelMiddlewareAuth(handler, { strict: true, ...options });
}

function vercelMiddlewareAuth(
handler: any,
options: any = {
loadSession: false,
Expand Down Expand Up @@ -97,13 +119,14 @@ export function withEdgeMiddlewareAuth(
});

if (status === AuthStatus.Interstitial) {
return new NextResponse(interstitial, {
headers: { 'Content-Type': 'text/html', 'Auth-Result': errorReason || '' },
status: 401,
});
return interstitialResponse(interstitial as string, errorReason);
}

if (status === AuthStatus.SignedOut) {
if (options.strict) {
return signedOutResponse();
}

const response = (await handler(
injectAuthIntoRequest(req, createSignedOutState()),
event,
Expand Down
1 change: 1 addition & 0 deletions packages/edge/src/vercel-edge/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export type WithEdgeMiddlewareAuthOptions = {
loadSession?: boolean;
authorizedParties?: string[];
jwtKey?: string;
strict?: boolean;
};

export type WithEdgeMiddlewareAuthCallback<Return, Options> = (
Expand Down
16 changes: 16 additions & 0 deletions packages/edge/src/vercel-edge/utils/responses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { AuthErrorReason } from '@clerk/backend-core';
import { NextResponse } from 'next/server';

export function signedOutResponse() {
return new NextResponse(JSON.stringify({ error: 'Unauthenticated' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}

export function interstitialResponse(interstitial: string, errorReason?: AuthErrorReason) {
return new NextResponse(interstitial, {
headers: { 'Content-Type': 'text/html', 'Auth-Result': errorReason || '' },
status: 401,
});
}
1 change: 1 addition & 0 deletions packages/nextjs/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ let exportLib;
if (process.env.NEXT_RUNTIME === 'edge') {
exportLib = require('./dist/edge-middleware');
exportLib.withAuth = exportLib.withEdgeMiddlewareAuth;
exportLib.requireAuth = exportLib.requireEdgeMiddlewareAuth;
} else {
exportLib = require('./dist/api');
}
Expand Down

0 comments on commit 9ce6a4e

Please sign in to comment.