UNPKG

@clerk/nextjs

Version:

Clerk SDK for NextJS

1 lines 7.18 kB
{"version":3,"sources":["../../../../src/app-router/server/auth.ts"],"sourcesContent":["import type { AuthObject } from '@clerk/backend';\nimport { constants, createClerkRequest, createRedirect, type RedirectFun } from '@clerk/backend/internal';\nimport { notFound, redirect } from 'next/navigation';\n\nimport { PUBLISHABLE_KEY, SIGN_IN_URL, SIGN_UP_URL } from '../../server/constants';\nimport { createAsyncGetAuth } from '../../server/createGetAuth';\nimport { authAuthHeaderMissing } from '../../server/errors';\nimport { getAuthKeyFromRequest, getHeader } from '../../server/headers-utils';\nimport type { AuthProtect } from '../../server/protect';\nimport { createProtect } from '../../server/protect';\nimport { decryptClerkRequestData } from '../../server/utils';\nimport { isNextWithUnstableServerActions } from '../../utils/sdk-versions';\nimport { buildRequestLike } from './utils';\n\n/**\n * `Auth` object of the currently active user and the `redirectToSignIn()` method.\n */\ntype Auth = AuthObject & {\n /**\n * The `auth()` helper returns the `redirectToSignIn()` method, which you can use to redirect the user to the sign-in page.\n *\n * @param [returnBackUrl] {string | URL} - The URL to redirect the user back to after they sign in.\n *\n * @note\n * `auth()` on the server-side can only access redirect URLs defined via [environment variables](https://clerk.com/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) or [`clerkMiddleware` dynamic keys](https://clerk.com/docs/references/nextjs/clerk-middleware#dynamic-keys).\n */\n redirectToSignIn: RedirectFun<ReturnType<typeof redirect>>;\n};\n\nexport interface AuthFn {\n (): Promise<Auth>;\n\n /**\n * `auth` includes a single property, the `protect()` method, which you can use in two ways:\n * - to check if a user is authenticated (signed in)\n * - to check if a user is authorized (has the correct roles or permissions) to access something, such as a component or a route handler\n *\n * The following table describes how auth.protect() behaves based on user authentication or authorization status:\n *\n * | Authenticated | Authorized | `auth.protect()` will |\n * | - | - | - |\n * | Yes | Yes | Return the [`Auth`](https://clerk.com/docs/references/backend/types/auth-object) object. |\n * | Yes | No | Return a `404` error. |\n * | No | No | Redirect the user to the sign-in page\\*. |\n *\n * @important\n * \\*For non-document requests, such as API requests, `auth.protect()` returns a `404` error to users who aren't authenticated.\n *\n * `auth.protect()` can be used to check if a user is authenticated or authorized to access certain parts of your application or even entire routes. See detailed examples in the [dedicated guide](https://clerk.com/docs/organizations/verify-user-permissions).\n */\n protect: AuthProtect;\n}\n\n/**\n * The `auth()` helper returns the [`Auth`](https://clerk.com/docs/references/backend/types/auth-object) object of the currently active user, as well as the [`redirectToSignIn()`](https://clerk.com/docs/references/nextjs/auth#redirect-to-sign-in) method.\n *\n * - Only available for App Router.\n * - Only works on the server-side, such as in Server Components, Route Handlers, and Server Actions.\n * - Requires [`clerkMiddleware()`](https://clerk.com/docs/references/nextjs/clerk-middleware) to be configured.\n */\nexport const auth: AuthFn = async () => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require('server-only');\n\n const request = await buildRequestLike();\n\n const stepsBasedOnSrcDirectory = async () => {\n if (isNextWithUnstableServerActions) {\n return [];\n }\n\n try {\n const isSrcAppDir = await import('../../server/fs/middleware-location.js').then(m => m.hasSrcAppDir());\n return [`Your Middleware exists at ./${isSrcAppDir ? 'src/' : ''}middleware.(ts|js)`];\n } catch {\n return [];\n }\n };\n const authObject = await createAsyncGetAuth({\n debugLoggerName: 'auth()',\n noAuthStatusMessage: authAuthHeaderMissing('auth', await stepsBasedOnSrcDirectory()),\n })(request);\n\n const clerkUrl = getAuthKeyFromRequest(request, 'ClerkUrl');\n\n const redirectToSignIn: RedirectFun<never> = (opts = {}) => {\n const clerkRequest = createClerkRequest(request);\n const devBrowserToken =\n clerkRequest.clerkUrl.searchParams.get(constants.QueryParameters.DevBrowser) ||\n clerkRequest.cookies.get(constants.Cookies.DevBrowser);\n\n const encryptedRequestData = getHeader(request, constants.Headers.ClerkRequestData);\n const decryptedRequestData = decryptClerkRequestData(encryptedRequestData);\n\n return createRedirect({\n redirectAdapter: redirect,\n devBrowserToken: devBrowserToken,\n baseUrl: clerkRequest.clerkUrl.toString(),\n publishableKey: decryptedRequestData.publishableKey || PUBLISHABLE_KEY,\n signInUrl: decryptedRequestData.signInUrl || SIGN_IN_URL,\n signUpUrl: decryptedRequestData.signUpUrl || SIGN_UP_URL,\n }).redirectToSignIn({\n returnBackUrl: opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkUrl?.toString(),\n });\n };\n\n return Object.assign(authObject, { redirectToSignIn });\n};\n\nauth.protect = async (...args: any[]) => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require('server-only');\n\n const request = await buildRequestLike();\n const authObject = await auth();\n\n const protect = createProtect({\n request,\n authObject,\n redirectToSignIn: authObject.redirectToSignIn,\n notFound,\n redirect,\n });\n\n return protect(...args);\n};\n"],"mappings":";AACA,SAAS,WAAW,oBAAoB,sBAAwC;AAChF,SAAS,UAAU,gBAAgB;AAEnC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,0BAA0B;AACnC,SAAS,6BAA6B;AACtC,SAAS,uBAAuB,iBAAiB;AAEjD,SAAS,qBAAqB;AAC9B,SAAS,+BAA+B;AACxC,SAAS,uCAAuC;AAChD,SAAS,wBAAwB;AAgD1B,MAAM,OAAe,YAAY;AAEtC,UAAQ,aAAa;AAErB,QAAM,UAAU,MAAM,iBAAiB;AAEvC,QAAM,2BAA2B,YAAY;AAC3C,QAAI,iCAAiC;AACnC,aAAO,CAAC;AAAA,IACV;AAEA,QAAI;AACF,YAAM,cAAc,MAAM,OAAO,wCAAwC,EAAE,KAAK,OAAK,EAAE,aAAa,CAAC;AACrG,aAAO,CAAC,+BAA+B,cAAc,SAAS,EAAE,oBAAoB;AAAA,IACtF,QAAQ;AACN,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AACA,QAAM,aAAa,MAAM,mBAAmB;AAAA,IAC1C,iBAAiB;AAAA,IACjB,qBAAqB,sBAAsB,QAAQ,MAAM,yBAAyB,CAAC;AAAA,EACrF,CAAC,EAAE,OAAO;AAEV,QAAM,WAAW,sBAAsB,SAAS,UAAU;AAE1D,QAAM,m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