@monocloud/auth-nextjs 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,10 +24,18 @@ type NextMiddlewareResult = NextResponse | Response | null | undefined | void;
24
24
  *
25
25
  * @param request - The incoming Next.js request.
26
26
  * @param event - The Next.js fetch event.
27
- * @param user - The authenticated user object (if available).
28
27
  * @returns A `NextMiddlewareResult` (e.g., a redirect or rewrite) or a Promise resolving to one.
29
28
  */
30
- type NextMiddlewareOnAccessDenied = (request: NextRequest, event: NextFetchEvent, user?: MonoCloudUser) => NextMiddlewareResult | Promise<NextMiddlewareResult>;
29
+ type NextMiddlewareOnAccessDenied = (request: NextRequest, event: NextFetchEvent) => NextMiddlewareResult | Promise<NextMiddlewareResult>;
30
+ /**
31
+ * Handler function triggered when a user is denied access in Next.js Middleware due to group restrictions.
32
+ *
33
+ * @param request - The incoming Next.js request.
34
+ * @param event - The Next.js fetch event.
35
+ * @param user - The authenticated user object.
36
+ * @returns A `NextMiddlewareResult` (e.g., a redirect or rewrite) or a Promise resolving to one.
37
+ */
38
+ type NextMiddlewareOnGroupAccessDenied = (request: NextRequest, event: NextFetchEvent, user: MonoCloudUser) => NextMiddlewareResult | Promise<NextMiddlewareResult>;
31
39
  /**
32
40
  *
33
41
  * ProtectedRouteMatcher can be a combination of the following types.
@@ -111,9 +119,13 @@ interface MonoCloudMiddlewareOptions {
111
119
  */
112
120
  matchAll?: boolean;
113
121
  /**
114
- * A middleware function called when the user is not authenticated or is not a member of the specified groups.
122
+ * A middleware function called when the user is not authenticated.
115
123
  */
116
124
  onAccessDenied?: NextMiddlewareOnAccessDenied;
125
+ /**
126
+ * A middleware function called when the user is authenticated but is not a member of the specified groups.
127
+ */
128
+ onGroupAccessDenied?: NextMiddlewareOnGroupAccessDenied;
117
129
  }
118
130
  /**
119
131
  * A subset of authorization parameters used on client side functions
@@ -141,10 +153,17 @@ type ProtectAppPageOptions = {
141
153
  */
142
154
  returnUrl?: string;
143
155
  /**
144
- * Alternate page handler called when the user is not authenticated or is not a member of the specified groups.
156
+ * Alternate page handler called when the user is not authenticated.
145
157
  */
146
158
  onAccessDenied?: (props: {
147
- user?: MonoCloudUser;
159
+ params?: Record<string, string | string[]>;
160
+ searchParams?: Record<string, string | string[] | undefined>;
161
+ }) => Promise<JSX.Element> | JSX.Element;
162
+ /**
163
+ * Alternate page handler called when the user is authenticated but is not a member of the specified groups.
164
+ */
165
+ onGroupAccessDenied?: (props: {
166
+ user: MonoCloudUser;
148
167
  params?: Record<string, string | string[]>;
149
168
  searchParams?: Record<string, string | string[] | undefined>;
150
169
  }) => Promise<JSX.Element> | JSX.Element;
@@ -173,26 +192,41 @@ type ProtectPagePageOptions<P extends Record<string, any> = Record<string, any>,
173
192
  */
174
193
  returnUrl?: string;
175
194
  /**
176
- * Alternate `getServerSideProps` function called when the user is not authenticated or is not a member of the specified groups.
195
+ * Alternate `getServerSideProps` function called when the user is not authenticated.
177
196
  */
178
197
  onAccessDenied?: ProtectPagePageOnAccessDeniedType<P, Q>;
198
+ /**
199
+ * Alternate `getServerSideProps` function called when the user IS authenticated but is not a member of the specified groups.
200
+ */
201
+ onGroupAccessDenied?: ProtectPagePageOnGroupAccessDeniedType<P, Q>;
179
202
  /**
180
203
  * Authorization parameters to be used during authentication.
181
204
  */
182
205
  authParams?: ExtraAuthParams;
183
206
  } & GroupOptions;
184
207
  /**
185
- * Handler function triggered when a user is denied access in a Pages Router `getServerSideProps` flow.
208
+ * Handler function triggered when a user is not authenticated in a Pages Router `getServerSideProps` flow.
186
209
  *
187
210
  * @typeParam P - The type of the props.
188
211
  * @typeParam Q - The type of the parsed query object.
189
212
  *
190
- * @param context - The server-side props context extended with the optional user object.
213
+ * @param context - The server-side props context
191
214
  *
192
215
  * @returns The result for `getServerSideProps`.
193
216
  */
194
- type ProtectPagePageOnAccessDeniedType<P, Q extends ParsedUrlQuery = ParsedUrlQuery> = (context: GetServerSidePropsContext<Q> & {
195
- user?: MonoCloudUser;
217
+ type ProtectPagePageOnAccessDeniedType<P, Q extends ParsedUrlQuery = ParsedUrlQuery> = (context: GetServerSidePropsContext<Q>) => Promise<GetServerSidePropsResult<P>> | GetServerSidePropsResult<P>;
218
+ /**
219
+ * Handler function triggered when a user is denied access in a Pages Router `getServerSideProps` flow due to group restrictions.
220
+ *
221
+ * @typeParam P - The type of the props.
222
+ * @typeParam Q - The type of the parsed query object.
223
+ *
224
+ * @param context - The server-side props context with the user object.
225
+ *
226
+ * @returns The result for `getServerSideProps`.
227
+ */
228
+ type ProtectPagePageOnGroupAccessDeniedType<P, Q extends ParsedUrlQuery = ParsedUrlQuery> = (context: GetServerSidePropsContext<Q> & {
229
+ user: MonoCloudUser;
196
230
  }) => Promise<GetServerSidePropsResult<P>> | GetServerSidePropsResult<P>;
197
231
  /**
198
232
  * The return type of the `protectPage()` wrapper for Pages Router.
@@ -216,39 +250,64 @@ type ProtectedAppServerComponent = (props: {
216
250
  searchParams?: Record<string, string | string[] | undefined>;
217
251
  }) => Promise<JSX.Element> | JSX.Element;
218
252
  /**
219
- * Handler function triggered when a user is denied access in an App Router API route.
253
+ * Handler function triggered when a user is not authenticated in an App Router API route.
220
254
  *
221
255
  * @param req - The incoming Next.js request.
222
256
  * @param ctx - The App Router context.
223
257
  *
224
- * @param user - The authenticated user object (if available).
258
+ * @returns A Response/NextResponse or Promise resolving to one.
259
+ */
260
+ type AppRouterApiOnAccessDeniedHandler = (req: NextRequest, ctx: AppRouterContext) => Promise<Response> | Response;
261
+ /**
262
+ * Handler function triggered when a user is denied access in an App Router API route due to group restrictions.
263
+ *
264
+ * @param req - The incoming Next.js request.
265
+ * @param ctx - The App Router context.
266
+ * @param user - The authenticated user object.
225
267
  *
226
268
  * @returns A Response/NextResponse or Promise resolving to one.
227
269
  */
228
- type AppRouterApiOnAccessDeniedHandler = (req: NextRequest, ctx: AppRouterContext, user?: MonoCloudUser) => Promise<Response> | Response;
270
+ type AppRouterApiOnGroupAccessDeniedHandler = (req: NextRequest, ctx: AppRouterContext, user: MonoCloudUser) => Promise<Response> | Response;
229
271
  /** Options for App Router `protectApi()` */
230
272
  type ProtectApiAppOptions = {
231
273
  /**
232
- * Alternate app router api handler called when the user is not authenticated or is not a member of the specified groups.
274
+ * Alternate app router api handler called when the user is not authenticated.
233
275
  */
234
276
  onAccessDenied?: AppRouterApiOnAccessDeniedHandler;
277
+ /**
278
+ * Alternate app router api handler called when the user is authenticated but is not a member of the specified groups.
279
+ */
280
+ onGroupAccessDenied?: AppRouterApiOnGroupAccessDeniedHandler;
235
281
  } & GroupOptions;
236
282
  /**
237
- * Handler function triggered when a user is denied access in a Pages Router API route.
283
+ * Handler function triggered when a user is not authenticated in a Pages Router API route.
284
+ *
285
+ * @param req - The incoming Next.js API request.
286
+ * @param res - The Next.js API response.
287
+ *
288
+ * @returns
289
+ */
290
+ type PageRouterApiOnAccessDeniedHandler = (req: NextApiRequest, res: NextApiResponse<any>) => Promise<unknown> | unknown;
291
+ /**
292
+ * Handler function triggered when a user is denied access in a Pages Router API route due to group restrictions.
238
293
  *
239
294
  * @param req - The incoming Next.js API request.
240
295
  * @param res - The Next.js API response.
241
- * @param user - The authenticated user object (if available).
296
+ * @param user - The authenticated user object.
242
297
  *
243
298
  * @returns
244
299
  */
245
- type PageRouterApiOnAccessDeniedHandler = (req: NextApiRequest, res: NextApiResponse<any>, user?: MonoCloudUser) => Promise<unknown> | unknown;
300
+ type PageRouterApiOnGroupAccessDeniedHandler = (req: NextApiRequest, res: NextApiResponse<any>, user: MonoCloudUser) => Promise<unknown> | unknown;
246
301
  /** Options for Page Router `protectApi()` */
247
302
  type ProtectApiPageOptions = {
248
303
  /**
249
- * Alternate page router api handler called when the user is not authenticated or is not a member of the specified groups.
304
+ * Alternate page router api handler called when the user is not authenticated.
250
305
  */
251
306
  onAccessDenied?: PageRouterApiOnAccessDeniedHandler;
307
+ /**
308
+ * Alternate page router api handler called when the user is authenticated but is not a member of the specified groups.
309
+ */
310
+ onGroupAccessDenied?: PageRouterApiOnGroupAccessDeniedHandler;
252
311
  } & GroupOptions;
253
312
  /**
254
313
  * Options for the `protect()` helper function.
@@ -322,7 +381,7 @@ interface RedirectToSignInOptions {
322
381
  */
323
382
  acrValues?: string[];
324
383
  /**
325
- * A hint to the authorization server about the user's identifier
384
+ * A hint to the authorization server about the user's identifier
326
385
  */
327
386
  loginHint?: string;
328
387
  /**
@@ -348,4 +407,4 @@ interface RedirectToSignOutOptions {
348
407
  }
349
408
  //#endregion
350
409
  export { ProtectPagePageOptions as _, GroupOptions as a, RedirectToSignInOptions as b, MonoCloudAuthOptions as c, PageRouterApiOnAccessDeniedHandler as d, ProtectApiAppOptions as f, ProtectPagePageOnAccessDeniedType as g, ProtectOptions as h, ExtraAuthParams as i, MonoCloudMiddlewareOptions as l, ProtectAppPageOptions as m, AppRouterApiOnAccessDeniedHandler as n, IsUserInGroupOptions as o, ProtectApiPageOptions as p, AppRouterPageHandler as r, MonoCloudAuthHandler as s, AppRouterApiHandlerFn as t, NextMiddlewareResult as u, ProtectPagePageReturnType as v, RedirectToSignOutOptions as x, ProtectedAppServerComponent as y };
351
- //# sourceMappingURL=types-DOfZTKa6.d.mts.map
410
+ //# sourceMappingURL=types-CsBjAJce.d.mts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monocloud/auth-nextjs",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "MonoCloud Next.js Authentication SDK",
5
5
  "keywords": [
6
6
  "monocloud",
@@ -57,7 +57,7 @@
57
57
  "dependencies": {
58
58
  "cookie": "1.1.1",
59
59
  "swr": "2.3.8",
60
- "@monocloud/auth-node-core": "0.1.3"
60
+ "@monocloud/auth-node-core": "0.1.4"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@edge-runtime/vm": "5.0.0",
@@ -86,7 +86,7 @@
86
86
  "lint:es": "eslint src tests",
87
87
  "lint:ts": "tsc",
88
88
  "lint": "pnpm run lint:es && pnpm run lint:ts",
89
- "test": "eslint tests && rimraf coverage && vitest --config vitest.node.config.mts --reporter=junit --outputFile=coverage/junit.node.xml && vitest --config vitest.edge.config.mts --reporter=junit --outputFile=coverage/junit.edge.xml && vitest --config vitest.browser.config.mts --reporter=junit --outputFile=coverage/junit.browser.xml && pnpm run report",
89
+ "test": "eslint tests && rimraf coverage && vitest --config vitest.node.config.mts && vitest --config vitest.edge.config.mts && vitest --config vitest.browser.config.mts && pnpm run report",
90
90
  "report": "shx cp ./coverage/browser/coverage-final.json ./coverage/coverage-0.json && shx cp ./coverage/node/coverage-final.json ./coverage/coverage-1.json && shx cp ./coverage/edge/coverage-final.json ./coverage/coverage-2.json && nyc merge ./coverage ./coverage/coverage.json && nyc report --reporter json-summary --reporter html --reporter text -t ./coverage --report-dir ./coverage/summary && npx @monocloud/auth-test-utils check-coverage"
91
91
  }
92
92
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-Be6A2vEn.cjs","names":[],"sources":["../src/client/use-auth.tsx","../src/client/protect.tsx"],"sourcesContent":["'use client';\n\nimport type { MonoCloudUser } from '@monocloud/auth-node-core';\nimport useSWR from 'swr';\n\n/**\n * Authentication State returned by `useAuth` hook.\n */\nexport interface AuthState {\n /**\n * Flag indicating if the authentication state is still loading.\n */\n isLoading: boolean;\n /**\n * Flag indicating if the user is authenticated.\n */\n isAuthenticated: boolean;\n /**\n * Error encountered during authentication, if any.\n */\n error?: Error;\n /**\n * The authenticated user's information, if available.\n */\n user?: MonoCloudUser;\n /**\n * Function to refetch the authentication state.\n *\n */\n refetch: (refresh?: boolean) => void;\n}\n\nconst fetchUser = async (url: string): Promise<MonoCloudUser | undefined> => {\n const res = await fetch(url, { credentials: 'include' });\n\n if (res.status === 204) {\n return undefined;\n }\n\n if (res.ok) {\n return res.json();\n }\n\n throw new Error('Failed to fetch user');\n};\n\n/**\n *\n * Hook for getting the user's profile on client components\n *\n * @returns Authentication State\n *\n * @example App Router\n *\n * ```tsx\n * \"use client\";\n *\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user } = useAuth();\n *\n * return <>User Id: {user?.sub}</>;\n * }\n * ```\n *\n * @example App Router - Refetch user from Userinfo endpoint\n *\n * Calling `refetch(true)` will force refresh the user's profile from the userinfo endpoint.\n * If you do not intent to refersh from your tenants userinfo endpoint, use just `refetch()`\n *\n * **Note⚠️: You need to set the env `MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES=true` or `allowQueryParamOverrides` should be `true` in the client initialization for force refresh to work**\n *\n * ```tsx\n * \"use client\";\n *\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user, refetch } = useAuth();\n *\n * return (\n * <>\n * <pre>{JSON.stringify(user)}</pre>\n * <button onClick={() => refetch(true)}>Refresh</button>\n * </>\n * );\n * }\n * ```\n *\n * @example Pages Router\n *\n * ```tsx\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user } = useAuth();\n *\n * return <>User Id: {user?.sub}</>;\n * }\n * ```\n *\n * @example Pages Router - Refetch user from Userinfo endpoint\n *\n * Calling `refetch(true)` will force refresh the user's profile from the userinfo endpoint.\n * If you do not intent to refersh from your tenants userinfo endpoint, use just `refetch()`\n *\n * **Note⚠️: You need to set the env `MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES=true` or `allowQueryParamOverrides` should be `true` in the client initialization for force refresh to work**\n *\n * ```tsx\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user, refetch } = useAuth();\n *\n * return (\n * <>\n * <pre>{JSON.stringify(user)}</pre>\n * <button onClick={() => refetch(true)}>Refresh</button>\n * </>\n * );\n * }\n * ```\n *\n */\nexport const useAuth = (): AuthState => {\n const key =\n process.env.NEXT_PUBLIC_MONOCLOUD_AUTH_USER_INFO_URL ??\n // eslint-disable-next-line no-underscore-dangle\n `${process.env.__NEXT_ROUTER_BASEPATH ?? ''}/api/auth/userinfo`;\n\n const { data, error, isLoading, mutate } = useSWR<MonoCloudUser | undefined>(\n key,\n fetchUser\n );\n\n const refetch = (refresh?: boolean): void => {\n const url = new URL(key, 'https://dummy');\n if (refresh) {\n url.searchParams.set('refresh', 'true');\n }\n\n void mutate(async () => await fetchUser(url.pathname + url.search), {\n revalidate: false,\n });\n };\n\n if (error) {\n return {\n user: undefined,\n isLoading: false,\n isAuthenticated: false,\n error: error as Error,\n refetch,\n };\n }\n\n if (data) {\n return {\n user: data,\n isLoading,\n isAuthenticated: !!data && Object.keys(data).length > 0,\n error: undefined,\n refetch,\n };\n }\n\n return {\n user: undefined,\n isLoading,\n isAuthenticated: false,\n error: undefined,\n /* v8 ignore next -- @preserve */\n refetch: (): void => {},\n };\n};\n","/* eslint-disable react/display-name */\n'use client';\n\nimport React, { ComponentType, JSX, useEffect } from 'react';\nimport type { MonoCloudUser } from '@monocloud/auth-node-core';\nimport { isUserInGroup } from '@monocloud/auth-node-core/utils';\nimport { useAuth } from './use-auth';\nimport { ExtraAuthParams, GroupOptions } from '../types';\n\n/**\n * Options for configuring page protection.\n */\nexport type ProtectPageOptions = {\n /**\n *The url where the user will be redirected to after sign in\n */\n returnUrl?: string;\n\n /**\n * A custom react element to render when the user is not authenticated or is not a member of the specified groups.\n */\n onAccessDenied?: (user?: MonoCloudUser) => JSX.Element;\n\n /**\n * Authorization parameters to be used during authentication.\n */\n authParams?: ExtraAuthParams;\n\n /**\n * Callback function to handle errors.\n * If not provided, errors will be thrown.\n *\n * @param error - The error object.\n * @returns JSX element to handle the error.\n */\n onError?: (error: Error) => JSX.Element;\n} & GroupOptions;\n\nexport const redirectToSignIn = (\n options: { returnUrl?: string } & ExtraAuthParams\n): void => {\n const searchParams = new URLSearchParams(window.location.search);\n searchParams.set(\n 'return_url',\n options.returnUrl ?? window.location.toString()\n );\n\n if (options?.scopes) {\n searchParams.set('scope', options.scopes);\n }\n if (options?.resource) {\n searchParams.set('resource', options.resource);\n }\n\n if (options?.acrValues) {\n searchParams.set('acr_values', options.acrValues.join(' '));\n }\n\n if (options?.display) {\n searchParams.set('display', options.display);\n }\n\n if (options?.prompt) {\n searchParams.set('prompt', options.prompt);\n }\n\n if (options?.authenticatorHint) {\n searchParams.set('authenticator_hint', options.authenticatorHint);\n }\n\n if (options?.uiLocales) {\n searchParams.set('ui_locales', options.uiLocales);\n }\n\n if (options?.maxAge) {\n searchParams.set('max_age', options.maxAge.toString());\n }\n\n if (options?.loginHint) {\n searchParams.set('login_hint', options.loginHint);\n }\n\n window.location.assign(\n // eslint-disable-next-line no-underscore-dangle\n `${process.env.NEXT_PUBLIC_MONOCLOUD_AUTH_SIGNIN_URL ?? `${process.env.__NEXT_ROUTER_BASEPATH ?? ''}/api/auth/signin`}?${searchParams.toString()}`\n );\n};\n\nconst handlePageError = (\n error: Error,\n options?: ProtectPageOptions\n): JSX.Element => {\n /* v8 ignore else -- @preserve */\n if (options?.onError) {\n return options.onError(error);\n }\n\n /* v8 ignore next -- @preserve */\n throw error;\n};\n\n/**\n * Function to protect a client rendered page component.\n * Ensures that only authenticated users can access the component.\n * \n * **Note⚠️: Since `window.location` is set as `returnUrl` query param by default, you need to set the env `MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES=true` or `allowQueryParamOverrides` should be `true` in the client initialization for returning to the same page.**\n *\n * @param Component - The component to protect.\n * @param options - The options.\n *\n * @returns Protected client rendered page component.\n *\n * @example App Router\n *\n * ```tsx\n * \"use client\";\n *\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(function Home() {\n * return <>You are signed in</>;\n * });\n * ```\n *\n * @example App Router with options\n * \n * See {@link ProtectPageOptions} for more options.\n *\n * ```tsx\n * \"use client\";\n *\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(\n * function Home() {\n * return <>You are signed in</>;\n * },\n * { returnUrl: \"/dashboard\", authParams: { loginHint: \"username\" } }\n * );\n * ```\n\n* @example Pages Router\n *\n * ```tsx\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(function Home() {\n * return <>You are signed in</>;\n * });\n * ```\n *\n * @example Pages Router with options\n * \n * See {@link ProtectPageOptions} for more options.\n *\n * ```tsx\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(\n * function Home() {\n * return <>You are signed in</>;\n * },\n * { returnUrl: \"/dashboard\", authParams: { loginHint: \"username\" } }\n * );\n * ```\n */\nexport const protectPage = <P extends object>(\n Component: ComponentType<P & { user: MonoCloudUser }>,\n options?: ProtectPageOptions\n): React.FC<P> => {\n return props => {\n const { user, error, isLoading } = useAuth();\n\n useEffect(() => {\n if (!user && !isLoading && !error) {\n if (options?.onAccessDenied) {\n return;\n }\n\n const authParams = options?.authParams ?? {};\n redirectToSignIn({\n returnUrl: options?.returnUrl,\n ...authParams,\n });\n }\n }, [user, isLoading, error]);\n\n if (error) {\n return handlePageError(error, options);\n }\n\n if (!user && !isLoading && options?.onAccessDenied) {\n return options.onAccessDenied();\n }\n\n if (user) {\n if (\n options?.groups &&\n !isUserInGroup(\n user,\n options.groups,\n options.groupsClaim ??\n process.env.NEXT_PUBLIC_MONOCLOUD_AUTH_GROUPS_CLAIM,\n options.matchAll\n )\n ) {\n const { onAccessDenied = (): JSX.Element => <div>Access Denied</div> } =\n options;\n return onAccessDenied(user);\n }\n\n return <Component user={user} {...props} />;\n }\n\n return null;\n };\n};\n"],"mappings":";;;;;;;;AAgCA,MAAM,YAAY,OAAO,QAAoD;CAC3E,MAAM,MAAM,MAAM,MAAM,KAAK,EAAE,aAAa,WAAW,CAAC;AAExD,KAAI,IAAI,WAAW,IACjB;AAGF,KAAI,IAAI,GACN,QAAO,IAAI,MAAM;AAGnB,OAAM,IAAI,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFzC,MA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AU,CAAC;AAGxD,uDAAI,QAAS,UACX,cAAa,IAAI,cAAc,QAAQ,UAAU;AAGnD,QAAO,SAAS,OAEd,GAAG,QAAQ,IAAI,yCAAyC,GAAG,QAAQ,IAAI,0BAA0B,GAAG,kBAAkB,GAAG,aAAa,UAAU,GACjJ;;AAGH,MAAM,mBACJ,OACA,YACgB;;AAEhB,uDAAI,QAAS,QACX,QAAO,QAAQ,QAAQ,MAAM;;AAI/B,OAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoER,MAAa,eACX,WACA,YACgB;AAChB,SAAO,UAAS;EACd,MAAM,EAAE,MAAM,OAAO,cAAc,SAAS;AAE5C,6BAAgB;AACd,OAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,OAAO;AACjC,0DAAI,QAAS,eACX;IAGF,MAAM,gEAAa,QAAS,eAAc,EAAE;AAC5C,qBAAiB;KACf,6DAAW,QAAS;KACpB,GAAG;KACJ,CAAC;;KAEH;GAAC;GAAM;GAAW;GAAM,CAAC;AAE5B,MAAI,MACF,QAAO,gBAAgB,OAAO,QAAQ;AAGxC,MAAI,CAAC,QAAQ,CAAC,gEAAa,QAAS,gBAClC,QAAO,QAAQ,gBAAgB;AAGjC,MAAI,MAAM;AACR,0DACE,QAAS,WACT,oDACE,MACA,QAAQ,QACR,QAAQ,eACN,QAAQ,IAAI,yCACd,QAAQ,SACT,EACD;IACA,MAAM,EAAE,uBAAoC,4CAAC,aAAI,gBAAmB,KAClE;AACF,WAAO,eAAe,KAAK;;AAG7B,UAAO,4CAAC;IAAgB;IAAM,GAAI;KAAS;;AAG7C,SAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-CnvBgZM-.mjs","names":[],"sources":["../src/client/use-auth.tsx","../src/client/protect.tsx"],"sourcesContent":["'use client';\n\nimport type { MonoCloudUser } from '@monocloud/auth-node-core';\nimport useSWR from 'swr';\n\n/**\n * Authentication State returned by `useAuth` hook.\n */\nexport interface AuthState {\n /**\n * Flag indicating if the authentication state is still loading.\n */\n isLoading: boolean;\n /**\n * Flag indicating if the user is authenticated.\n */\n isAuthenticated: boolean;\n /**\n * Error encountered during authentication, if any.\n */\n error?: Error;\n /**\n * The authenticated user's information, if available.\n */\n user?: MonoCloudUser;\n /**\n * Function to refetch the authentication state.\n *\n */\n refetch: (refresh?: boolean) => void;\n}\n\nconst fetchUser = async (url: string): Promise<MonoCloudUser | undefined> => {\n const res = await fetch(url, { credentials: 'include' });\n\n if (res.status === 204) {\n return undefined;\n }\n\n if (res.ok) {\n return res.json();\n }\n\n throw new Error('Failed to fetch user');\n};\n\n/**\n *\n * Hook for getting the user's profile on client components\n *\n * @returns Authentication State\n *\n * @example App Router\n *\n * ```tsx\n * \"use client\";\n *\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user } = useAuth();\n *\n * return <>User Id: {user?.sub}</>;\n * }\n * ```\n *\n * @example App Router - Refetch user from Userinfo endpoint\n *\n * Calling `refetch(true)` will force refresh the user's profile from the userinfo endpoint.\n * If you do not intent to refersh from your tenants userinfo endpoint, use just `refetch()`\n *\n * **Note⚠️: You need to set the env `MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES=true` or `allowQueryParamOverrides` should be `true` in the client initialization for force refresh to work**\n *\n * ```tsx\n * \"use client\";\n *\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user, refetch } = useAuth();\n *\n * return (\n * <>\n * <pre>{JSON.stringify(user)}</pre>\n * <button onClick={() => refetch(true)}>Refresh</button>\n * </>\n * );\n * }\n * ```\n *\n * @example Pages Router\n *\n * ```tsx\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user } = useAuth();\n *\n * return <>User Id: {user?.sub}</>;\n * }\n * ```\n *\n * @example Pages Router - Refetch user from Userinfo endpoint\n *\n * Calling `refetch(true)` will force refresh the user's profile from the userinfo endpoint.\n * If you do not intent to refersh from your tenants userinfo endpoint, use just `refetch()`\n *\n * **Note⚠️: You need to set the env `MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES=true` or `allowQueryParamOverrides` should be `true` in the client initialization for force refresh to work**\n *\n * ```tsx\n * import { useAuth } from \"@monocloud/auth-nextjs/client\";\n *\n * export default function Home() {\n * const { user, refetch } = useAuth();\n *\n * return (\n * <>\n * <pre>{JSON.stringify(user)}</pre>\n * <button onClick={() => refetch(true)}>Refresh</button>\n * </>\n * );\n * }\n * ```\n *\n */\nexport const useAuth = (): AuthState => {\n const key =\n process.env.NEXT_PUBLIC_MONOCLOUD_AUTH_USER_INFO_URL ??\n // eslint-disable-next-line no-underscore-dangle\n `${process.env.__NEXT_ROUTER_BASEPATH ?? ''}/api/auth/userinfo`;\n\n const { data, error, isLoading, mutate } = useSWR<MonoCloudUser | undefined>(\n key,\n fetchUser\n );\n\n const refetch = (refresh?: boolean): void => {\n const url = new URL(key, 'https://dummy');\n if (refresh) {\n url.searchParams.set('refresh', 'true');\n }\n\n void mutate(async () => await fetchUser(url.pathname + url.search), {\n revalidate: false,\n });\n };\n\n if (error) {\n return {\n user: undefined,\n isLoading: false,\n isAuthenticated: false,\n error: error as Error,\n refetch,\n };\n }\n\n if (data) {\n return {\n user: data,\n isLoading,\n isAuthenticated: !!data && Object.keys(data).length > 0,\n error: undefined,\n refetch,\n };\n }\n\n return {\n user: undefined,\n isLoading,\n isAuthenticated: false,\n error: undefined,\n /* v8 ignore next -- @preserve */\n refetch: (): void => {},\n };\n};\n","/* eslint-disable react/display-name */\n'use client';\n\nimport React, { ComponentType, JSX, useEffect } from 'react';\nimport type { MonoCloudUser } from '@monocloud/auth-node-core';\nimport { isUserInGroup } from '@monocloud/auth-node-core/utils';\nimport { useAuth } from './use-auth';\nimport { ExtraAuthParams, GroupOptions } from '../types';\n\n/**\n * Options for configuring page protection.\n */\nexport type ProtectPageOptions = {\n /**\n *The url where the user will be redirected to after sign in\n */\n returnUrl?: string;\n\n /**\n * A custom react element to render when the user is not authenticated or is not a member of the specified groups.\n */\n onAccessDenied?: (user?: MonoCloudUser) => JSX.Element;\n\n /**\n * Authorization parameters to be used during authentication.\n */\n authParams?: ExtraAuthParams;\n\n /**\n * Callback function to handle errors.\n * If not provided, errors will be thrown.\n *\n * @param error - The error object.\n * @returns JSX element to handle the error.\n */\n onError?: (error: Error) => JSX.Element;\n} & GroupOptions;\n\nexport const redirectToSignIn = (\n options: { returnUrl?: string } & ExtraAuthParams\n): void => {\n const searchParams = new URLSearchParams(window.location.search);\n searchParams.set(\n 'return_url',\n options.returnUrl ?? window.location.toString()\n );\n\n if (options?.scopes) {\n searchParams.set('scope', options.scopes);\n }\n if (options?.resource) {\n searchParams.set('resource', options.resource);\n }\n\n if (options?.acrValues) {\n searchParams.set('acr_values', options.acrValues.join(' '));\n }\n\n if (options?.display) {\n searchParams.set('display', options.display);\n }\n\n if (options?.prompt) {\n searchParams.set('prompt', options.prompt);\n }\n\n if (options?.authenticatorHint) {\n searchParams.set('authenticator_hint', options.authenticatorHint);\n }\n\n if (options?.uiLocales) {\n searchParams.set('ui_locales', options.uiLocales);\n }\n\n if (options?.maxAge) {\n searchParams.set('max_age', options.maxAge.toString());\n }\n\n if (options?.loginHint) {\n searchParams.set('login_hint', options.loginHint);\n }\n\n window.location.assign(\n // eslint-disable-next-line no-underscore-dangle\n `${process.env.NEXT_PUBLIC_MONOCLOUD_AUTH_SIGNIN_URL ?? `${process.env.__NEXT_ROUTER_BASEPATH ?? ''}/api/auth/signin`}?${searchParams.toString()}`\n );\n};\n\nconst handlePageError = (\n error: Error,\n options?: ProtectPageOptions\n): JSX.Element => {\n /* v8 ignore else -- @preserve */\n if (options?.onError) {\n return options.onError(error);\n }\n\n /* v8 ignore next -- @preserve */\n throw error;\n};\n\n/**\n * Function to protect a client rendered page component.\n * Ensures that only authenticated users can access the component.\n * \n * **Note⚠️: Since `window.location` is set as `returnUrl` query param by default, you need to set the env `MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES=true` or `allowQueryParamOverrides` should be `true` in the client initialization for returning to the same page.**\n *\n * @param Component - The component to protect.\n * @param options - The options.\n *\n * @returns Protected client rendered page component.\n *\n * @example App Router\n *\n * ```tsx\n * \"use client\";\n *\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(function Home() {\n * return <>You are signed in</>;\n * });\n * ```\n *\n * @example App Router with options\n * \n * See {@link ProtectPageOptions} for more options.\n *\n * ```tsx\n * \"use client\";\n *\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(\n * function Home() {\n * return <>You are signed in</>;\n * },\n * { returnUrl: \"/dashboard\", authParams: { loginHint: \"username\" } }\n * );\n * ```\n\n* @example Pages Router\n *\n * ```tsx\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(function Home() {\n * return <>You are signed in</>;\n * });\n * ```\n *\n * @example Pages Router with options\n * \n * See {@link ProtectPageOptions} for more options.\n *\n * ```tsx\n * import { protectPage } from \"@monocloud/auth-nextjs/client\";\n *\n * export default protectPage(\n * function Home() {\n * return <>You are signed in</>;\n * },\n * { returnUrl: \"/dashboard\", authParams: { loginHint: \"username\" } }\n * );\n * ```\n */\nexport const protectPage = <P extends object>(\n Component: ComponentType<P & { user: MonoCloudUser }>,\n options?: ProtectPageOptions\n): React.FC<P> => {\n return props => {\n const { user, error, isLoading } = useAuth();\n\n useEffect(() => {\n if (!user && !isLoading && !error) {\n if (options?.onAccessDenied) {\n return;\n }\n\n const authParams = options?.authParams ?? {};\n redirectToSignIn({\n returnUrl: options?.returnUrl,\n ...authParams,\n });\n }\n }, [user, isLoading, error]);\n\n if (error) {\n return handlePageError(error, options);\n }\n\n if (!user && !isLoading && options?.onAccessDenied) {\n return options.onAccessDenied();\n }\n\n if (user) {\n if (\n options?.groups &&\n !isUserInGroup(\n user,\n options.groups,\n options.groupsClaim ??\n process.env.NEXT_PUBLIC_MONOCLOUD_AUTH_GROUPS_CLAIM,\n options.matchAll\n )\n ) {\n const { onAccessDenied = (): JSX.Element => <div>Access Denied</div> } =\n options;\n return onAccessDenied(user);\n }\n\n return <Component user={user} {...props} />;\n }\n\n return null;\n };\n};\n"],"mappings":";;;;;AAgCA,MAAM,YAAY,OAAO,QAAoD;CAC3E,MAAM,MAAM,MAAM,MAAM,KAAK,EAAE,aAAa,WAAW,CAAC;AAExD,KAAI,IAAI,WAAW,IACjB;AAGF,KAAI,IAAI,GACN,QAAO,IAAI,MAAM;AAGnB,OAAM,IAAI,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFzC,MAAa,gBAA2B;CACtC,MAAM,MACJ,QAAQ,IAAI,4CAEZ,GAAG,QAAQ,IAAI,0BAA0B,GAAG;CAE9C,MAAM,EAAE,MAAM,OAAO,WAAW,WAAW,OACzC,KACA,UACD;CAED,MAAM,WAAW,YAA4B;EAC3C,MAAM,MAAM,IAAI,IAAI,KAAK,gBAAgB;AACzC,MAAI,QACF,KAAI,aAAa,IAAI,WAAW,OAAO;AAGzC,EAAK,OAAO,YAAY,MAAM,UAAU,IAAI,WAAW,IAAI,OAAO,EAAE,EAClE,YAAY,OACb,CAAC;;AAGJ,KAAI,MACF,QAAO;EACL,MAAM;EACN,WAAW;EACX,iBAAiB;EACV;EACP;EACD;AAGH,KAAI,KACF,QAAO;EACL,MAAM;EACN;EACA,iBAAiB,CAAC,CAAC,QAAQ,OAAO,KAAK,KAAK,CAAC,SAAS;EACtD,OAAO;EACP;EACD;AAGH,QAAO;EACL,MAAM;EACN;EACA,iBAAiB;EACjB,OAAO;EAEP,eAAqB;EACtB;;;;;ACxIH,MAAa,oBACX,YACS;CACT,MAAM,eAAe,IAAI,gBAAgB,OAAO,SAAS,OAAO;AAChE,cAAa,IACX,cACA,QAAQ,aAAa,OAAO,SAAS,U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