@cabin-id/nextjs 0.0.1 → 0.1.1

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.
Files changed (74) hide show
  1. package/dist/cjs/client/provider.js +10 -11
  2. package/dist/cjs/client/provider.js.map +1 -1
  3. package/dist/cjs/client/request.js +43 -0
  4. package/dist/cjs/client/request.js.map +1 -0
  5. package/dist/cjs/component.client.js +30 -0
  6. package/dist/cjs/component.client.js.map +1 -1
  7. package/dist/cjs/components/SignInButton.js +1 -1
  8. package/dist/cjs/components/SignInButton.js.map +1 -1
  9. package/dist/cjs/constants.js +1 -1
  10. package/dist/cjs/constants.js.map +1 -1
  11. package/dist/cjs/package.json +9 -0
  12. package/dist/cjs/server/getCurrentUser.js.map +1 -1
  13. package/dist/cjs/server/middleware.js +21 -25
  14. package/dist/cjs/server/middleware.js.map +1 -1
  15. package/dist/cjs/types.js.map +1 -1
  16. package/dist/esm/client/provider.js +10 -11
  17. package/dist/esm/client/provider.js.map +1 -1
  18. package/dist/esm/client/request.js +19 -0
  19. package/dist/esm/client/request.js.map +1 -0
  20. package/dist/esm/component.client.js +6 -0
  21. package/dist/esm/component.client.js.map +1 -1
  22. package/dist/esm/components/SignInButton.js +1 -1
  23. package/dist/esm/components/SignInButton.js.map +1 -1
  24. package/dist/esm/constants.js +1 -1
  25. package/dist/esm/constants.js.map +1 -1
  26. package/dist/esm/package.json +9 -0
  27. package/dist/esm/server/getCurrentUser.js.map +1 -1
  28. package/dist/esm/server/middleware.js +24 -26
  29. package/dist/esm/server/middleware.js.map +1 -1
  30. package/dist/types/api/getUserInfo.d.ts +2 -0
  31. package/dist/types/client/provider.d.ts +7 -0
  32. package/dist/types/client/provider.d.ts.map +1 -1
  33. package/dist/types/client/request.d.ts +3 -0
  34. package/dist/types/client/request.d.ts.map +1 -0
  35. package/dist/types/component.client.d.ts +3 -0
  36. package/dist/types/component.client.d.ts.map +1 -1
  37. package/dist/types/component.server.d.ts +2 -0
  38. package/dist/types/components/SignInButton.d.ts +3 -0
  39. package/dist/types/components/index.d.ts +2 -0
  40. package/dist/types/constants.d.ts +68 -0
  41. package/dist/types/constants.d.ts.map +1 -1
  42. package/dist/types/hooks/index.d.ts +2 -0
  43. package/dist/types/hooks/useUser.d.ts +2 -0
  44. package/dist/types/hooks/useUser.d.ts.map +1 -1
  45. package/dist/types/icons/logo.d.ts +3 -0
  46. package/dist/types/index.d.ts +7 -0
  47. package/dist/types/server/auth.d.ts +4 -0
  48. package/dist/types/server/createRedirect.d.ts +21 -0
  49. package/dist/types/server/getCurrentUser.d.ts +3 -0
  50. package/dist/types/server/getCurrentUser.d.ts.map +1 -1
  51. package/dist/types/server/middleware.d.ts +88 -0
  52. package/dist/types/server/middleware.d.ts.map +1 -1
  53. package/dist/types/server/routeMatcher.d.ts +10 -0
  54. package/dist/types/server/serverRedirectWithAuth.d.ts +2 -0
  55. package/dist/types/server/type.d.ts +5 -0
  56. package/dist/types/server/utils.d.ts +10 -0
  57. package/dist/types/types.d.ts +36 -0
  58. package/dist/types/types.d.ts.map +1 -1
  59. package/dist/types/utils/assertValidSecretKey.d.ts +2 -0
  60. package/dist/types/utils/isomorphicAtob.d.ts +6 -0
  61. package/dist/types/utils/isomorphicBtoa.d.ts +2 -0
  62. package/dist/types/utils/key.d.ts +5 -0
  63. package/dist/types/utils/path.d.ts +4 -0
  64. package/dist/types/utils/response.d.ts +13 -0
  65. package/dist/types/utils.d.ts +4 -0
  66. package/package.json +4 -5
  67. package/dist/cjs/global.d.js +0 -17
  68. package/dist/cjs/global.d.js.map +0 -1
  69. package/dist/cjs/styles/global.css +0 -334
  70. package/dist/cjs/styles/global.css.map +0 -1
  71. package/dist/esm/global.d.js +0 -1
  72. package/dist/esm/global.d.js.map +0 -1
  73. package/dist/esm/styles/global.css +0 -334
  74. package/dist/esm/styles/global.css.map +0 -1
@@ -33,21 +33,20 @@ __export(provider_exports, {
33
33
  });
34
34
  module.exports = __toCommonJS(provider_exports);
35
35
  var import_react = __toESM(require("react"));
36
- var import_constants = require("../constants");
36
+ var import_request = require("./request");
37
37
  const CabinIDContext = import_react.default.createContext({
38
- signInUrl: "",
39
38
  user: null
40
39
  });
41
40
  const CabinIDProvider = ({ children }) => {
42
- const [user] = import_react.default.useState(null);
43
- const signInUrl = import_constants.frontendApi || "";
44
- const redirectUrl = import_constants.CUSTOM_AFTER_SIGN_IN_URL;
45
- if (!redirectUrl) {
46
- throw new Error(
47
- "You must provide the NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL environment variable."
48
- );
49
- }
50
- return /* @__PURE__ */ import_react.default.createElement(CabinIDContext.Provider, { value: { user, signInUrl } }, children);
41
+ const [user, setState] = import_react.default.useState(null);
42
+ import_react.default.useEffect(() => {
43
+ fetchUser();
44
+ }, []);
45
+ const fetchUser = async () => {
46
+ const user2 = await (0, import_request.getCurrentUser)();
47
+ setState(user2);
48
+ };
49
+ return /* @__PURE__ */ import_react.default.createElement(CabinIDContext.Provider, { value: { user } }, children);
51
50
  };
52
51
  // Annotate the CommonJS export names for ESM import in node:
53
52
  0 && (module.exports = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/client/provider.tsx"],"sourcesContent":["import React from 'react';\nimport type { PropsWithChildren } from 'react';\nimport { CabinIDProviderProps, CabinIDUser } from '../types';\nimport { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from '../constants';\n\nexport const CabinIDContext = React.createContext<CabinIDProviderProps>({\n signInUrl: '',\n user: null,\n});\n\nconst CabinIDProvider = ({ children }: PropsWithChildren<any>) => {\n const [user] = React.useState<CabinIDUser | null>(null);\n const signInUrl = frontendApi || '';\n\n const redirectUrl = CUSTOM_AFTER_SIGN_IN_URL;\n\n if (!redirectUrl) {\n throw new Error(\n 'You must provide the NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL environment variable.'\n );\n }\n\n return (\n <CabinIDContext.Provider value={{ user, signInUrl }}>\n {children}\n </CabinIDContext.Provider>\n );\n};\n\nexport { CabinIDProvider };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAGlB,uBAAsD;AAE/C,MAAM,iBAAiB,aAAAA,QAAM,cAAoC;AAAA,EACtE,WAAW;AAAA,EACX,MAAM;AACR,CAAC;AAED,MAAM,kBAAkB,CAAC,EAAE,SAAS,MAA8B;AAChE,QAAM,CAAC,IAAI,IAAI,aAAAA,QAAM,SAA6B,IAAI;AACtD,QAAM,YAAY,gCAAe;AAEjC,QAAM,cAAc;AAEpB,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SACE,6BAAAA,QAAA,cAAC,eAAe,UAAf,EAAwB,OAAO,EAAE,MAAM,UAAU,KAC/C,QACH;AAEJ;","names":["React"]}
1
+ {"version":3,"sources":["../../../src/client/provider.tsx"],"sourcesContent":["import React from 'react';\nimport type { PropsWithChildren } from 'react';\nimport { CabinIDProviderProps, User } from '../types';\nimport { getCurrentUser } from './request';\n\nexport const CabinIDContext = React.createContext<CabinIDProviderProps>({\n user: null,\n});\n\nconst CabinIDProvider = ({ children }: PropsWithChildren<any>) => {\n const [user, setState] = React.useState<User | null>(null);\n\n React.useEffect(() => {\n fetchUser();\n }, []);\n\n const fetchUser = async () => {\n const user = await getCurrentUser();\n setState(user);\n };\n\n return (\n <CabinIDContext.Provider value={{ user }}>\n {children}\n </CabinIDContext.Provider>\n );\n};\n\nexport { CabinIDProvider };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAGlB,qBAA+B;AAExB,MAAM,iBAAiB,aAAAA,QAAM,cAAoC;AAAA,EACtE,MAAM;AACR,CAAC;AAED,MAAM,kBAAkB,CAAC,EAAE,SAAS,MAA8B;AAChE,QAAM,CAAC,MAAM,QAAQ,IAAI,aAAAA,QAAM,SAAsB,IAAI;AAEzD,eAAAA,QAAM,UAAU,MAAM;AACpB,cAAU;AAAA,EACZ,GAAG,CAAC,CAAC;AAEL,QAAM,YAAY,YAAY;AAC5B,UAAMC,QAAO,UAAM,+BAAe;AAClC,aAASA,KAAI;AAAA,EACf;AAEA,SACE,6BAAAD,QAAA,cAAC,eAAe,UAAf,EAAwB,OAAO,EAAE,KAAK,KACpC,QACH;AAEJ;","names":["React","user"]}
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ "use server";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var request_exports = {};
21
+ __export(request_exports, {
22
+ getCurrentUser: () => getCurrentUser
23
+ });
24
+ module.exports = __toCommonJS(request_exports);
25
+ var import_constants = require("../constants");
26
+ var import_headers = require("next/headers");
27
+ const getCurrentUser = async () => {
28
+ var _a;
29
+ const token = (_a = (0, import_headers.cookies)().get(import_constants.constants.Cookies.Client)) == null ? void 0 : _a.value;
30
+ const response = await fetch(`${import_constants.baseApiUrl}/user/me`, {
31
+ method: "GET",
32
+ headers: {
33
+ Authorization: `Bearer ${token}`
34
+ }
35
+ });
36
+ const data = await response.json();
37
+ return data;
38
+ };
39
+ // Annotate the CommonJS export names for ESM import in node:
40
+ 0 && (module.exports = {
41
+ getCurrentUser
42
+ });
43
+ //# sourceMappingURL=request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/client/request.ts"],"sourcesContent":["'use server';\n\nimport { User } from 'src/types';\nimport { baseApiUrl, constants } from '../constants';\nimport { cookies } from 'next/headers';\n\nexport const getCurrentUser = async (): Promise<User | null> => {\n const token = cookies().get(constants.Cookies.Client)?.value;\n const response = await fetch(`${baseApiUrl}/user/me`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n const data: User = await response.json();\n return data;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,uBAAsC;AACtC,qBAAwB;AAEjB,MAAM,iBAAiB,YAAkC;AANhE;AAOE,QAAM,SAAQ,iCAAQ,EAAE,IAAI,2BAAU,QAAQ,MAAM,MAAtC,mBAAyC;AACvD,QAAM,WAAW,MAAM,MAAM,GAAG,2BAAU,YAAY;AAAA,IACpD,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,UAAU,KAAK;AAAA,IAChC;AAAA,EACF,CAAC;AACD,QAAM,OAAa,MAAM,SAAS,KAAK;AACvC,SAAO;AACT;","names":[]}
@@ -1,2 +1,32 @@
1
1
  "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var component_client_exports = {};
20
+ __export(component_client_exports, {
21
+ CabinIDProvider: () => import_provider.CabinIDProvider,
22
+ useUser: () => import_hooks.useUser
23
+ });
24
+ module.exports = __toCommonJS(component_client_exports);
25
+ var import_provider = require("./client/provider");
26
+ var import_hooks = require("./hooks");
27
+ // Annotate the CommonJS export names for ESM import in node:
28
+ 0 && (module.exports = {
29
+ CabinIDProvider,
30
+ useUser
31
+ });
2
32
  //# sourceMappingURL=component.client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../../src/component.client.ts"],"sourcesContent":["export { CabinIDProvider } from './client/provider';\nexport { useUser } from './hooks';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAgC;AAChC,mBAAwB;","names":[]}
@@ -37,7 +37,7 @@ var import_constants = require("../constants");
37
37
  const SignInButton = () => {
38
38
  const signInUrl = import_react.default.useMemo(() => {
39
39
  const params = new URLSearchParams({
40
- redirect_url: import_constants.CUSTOM_AFTER_SIGN_IN_URL
40
+ redirect_url: import_constants.CUSTOM_AFTER_SIGN_IN_URL || "/"
41
41
  });
42
42
  return import_constants.frontendApi ? `http://${import_constants.frontendApi}/sign-in?${params.toString()}` : "#";
43
43
  }, [import_constants.frontendApi, import_constants.CUSTOM_AFTER_SIGN_IN_URL]);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/components/SignInButton.tsx"],"sourcesContent":["import React from 'react';\nimport { CabinLogo } from '../icons/logo';\nimport { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from '../constants';\n\nexport const SignInButton = () => {\n const signInUrl = React.useMemo(() => {\n const params = new URLSearchParams({\n redirect_url: CUSTOM_AFTER_SIGN_IN_URL,\n });\n return frontendApi\n ? `http://${frontendApi}/sign-in?${params.toString()}`\n : '#';\n }, [frontendApi, CUSTOM_AFTER_SIGN_IN_URL]);\n\n return (\n <a\n href={signInUrl}\n className=\"max-w-48 pl-2 py-2 pr-4 bg-blue-600 rounded-full flex flex-row space-x-2 items-center hover:opacity-90 active:bg-blue-700\"\n >\n <CabinLogo />\n <span className=\"text-white text-sm\">Continue to CabinID</span>\n </a>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,kBAA0B;AAC1B,uBAAsD;AAE/C,MAAM,eAAe,MAAM;AAChC,QAAM,YAAY,aAAAA,QAAM,QAAQ,MAAM;AACpC,UAAM,SAAS,IAAI,gBAAgB;AAAA,MACjC,cAAc;AAAA,IAChB,CAAC;AACD,WAAO,+BACH,UAAU,4BAAW,YAAY,OAAO,SAAS,CAAC,KAClD;AAAA,EACN,GAAG,CAAC,8BAAa,yCAAwB,CAAC;AAE1C,SACE,6BAAAA,QAAA;AAAA,IAAC;AAAA;AAAA,MACC,MAAM;AAAA,MACN,WAAU;AAAA;AAAA,IAEV,6BAAAA,QAAA,cAAC,2BAAU;AAAA,IACX,6BAAAA,QAAA,cAAC,UAAK,WAAU,wBAAqB,qBAAmB;AAAA,EAC1D;AAEJ;","names":["React"]}
1
+ {"version":3,"sources":["../../../src/components/SignInButton.tsx"],"sourcesContent":["import React from 'react';\nimport { CabinLogo } from '../icons/logo';\nimport { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from '../constants';\n\nexport const SignInButton = () => {\n const signInUrl = React.useMemo(() => {\n const params = new URLSearchParams({\n redirect_url: CUSTOM_AFTER_SIGN_IN_URL || '/',\n });\n return frontendApi\n ? `http://${frontendApi}/sign-in?${params.toString()}`\n : '#';\n }, [frontendApi, CUSTOM_AFTER_SIGN_IN_URL]);\n\n return (\n <a\n href={signInUrl}\n className=\"max-w-48 pl-2 py-2 pr-4 bg-blue-600 rounded-full flex flex-row space-x-2 items-center hover:opacity-90 active:bg-blue-700\"\n >\n <CabinLogo />\n <span className=\"text-white text-sm\">Continue to CabinID</span>\n </a>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,kBAA0B;AAC1B,uBAAsD;AAE/C,MAAM,eAAe,MAAM;AAChC,QAAM,YAAY,aAAAA,QAAM,QAAQ,MAAM;AACpC,UAAM,SAAS,IAAI,gBAAgB;AAAA,MACjC,cAAc,6CAA4B;AAAA,IAC5C,CAAC;AACD,WAAO,+BACH,UAAU,4BAAW,YAAY,OAAO,SAAS,CAAC,KAClD;AAAA,EACN,GAAG,CAAC,8BAAa,yCAAwB,CAAC;AAE1C,SACE,6BAAAA,QAAA;AAAA,IAAC;AAAA;AAAA,MACC,MAAM;AAAA,MACN,WAAU;AAAA;AAAA,IAEV,6BAAAA,QAAA,cAAC,2BAAU;AAAA,IACX,6BAAAA,QAAA,cAAC,UAAK,WAAU,wBAAqB,qBAAmB;AAAA,EAC1D;AAEJ;","names":["React"]}
@@ -33,7 +33,7 @@ __export(constants_exports, {
33
33
  module.exports = __toCommonJS(constants_exports);
34
34
  var import_key = require("./utils/key");
35
35
  var import_path = require("./utils/path");
36
- const API_URL = "https://api.cabinid.dev/";
36
+ const API_URL = "http://localhost:3001/";
37
37
  const API_VERSION = "v1";
38
38
  const PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_CABIN_ID_PUBLISH_KEY || "";
39
39
  const SECRET_KEY = process.env.CABIN_ID_SECRET_KEY || "";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/constants.ts"],"sourcesContent":["import { parsePublishableKey } from './utils/key';\nimport { joinPaths } from './utils/path';\n\n/* The line `// export const API_URL = 'https://api.cabinid.dev/';` is a commented-out line of code in\nTypeScript. It is currently not active or being used in the code because it is preceded by `//`,\nwhich makes it a comment. */\nexport const API_URL = 'https://api.cabinid.dev/';\n// export const API_URL = 'http://localhost:3001/';\nexport const API_VERSION = 'v1';\nexport const PUBLISHABLE_KEY =\n process.env.NEXT_PUBLIC_CABIN_ID_PUBLISH_KEY! || '';\nexport const SECRET_KEY = process.env.CABIN_ID_SECRET_KEY! || '';\nexport const CUSTOM_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_IN_URL! || '';\nexport const CUSTOM_SIGN_Up_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_UP_URL! || '';\nexport const CUSTOM_AFTER_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL || '';\nexport const CUSTOM_AFTER_SIGN_UP_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_UP_URL || '';\n\nexport const baseApiUrl = joinPaths(API_URL, API_VERSION);\nexport const frontendApi = parsePublishableKey(PUBLISHABLE_KEY);\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Client: '__client',\n User: '__user',\n} as const;\n\nconst QueryParams = {\n UserId: 'user_id',\n Token: 'token',\n} as const;\n\nconst Headers = {\n AuthToken: 'x-cabin-id-auth-token',\n AuthSignature: 'x-cabin-id-auth-signature',\n AuthStatus: 'x-cabin-id-auth-status',\n AuthReason: 'x-cabin-id-auth-reason',\n AuthMessage: 'x-cabin-id-auth-message',\n CabinIdUrl: 'x-cabin-id-cabin-id-url',\n EnableDebug: 'x-cabin-id-debug',\n CabinIdRedirectTo: 'x-cabin-id-redirect-to',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n Authorization: 'authorization',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n ForwardedHost: 'x-forwarded-host',\n Accept: 'accept',\n Referrer: 'referer',\n UserAgent: 'user-agent',\n Origin: 'origin',\n Host: 'host',\n ContentType: 'content-type',\n SecFetchDest: 'sec-fetch-dest',\n Location: 'location',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\nconst NextHeaders = {\n NextRewrite: 'x-middleware-rewrite',\n NextResume: 'x-middleware-next',\n NextRedirect: 'Location',\n // Used by next to identify internal navigation for app router\n NextUrl: 'next-url',\n NextAction: 'next-action',\n // Used by next to identify internal navigation for pages router\n NextjsData: 'x-nextjs-data',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParams,\n NextHeaders,\n} as const;\n\nexport type Constants = typeof constants;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAoC;AACpC,kBAA0B;AAKnB,MAAM,UAAU;AAEhB,MAAM,cAAc;AACpB,MAAM,kBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,aAAa,QAAQ,IAAI,uBAAwB;AACvD,MAAM,qBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,qBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,2BACX,QAAQ,IAAI,0CAA0C;AACjD,MAAM,2BACX,QAAQ,IAAI,0CAA0C;AAEjD,MAAM,iBAAa,uBAAU,SAAS,WAAW;AACjD,MAAM,kBAAc,gCAAoB,eAAe;AAE9D,MAAM,aAAa;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AACZ;AAEA,MAAM,UAAU;AAAA,EACd,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AACR;AAEA,MAAM,cAAc;AAAA,EAClB,QAAQ;AAAA,EACR,OAAO;AACT;AAEA,MAAM,UAAU;AAAA,EACd,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,0BAA0B;AAAA,EAC1B,eAAe;AAAA,EACf,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAAA,EACd,UAAU;AACZ;AAEA,MAAM,eAAe;AAAA,EACnB,MAAM;AACR;AAEA,MAAM,cAAc;AAAA,EAClB,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,cAAc;AAAA;AAAA,EAEd,SAAS;AAAA,EACT,YAAY;AAAA;AAAA,EAEZ,YAAY;AACd;AAKO,MAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/constants.ts"],"sourcesContent":["import { parsePublishableKey } from './utils/key';\nimport { joinPaths } from './utils/path';\n\n// export const API_URL = 'https://api.cabinid.dev/';\nexport const API_URL = 'http://localhost:3001/';\nexport const API_VERSION = 'v1';\nexport const PUBLISHABLE_KEY =\n process.env.NEXT_PUBLIC_CABIN_ID_PUBLISH_KEY! || '';\nexport const SECRET_KEY = process.env.CABIN_ID_SECRET_KEY! || '';\nexport const CUSTOM_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_IN_URL! || '';\nexport const CUSTOM_SIGN_Up_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_UP_URL! || '';\nexport const CUSTOM_AFTER_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL || '';\nexport const CUSTOM_AFTER_SIGN_UP_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_UP_URL || '';\n\nexport const baseApiUrl = joinPaths(API_URL, API_VERSION);\nexport const frontendApi = parsePublishableKey(PUBLISHABLE_KEY);\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Client: '__client',\n User: '__user',\n} as const;\n\nconst QueryParams = {\n UserId: 'user_id',\n Token: 'token',\n} as const;\n\nconst Headers = {\n AuthToken: 'x-cabin-id-auth-token',\n AuthSignature: 'x-cabin-id-auth-signature',\n AuthStatus: 'x-cabin-id-auth-status',\n AuthReason: 'x-cabin-id-auth-reason',\n AuthMessage: 'x-cabin-id-auth-message',\n CabinIdUrl: 'x-cabin-id-cabin-id-url',\n EnableDebug: 'x-cabin-id-debug',\n CabinIdRedirectTo: 'x-cabin-id-redirect-to',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n Authorization: 'authorization',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n ForwardedHost: 'x-forwarded-host',\n Accept: 'accept',\n Referrer: 'referer',\n UserAgent: 'user-agent',\n Origin: 'origin',\n Host: 'host',\n ContentType: 'content-type',\n SecFetchDest: 'sec-fetch-dest',\n Location: 'location',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\nconst NextHeaders = {\n NextRewrite: 'x-middleware-rewrite',\n NextResume: 'x-middleware-next',\n NextRedirect: 'Location',\n // Used by next to identify internal navigation for app router\n NextUrl: 'next-url',\n NextAction: 'next-action',\n // Used by next to identify internal navigation for pages router\n NextjsData: 'x-nextjs-data',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParams,\n NextHeaders,\n} as const;\n\nexport type Constants = typeof constants;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA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SAAS;AAAA,EACT,YAAY;AAAA;AAAA,EAEZ,YAAY;AACd;AAKO,MAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -0,0 +1,9 @@
1
+ {
2
+ "sideEffects": false,
3
+ "imports": {
4
+ "#components": {
5
+ "react-server": "./components.server.js",
6
+ "default": "./components.client.js"
7
+ }
8
+ }
9
+ }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/server/getCurrentUser.ts"],"sourcesContent":["import { baseApiUrl, SECRET_KEY } from '../constants';\n\nimport { auth } from './auth';\n\nexport type User = {\n id: string;\n avatar: string | null;\n email: string | null;\n phoneNumber: string;\n firstName: string;\n lastName: string;\n address: string | null;\n createdAt: string;\n updatedAt: string;\n};\n\nexport async function currentUser(): Promise<User | null> {\n const { userId } = auth();\n if (!userId) return null;\n\n const response = await fetch(`${baseApiUrl}/user/${userId}`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${SECRET_KEY}`,\n },\n });\n const data: User = await response.json();\n return data;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAuC;AAEvC,kBAAqB;AAcrB,eAAsB,cAAoC;AACxD,QAAM,EAAE,OAAO,QAAI,kBAAK;AACxB,MAAI,CAAC;AAAQ,WAAO;AAEpB,QAAM,WAAW,MAAM,MAAM,GAAG,2BAAU,SAAS,MAAM,IAAI;AAAA,IAC3D,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,UAAU,2BAAU;AAAA,IACrC;AAAA,EACF,CAAC;AACD,QAAM,OAAa,MAAM,SAAS,KAAK;AACvC,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../../src/server/getCurrentUser.ts"],"sourcesContent":["import { User } from '../types';\nimport { baseApiUrl, SECRET_KEY } from '../constants';\n\nimport { auth } from './auth';\n\nexport async function currentUser(): Promise<User | null> {\n const { userId } = auth();\n if (!userId) return null;\n\n const response = await fetch(`${baseApiUrl}/user/${userId}`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${SECRET_KEY}`,\n },\n });\n\n const data: User = await response.json();\n return data;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAAuC;AAEvC,kBAAqB;AAErB,eAAsB,cAAoC;AACxD,QAAM,EAAE,OAAO,QAAI,kBAAK;AACxB,MAAI,CAAC;AAAQ,WAAO;AAEpB,QAAM,WAAW,MAAM,MAAM,GAAG,2BAAU,SAAS,MAAM,IAAI;AAAA,IAC3D,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,UAAU,2BAAU;AAAA,IACrC;AAAA,EACF,CAAC;AAED,QAAM,OAAa,MAAM,SAAS,KAAK;AACvC,SAAO;AACT;","names":[]}
@@ -64,12 +64,6 @@ const authMiddleware = (...args) => {
64
64
  const isPublicRoute = (0, import_routeMatcher.createRouteMatcher)(
65
65
  withDefaultPublicRoutes(options.publicRoutes)
66
66
  );
67
- const isApiRoute = createApiRoutes(options.apiRoutes);
68
- const defaultAfterAuth = createDefaultAfterAuth(
69
- isPublicRoute,
70
- isApiRoute,
71
- options
72
- );
73
67
  return async (_req, evt) => {
74
68
  const url = _req.nextUrl;
75
69
  const accessToken = url.searchParams.get(import_constants.constants.QueryParams.Token);
@@ -92,21 +86,6 @@ const authMiddleware = (...args) => {
92
86
  "before-auth-redirect"
93
87
  );
94
88
  }
95
- const requestState = {
96
- token: accessToken,
97
- userId
98
- };
99
- const auth = {
100
- ...requestState,
101
- isPublicRoute: isPublicRoute(nextRequest),
102
- isApiRoute: isApiRoute(nextRequest)
103
- };
104
- const afterAuthRes = await (options.afterAuth || defaultAfterAuth)(
105
- auth,
106
- nextRequest,
107
- evt
108
- );
109
- const finalRes = (0, import_response.mergeResponses)(beforeAuthRes, afterAuthRes) || import_server.NextResponse.next();
110
89
  if (accessToken && userId) {
111
90
  const path = url.pathname;
112
91
  const response = import_server.NextResponse.redirect(new URL(path || "/", _req.url));
@@ -114,10 +93,7 @@ const authMiddleware = (...args) => {
114
93
  response.cookies.set(import_constants.constants.Cookies.User, userId);
115
94
  return response;
116
95
  }
117
- const result = (
118
- // decorateRequest(_req, finalRes, requestState, secretKey) ||
119
- import_server.NextResponse.next()
120
- );
96
+ const result = checkAuth(_req);
121
97
  return result;
122
98
  };
123
99
  };
@@ -174,6 +150,26 @@ const createDefaultAfterAuth = (isPublicRoute, isApiRoute, options) => {
174
150
  return import_server.NextResponse.next();
175
151
  };
176
152
  };
153
+ const checkAuth = (req) => {
154
+ const accessToken = req.cookies.get(import_constants.constants.Cookies.Client);
155
+ if (!accessToken && req.nextUrl.href !== import_constants.CUSTOM_SIGN_IN_URL) {
156
+ if (import_constants.CUSTOM_SIGN_IN_URL) {
157
+ return import_server.NextResponse.redirect(new URL(import_constants.CUSTOM_SIGN_IN_URL));
158
+ }
159
+ if (import_constants.frontendApi) {
160
+ const params = new URLSearchParams({
161
+ redirect_url: import_constants.CUSTOM_AFTER_SIGN_IN_URL || "/"
162
+ });
163
+ return import_server.NextResponse.redirect(
164
+ new URL(`${import_constants.frontendApi}/sign-in?${params.toString()}`)
165
+ );
166
+ }
167
+ throw new Error(
168
+ "You are not authentication. Please provide CABIN ID PUBLISH KEY to redirect to authentication page"
169
+ );
170
+ }
171
+ return import_server.NextResponse.next();
172
+ };
177
173
  // Annotate the CommonJS export names for ESM import in node:
178
174
  0 && (module.exports = {
179
175
  DEFAULT_API_ROUTES,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/server/middleware.ts"],"sourcesContent":["import { NextFetchEvent, NextMiddleware, NextResponse } from 'next/server';\nimport { NextRequest } from 'next/server';\nimport {\n constants,\n CUSTOM_SIGN_IN_URL,\n PUBLISHABLE_KEY,\n SECRET_KEY,\n} from '../constants';\nimport { createRouteMatcher, RouteMatcherParam } from './routeMatcher';\nimport {\n apiEndpointUnauthorizedNextResponse,\n assertKey,\n // decorateRequest,\n redirectAdapter,\n} from './utils';\nimport { NextMiddlewareReturn } from './type';\nimport { isRedirect, mergeResponses, setHeader } from '../utils/response';\nimport { createRedirect } from './createRedirect';\n// import { serverRedirectWithAuth } from './serverRedirectWithAuth';\n\ntype BeforeAuthHandler = (\n req: NextRequest,\n evt: NextFetchEvent\n) => NextMiddlewareReturn | false | Promise<false>;\n\ntype AfterAuthHandler = (\n auth: { isPublicRoute: boolean; isApiRoute: boolean },\n req: NextRequest,\n evt: NextFetchEvent\n) => NextMiddlewareReturn;\n\nexport type AuthenticateRequestOptions = {\n publishableKey?: string;\n secretKey?: string;\n domain?: string;\n isSatellite?: boolean;\n proxyUrl?: string;\n signInUrl?: string;\n signUpUrl?: string;\n afterSignInUrl?: string;\n afterSignUpUrl?: string;\n};\n\ntype AuthMiddlewareParams = AuthenticateRequestOptions & {\n /**\n * A function that is called before the authentication middleware is executed.\n * If a redirect response is returned, the middleware will respect it and redirect the user.\n * If false is returned, the auth middleware will not execute and the request will be handled as if the auth middleware was not present.\n */\n beforeAuth?: BeforeAuthHandler;\n /**\n * A function that is called after the authentication middleware is executed.\n * This function has access to the auth object and can be used to execute logic based on the auth state.\n */\n afterAuth?: AfterAuthHandler;\n /**\n * A list of routes that should be accessible without authentication.\n * You can use glob patterns to match multiple routes or a function to match against the request object.\n * Path patterns and regular expressions are supported, for example: `['/foo', '/bar(.*)'] or `[/^\\/foo\\/.*$/]`\n * The sign in and sign up URLs are included by default, unless a function is provided.\n * For more information, see: https://clerk.com/docs\n */\n publicRoutes?: RouteMatcherParam;\n /**\n * A list of routes that should be ignored by the middleware.\n * This list typically includes routes for static files or Next.js internals.\n * For improved performance, these routes should be skipped using the default config.matcher instead.\n */\n ignoredRoutes?: IgnoredRoutesParam;\n /**\n * A list of routes that should be treated as API endpoints.\n * When user is signed out, the middleware will return a 401 response for these routes, instead of redirecting the user.\n *\n * If omitted, the following heuristics will be used to determine an API endpoint:\n * - The route path is ['/api/(.*)', '/trpc/(.*)'],\n * - or the request has `Content-Type` set to `application/json`,\n * - or the request method is not one of: `GET`, `OPTIONS` ,` HEAD`\n *\n * @default undefined\n */\n apiRoutes?: ApiRoutesParam;\n};\n\nexport interface AuthMiddleware {\n (params?: AuthMiddlewareParams): NextMiddleware;\n}\n\n/**\n * The default ideal matcher that excludes the _next directory (internals) and all static files,\n * but it will match the root route (/) and any routes that start with /api or /trpc.\n */\nexport const DEFAULT_CONFIG_MATCHER = [\n '/((?!.+\\\\.[\\\\w]+$|_next).*)',\n '/',\n '/(api|trpc)(.*)',\n];\n\n/**\n * Any routes matching this path will be ignored by the middleware.\n * This is the inverted version of DEFAULT_CONFIG_MATCHER.\n */\nexport const DEFAULT_IGNORED_ROUTES = [`/((?!api|trpc))(_next.*|.+\\\\.[\\\\w]+$)`];\n/**\n * Any routes matching this path will be treated as API endpoints by the middleware.\n */\nexport const DEFAULT_API_ROUTES = ['/api/(.*)', '/trpc/(.*)'];\n\ntype IgnoredRoutesParam =\n | Array<RegExp | string>\n | RegExp\n | string\n | ((req: NextRequest) => boolean);\n\ntype ApiRoutesParam = IgnoredRoutesParam;\n\nconst authMiddleware: AuthMiddleware = (...args: unknown[]) => {\n const [params = {}] = args as [AuthMiddlewareParams?];\n\n const publishableKey = assertKey(\n params.publishableKey || PUBLISHABLE_KEY,\n () => {\n throw new Error('Publish Key is not exist');\n }\n );\n const secretKey = assertKey(params.secretKey || SECRET_KEY, () => {\n throw new Error('Secret Key is not valid');\n });\n\n const signInUrl = params.signInUrl || CUSTOM_SIGN_IN_URL;\n const signUpUrl = params.signUpUrl || CUSTOM_SIGN_IN_URL;\n\n const options = {\n ...params,\n publishableKey,\n secretKey,\n signInUrl,\n signUpUrl,\n };\n\n const isIgnoredRoute = createRouteMatcher(\n options.ignoredRoutes || DEFAULT_IGNORED_ROUTES\n );\n const isPublicRoute = createRouteMatcher(\n withDefaultPublicRoutes(options.publicRoutes)\n );\n const isApiRoute = createApiRoutes(options.apiRoutes);\n const defaultAfterAuth = createDefaultAfterAuth(\n isPublicRoute,\n isApiRoute,\n options\n );\n\n return async (_req: NextRequest, evt: NextFetchEvent) => {\n const url = _req.nextUrl;\n const accessToken = url.searchParams.get(constants.QueryParams.Token);\n const userId = url.searchParams.get(constants.QueryParams.UserId);\n\n if (isIgnoredRoute(_req) || isPublicRoute(_req)) {\n return;\n }\n const nextRequest = _req;\n\n const beforeAuthRes = await (options.beforeAuth &&\n options.beforeAuth(nextRequest, evt));\n\n if (beforeAuthRes === false) {\n return setHeader(\n NextResponse.next(),\n constants.Headers.AuthReason,\n 'skip'\n );\n } else if (beforeAuthRes && isRedirect(beforeAuthRes)) {\n return setHeader(\n beforeAuthRes,\n constants.Headers.AuthReason,\n 'before-auth-redirect'\n );\n }\n\n const requestState = {\n token: accessToken,\n userId,\n };\n\n const auth = {\n ...requestState,\n isPublicRoute: isPublicRoute(nextRequest),\n isApiRoute: isApiRoute(nextRequest),\n };\n\n const afterAuthRes = await (options.afterAuth || defaultAfterAuth)(\n auth,\n nextRequest,\n evt\n );\n\n const finalRes =\n mergeResponses(beforeAuthRes, afterAuthRes) || NextResponse.next();\n\n if (accessToken && userId) {\n const path = url.pathname;\n const response = NextResponse.redirect(new URL(path || '/', _req.url));\n response.cookies.set(constants.Cookies.Client, accessToken);\n response.cookies.set(constants.Cookies.User, userId);\n return response;\n }\n \n // if (isRedirect(finalRes)) {\n // const res = serverRedirectWithAuth(finalRes);\n // return res;\n // }\n\n const result =\n // decorateRequest(_req, finalRes, requestState, secretKey) ||\n NextResponse.next();\n\n return result;\n };\n};\n\nconst withDefaultPublicRoutes = (\n publicRoutes: RouteMatcherParam | undefined\n) => {\n if (typeof publicRoutes === 'function') {\n return publicRoutes;\n }\n\n const routes = [publicRoutes || ''].flat().filter(Boolean);\n // TODO: refactor it to use common config file eg SIGN_IN_URL from ./clerkClient\n // we use process.env for now to support testing\n const signInUrl = process.env.NEXT_PUBLIC_CLERK_SIGN_IN_URL || '';\n if (signInUrl) {\n routes.push(matchRoutesStartingWith(signInUrl));\n }\n // TODO: refactor it to use common config file eg SIGN_UP_URL from ./clerkClient\n // we use process.env for now to support testing\n const signUpUrl = process.env.NEXT_PUBLIC_CLERK_SIGN_UP_URL || '';\n if (signUpUrl) {\n routes.push(matchRoutesStartingWith(signUpUrl));\n }\n return routes;\n};\n\nconst matchRoutesStartingWith = (path: string) => {\n path = path.replace(/\\/$/, '');\n return new RegExp(`^${path}(/.*)?$`);\n};\n\nconst isRequestMethodIndicatingApiRoute = (req: NextRequest): boolean => {\n const requestMethod = req.method.toLowerCase();\n return !['get', 'head', 'options'].includes(requestMethod);\n};\n\nconst isRequestContentTypeJson = (req: NextRequest): boolean => {\n const requestContentType = req.headers.get(constants.Headers.ContentType);\n return requestContentType === constants.ContentTypes.Json;\n};\n\n// - Default behavior:\n// If the route path is `['/api/(.*)*', '*/trpc/(.*)']`\n// or Request has `Content-Type: application/json`\n// or Request method is not-GET,OPTIONS,HEAD,\n// then this is considered an API route.\n//\n// - If the user has provided a specific `apiRoutes` prop in `authMiddleware` then all the above are discarded,\n// and only routes that match the user’s provided paths are considered API routes.\nconst createApiRoutes = (\n apiRoutes: RouteMatcherParam | undefined\n): ((req: NextRequest) => boolean) => {\n if (apiRoutes) {\n return createRouteMatcher(apiRoutes);\n }\n const isDefaultApiRoute = createRouteMatcher(DEFAULT_API_ROUTES);\n return (req: NextRequest) =>\n isDefaultApiRoute(req) ||\n isRequestMethodIndicatingApiRoute(req) ||\n isRequestContentTypeJson(req);\n};\n\nexport const createDefaultAfterAuth = (\n isPublicRoute: ReturnType<typeof createRouteMatcher>,\n isApiRoute: ReturnType<typeof createApiRoutes>,\n options: {\n signInUrl: string;\n signUpUrl: string;\n publishableKey: string;\n secretKey: string;\n }\n) => {\n return (auth: any, req: NextRequest) => {\n if (!auth.userId && !isPublicRoute(req)) {\n if (isApiRoute(req)) {\n return apiEndpointUnauthorizedNextResponse();\n }\n return createRedirect({\n redirectAdapter,\n signInUrl: options.signInUrl,\n signUpUrl: options.signUpUrl,\n publishableKey: options.publishableKey,\n // We're setting baseUrl to '' here as we want to keep the legacy behavior of\n // the redirectToSignIn, redirectToSignUp helpers in the backend package.\n baseUrl: '',\n }).redirectToSignIn({ returnBackUrl: req.nextUrl.href });\n }\n return NextResponse.next();\n };\n};\n\nexport { authMiddleware };\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6D;AAE7D,uBAKO;AACP,0BAAsD;AACtD,mBAKO;AAEP,sBAAsD;AACtD,4BAA+B;AA0ExB,MAAM,yBAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AACF;AAMO,MAAM,yBAAyB,CAAC,uCAAuC;AAIvE,MAAM,qBAAqB,CAAC,aAAa,YAAY;AAU5D,MAAM,iBAAiC,IAAI,SAAoB;AAC7D,QAAM,CAAC,SAAS,CAAC,CAAC,IAAI;AAEtB,QAAM,qBAAiB;AAAA,IACrB,OAAO,kBAAkB;AAAA,IACzB,MAAM;AACJ,YAAM,IAAI,MAAM,0BAA0B;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,gBAAY,wBAAU,OAAO,aAAa,6BAAY,MAAM;AAChE,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C,CAAC;AAED,QAAM,YAAY,OAAO,aAAa;AACtC,QAAM,YAAY,OAAO,aAAa;AAEtC,QAAM,UAAU;AAAA,IACd,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,qBAAiB;AAAA,IACrB,QAAQ,iBAAiB;AAAA,EAC3B;AACA,QAAM,oBAAgB;AAAA,IACpB,wBAAwB,QAAQ,YAAY;AAAA,EAC9C;AACA,QAAM,aAAa,gBAAgB,QAAQ,SAAS;AACpD,QAAM,mBAAmB;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO,OAAO,MAAmB,QAAwB;AACvD,UAAM,MAAM,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B,SAAS;AAAA,MACX,CAAC,EAAE,iBAAiB,EAAE,eAAe,IAAI,QAAQ,KAAK,CAAC;AAAA,IACzD;AACA,WAAO,2BAAa,KAAK;AAAA,EAC3B;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/server/middleware.ts"],"sourcesContent":["import { NextFetchEvent, NextMiddleware, NextResponse } from 'next/server';\nimport { NextRequest } from 'next/server';\nimport {\n constants,\n CUSTOM_AFTER_SIGN_IN_URL,\n CUSTOM_SIGN_IN_URL,\n frontendApi,\n PUBLISHABLE_KEY,\n SECRET_KEY,\n} from '../constants';\nimport { createRouteMatcher, RouteMatcherParam } from './routeMatcher';\nimport {\n apiEndpointUnauthorizedNextResponse,\n assertKey,\n // decorateRequest,\n redirectAdapter,\n} from './utils';\nimport { NextMiddlewareReturn } from './type';\nimport { isRedirect, setHeader } from '../utils/response';\nimport { createRedirect } from './createRedirect';\n// import { serverRedirectWithAuth } from './serverRedirectWithAuth';\n\ntype BeforeAuthHandler = (\n req: NextRequest,\n evt: NextFetchEvent\n) => NextMiddlewareReturn | false | Promise<false>;\n\ntype AfterAuthHandler = (\n auth: { isPublicRoute: boolean; isApiRoute: boolean },\n req: NextRequest,\n evt: NextFetchEvent\n) => NextMiddlewareReturn;\n\nexport type AuthenticateRequestOptions = {\n publishableKey?: string;\n secretKey?: string;\n domain?: string;\n isSatellite?: boolean;\n proxyUrl?: string;\n signInUrl?: string;\n signUpUrl?: string;\n afterSignInUrl?: string;\n afterSignUpUrl?: string;\n};\n\ntype AuthMiddlewareParams = AuthenticateRequestOptions & {\n /**\n * A function that is called before the authentication middleware is executed.\n * If a redirect response is returned, the middleware will respect it and redirect the user.\n * If false is returned, the auth middleware will not execute and the request will be handled as if the auth middleware was not present.\n */\n beforeAuth?: BeforeAuthHandler;\n /**\n * A function that is called after the authentication middleware is executed.\n * This function has access to the auth object and can be used to execute logic based on the auth state.\n */\n afterAuth?: AfterAuthHandler;\n /**\n * A list of routes that should be accessible without authentication.\n * You can use glob patterns to match multiple routes or a function to match against the request object.\n * Path patterns and regular expressions are supported, for example: `['/foo', '/bar(.*)'] or `[/^\\/foo\\/.*$/]`\n * The sign in and sign up URLs are included by default, unless a function is provided.\n * For more information, see: https://clerk.com/docs\n */\n publicRoutes?: RouteMatcherParam;\n /**\n * A list of routes that should be ignored by the middleware.\n * This list typically includes routes for static files or Next.js internals.\n * For improved performance, these routes should be skipped using the default config.matcher instead.\n */\n ignoredRoutes?: IgnoredRoutesParam;\n /**\n * A list of routes that should be treated as API endpoints.\n * When user is signed out, the middleware will return a 401 response for these routes, instead of redirecting the user.\n *\n * If omitted, the following heuristics will be used to determine an API endpoint:\n * - The route path is ['/api/(.*)', '/trpc/(.*)'],\n * - or the request has `Content-Type` set to `application/json`,\n * - or the request method is not one of: `GET`, `OPTIONS` ,` HEAD`\n *\n * @default undefined\n */\n apiRoutes?: ApiRoutesParam;\n};\n\nexport interface AuthMiddleware {\n (params?: AuthMiddlewareParams): NextMiddleware;\n}\n\n/**\n * The default ideal matcher that excludes the _next directory (internals) and all static files,\n * but it will match the root route (/) and any routes that start with /api or /trpc.\n */\nexport const DEFAULT_CONFIG_MATCHER = [\n '/((?!.+\\\\.[\\\\w]+$|_next).*)',\n '/',\n '/(api|trpc)(.*)',\n];\n\n/**\n * Any routes matching this path will be ignored by the middleware.\n * This is the inverted version of DEFAULT_CONFIG_MATCHER.\n */\nexport const DEFAULT_IGNORED_ROUTES = [`/((?!api|trpc))(_next.*|.+\\\\.[\\\\w]+$)`];\n/**\n * Any routes matching this path will be treated as API endpoints by the middleware.\n */\nexport const DEFAULT_API_ROUTES = ['/api/(.*)', '/trpc/(.*)'];\n\ntype IgnoredRoutesParam =\n | Array<RegExp | string>\n | RegExp\n | string\n | ((req: NextRequest) => boolean);\n\ntype ApiRoutesParam = IgnoredRoutesParam;\n\nconst authMiddleware: AuthMiddleware = (...args: unknown[]) => {\n const [params = {}] = args as [AuthMiddlewareParams?];\n\n const publishableKey = assertKey(\n params.publishableKey || PUBLISHABLE_KEY,\n () => {\n throw new Error('Publish Key is not exist');\n }\n );\n const secretKey = assertKey(params.secretKey || SECRET_KEY, () => {\n throw new Error('Secret Key is not valid');\n });\n\n const signInUrl = params.signInUrl || CUSTOM_SIGN_IN_URL;\n const signUpUrl = params.signUpUrl || CUSTOM_SIGN_IN_URL;\n\n const options = {\n ...params,\n publishableKey,\n secretKey,\n signInUrl,\n signUpUrl,\n };\n\n const isIgnoredRoute = createRouteMatcher(\n options.ignoredRoutes || DEFAULT_IGNORED_ROUTES\n );\n const isPublicRoute = createRouteMatcher(\n withDefaultPublicRoutes(options.publicRoutes)\n );\n // const isApiRoute = createApiRoutes(options.apiRoutes);\n // const defaultAfterAuth = createDefaultAfterAuth(\n // isPublicRoute,\n // isApiRoute,\n // options\n // );\n\n return async (_req: NextRequest, evt: NextFetchEvent) => {\n const url = _req.nextUrl;\n\n const accessToken = url.searchParams.get(constants.QueryParams.Token);\n const userId = url.searchParams.get(constants.QueryParams.UserId);\n\n if (isIgnoredRoute(_req) || isPublicRoute(_req)) {\n return;\n }\n const nextRequest = _req;\n\n const beforeAuthRes = await (options.beforeAuth &&\n options.beforeAuth(nextRequest, evt));\n\n if (beforeAuthRes === false) {\n return setHeader(\n NextResponse.next(),\n constants.Headers.AuthReason,\n 'skip'\n );\n } else if (beforeAuthRes && isRedirect(beforeAuthRes)) {\n return setHeader(\n beforeAuthRes,\n constants.Headers.AuthReason,\n 'before-auth-redirect'\n );\n }\n\n // const requestState = {\n // token: accessToken,\n // userId,\n // };\n\n // const auth = {\n // ...requestState,\n // isPublicRoute: isPublicRoute(nextRequest),\n // isApiRoute: isApiRoute(nextRequest),\n // };\n\n // const afterAuthRes = await (options.afterAuth || defaultAfterAuth)(\n // auth,\n // nextRequest,\n // evt\n // );\n\n // const finalRes =\n // mergeResponses(beforeAuthRes, afterAuthRes) || NextResponse.next();\n\n if (accessToken && userId) {\n const path = url.pathname;\n const response = NextResponse.redirect(new URL(path || '/', _req.url));\n response.cookies.set(constants.Cookies.Client, accessToken);\n response.cookies.set(constants.Cookies.User, userId);\n return response;\n }\n\n // console.log(finalRes);\n\n // if (isRedirect(finalRes)) {\n // const res = serverRedirectWithAuth(finalRes);\n // return res;\n // }\n\n const result = checkAuth(_req);\n\n return result;\n };\n};\n\nconst withDefaultPublicRoutes = (\n publicRoutes: RouteMatcherParam | undefined\n) => {\n if (typeof publicRoutes === 'function') {\n return publicRoutes;\n }\n\n const routes = [publicRoutes || ''].flat().filter(Boolean);\n // TODO: refactor it to use common config file eg SIGN_IN_URL from ./clerkClient\n // we use process.env for now to support testing\n const signInUrl = process.env.NEXT_PUBLIC_CLERK_SIGN_IN_URL || '';\n if (signInUrl) {\n routes.push(matchRoutesStartingWith(signInUrl));\n }\n // TODO: refactor it to use common config file eg SIGN_UP_URL from ./clerkClient\n // we use process.env for now to support testing\n const signUpUrl = process.env.NEXT_PUBLIC_CLERK_SIGN_UP_URL || '';\n if (signUpUrl) {\n routes.push(matchRoutesStartingWith(signUpUrl));\n }\n return routes;\n};\n\nconst matchRoutesStartingWith = (path: string) => {\n path = path.replace(/\\/$/, '');\n return new RegExp(`^${path}(/.*)?$`);\n};\n\nconst isRequestMethodIndicatingApiRoute = (req: NextRequest): boolean => {\n const requestMethod = req.method.toLowerCase();\n return !['get', 'head', 'options'].includes(requestMethod);\n};\n\nconst isRequestContentTypeJson = (req: NextRequest): boolean => {\n const requestContentType = req.headers.get(constants.Headers.ContentType);\n return requestContentType === constants.ContentTypes.Json;\n};\n\n// - Default behavior:\n// If the route path is `['/api/(.*)*', '*/trpc/(.*)']`\n// or Request has `Content-Type: application/json`\n// or Request method is not-GET,OPTIONS,HEAD,\n// then this is considered an API route.\n//\n// - If the user has provided a specific `apiRoutes` prop in `authMiddleware` then all the above are discarded,\n// and only routes that match the user’s provided paths are considered API routes.\nconst createApiRoutes = (\n apiRoutes: RouteMatcherParam | undefined\n): ((req: NextRequest) => boolean) => {\n if (apiRoutes) {\n return createRouteMatcher(apiRoutes);\n }\n const isDefaultApiRoute = createRouteMatcher(DEFAULT_API_ROUTES);\n return (req: NextRequest) =>\n isDefaultApiRoute(req) ||\n isRequestMethodIndicatingApiRoute(req) ||\n isRequestContentTypeJson(req);\n};\n\nexport const createDefaultAfterAuth = (\n isPublicRoute: ReturnType<typeof createRouteMatcher>,\n isApiRoute: ReturnType<typeof createApiRoutes>,\n options: {\n signInUrl: string;\n signUpUrl: string;\n publishableKey: string;\n secretKey: string;\n }\n) => {\n return (auth: any, req: NextRequest) => {\n if (!auth.userId && !isPublicRoute(req)) {\n if (isApiRoute(req)) {\n return apiEndpointUnauthorizedNextResponse();\n }\n return createRedirect({\n redirectAdapter,\n signInUrl: options.signInUrl,\n signUpUrl: options.signUpUrl,\n publishableKey: options.publishableKey,\n // We're setting baseUrl to '' here as we want to keep the legacy behavior of\n // the redirectToSignIn, redirectToSignUp helpers in the backend package.\n baseUrl: '',\n }).redirectToSignIn({ returnBackUrl: req.nextUrl.href });\n }\n return NextResponse.next();\n };\n};\n\nconst checkAuth = (req: NextRequest): any => {\n const accessToken = req.cookies.get(constants.Cookies.Client);\n\n if (!accessToken && req.nextUrl.href !== CUSTOM_SIGN_IN_URL) {\n if (CUSTOM_SIGN_IN_URL) {\n return NextResponse.redirect(new URL(CUSTOM_SIGN_IN_URL));\n }\n\n if (frontendApi) {\n const params = new URLSearchParams({\n redirect_url: CUSTOM_AFTER_SIGN_IN_URL || '/',\n });\n return NextResponse.redirect(\n new URL(`${frontendApi}/sign-in?${params.toString()}`)\n );\n }\n throw new Error(\n 'You are not authentication. Please provide CABIN ID PUBLISH KEY to redirect to authentication page'\n );\n }\n return NextResponse.next();\n};\n\nexport { authMiddleware };\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6D;AAE7D,uBAOO;AACP,0BAAsD;AACtD,mBAKO;AAEP,sBAAsC;AACtC,4BAA+B;AA0ExB,MAAM,yBA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wCAAmB,kBAAkB;AAC/D,SAAO,CAAC,QACN,kBAAkB,GAAG,KACrB,kCAAkC,GAAG,KACrC,yBAAyB,GAAG;AAChC;AAEO,MAAM,yBAAyB,CACpC,eACA,YACA,YAMG;AACH,SAAO,CAAC,MAAW,QAAqB;AACtC,QAAI,CAAC,KAAK,UAAU,CAAC,cAAc,GAAG,GAAG;AACvC,UAAI,WAAW,GAAG,GAAG;AACnB,mBAAO,kDAAoC;AAAA,MAC7C;AACA,iBAAO,sCAAe;AAAA,QACpB;AAAA,QACA,WAAW,QAAQ;AAAA,QACnB,WAAW,QAAQ;AAAA,QACnB,gBAAgB,QAAQ;AAAA;AAAA;AAAA,QAGxB,SAAS;AAAA,MACX,CAAC,EAAE,iBAAiB,EAAE,eAAe,IAAI,QAAQ,KAAK,CAAC;AAAA,IACzD;AACA,WAAO,2BAAa,KAAK;AAAA,EAC3B;AACF;AAEA,MAAM,YAAY,CAAC,QAA0B;AAC3C,QAAM,cAAc,IAAI,QAAQ,IAAI,2BAAU,QAAQ,MAAM;AAE5D,MAAI,CAAC,eAAe,IAAI,QAAQ,SAAS,qCAAoB;AAC3D,QAAI,qCAAoB;AACtB,aAAO,2BAAa,SAAS,IAAI,IAAI,mCAAkB,CAAC;AAAA,IAC1D;AAEA,QAAI,8BAAa;AACf,YAAM,SAAS,IAAI,gBAAgB;AAAA,QACjC,cAAc,6CAA4B;AAAA,MAC5C,CAAC;AACD,aAAO,2BAAa;AAAA,QAClB,IAAI,IAAI,GAAG,4BAAW,YAAY,OAAO,SAAS,CAAC,EAAE;AAAA,MACvD;AAAA,IACF;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,2BAAa,KAAK;AAC3B;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { NextRequest } from 'next/server';\n\nexport type CabinIDUser = {\n id: string;\n firstName: string;\n lastName: string;\n email: string;\n phoneNumber: string;\n createdAt: string;\n updatedAt: string;\n};\n\nexport type CabinIDProviderProps = {\n user: CabinIDUser | null;\n signInUrl: string;\n};\n\nexport type LogoutParams = {\n redirectUrl?: string;\n};\n\nexport type ResponseDataType<T> = {\n data?: T;\n error: any;\n loading: boolean;\n};\n\n/**\n * Enables autocompletion for a union type, while keeping the ability to use any string\n * or type of `T`\n */\nexport type Autocomplete<U extends T, T = string> =\n | U\n | (T & Record<never, never>);\n\n/**\n * Omit without union flattening\n * */\nexport type Without<T, W> = {\n [P in keyof T as Exclude<P, W>]: T[P];\n};\n\nexport type IgnoredRoutesParam =\n | Array<RegExp | string>\n | RegExp\n | string\n | ((req: NextRequest) => boolean);\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { NextRequest } from 'next/server';\n\nexport type User = {\n id: string;\n avatar: string | null;\n email: string | null;\n phoneNumber: string;\n firstName: string;\n lastName: string;\n address: string | null;\n createdAt: string;\n updatedAt: string;\n};\n\nexport type CabinIDProviderProps = {\n user: User | null;\n};\n\nexport type LogoutParams = {\n redirectUrl?: string;\n};\n\nexport type ResponseDataType<T> = {\n data?: T;\n error: any;\n loading: boolean;\n};\n\n/**\n * Enables autocompletion for a union type, while keeping the ability to use any string\n * or type of `T`\n */\nexport type Autocomplete<U extends T, T = string> =\n | U\n | (T & Record<never, never>);\n\n/**\n * Omit without union flattening\n * */\nexport type Without<T, W> = {\n [P in keyof T as Exclude<P, W>]: T[P];\n};\n\nexport type IgnoredRoutesParam =\n | Array<RegExp | string>\n | RegExp\n | string\n | ((req: NextRequest) => boolean);\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -1,19 +1,18 @@
1
1
  import React from "react";
2
- import { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from "../constants";
2
+ import { getCurrentUser } from "./request";
3
3
  const CabinIDContext = React.createContext({
4
- signInUrl: "",
5
4
  user: null
6
5
  });
7
6
  const CabinIDProvider = ({ children }) => {
8
- const [user] = React.useState(null);
9
- const signInUrl = frontendApi || "";
10
- const redirectUrl = CUSTOM_AFTER_SIGN_IN_URL;
11
- if (!redirectUrl) {
12
- throw new Error(
13
- "You must provide the NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL environment variable."
14
- );
15
- }
16
- return /* @__PURE__ */ React.createElement(CabinIDContext.Provider, { value: { user, signInUrl } }, children);
7
+ const [user, setState] = React.useState(null);
8
+ React.useEffect(() => {
9
+ fetchUser();
10
+ }, []);
11
+ const fetchUser = async () => {
12
+ const user2 = await getCurrentUser();
13
+ setState(user2);
14
+ };
15
+ return /* @__PURE__ */ React.createElement(CabinIDContext.Provider, { value: { user } }, children);
17
16
  };
18
17
  export {
19
18
  CabinIDContext,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/client/provider.tsx"],"sourcesContent":["import React from 'react';\nimport type { PropsWithChildren } from 'react';\nimport { CabinIDProviderProps, CabinIDUser } from '../types';\nimport { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from '../constants';\n\nexport const CabinIDContext = React.createContext<CabinIDProviderProps>({\n signInUrl: '',\n user: null,\n});\n\nconst CabinIDProvider = ({ children }: PropsWithChildren<any>) => {\n const [user] = React.useState<CabinIDUser | null>(null);\n const signInUrl = frontendApi || '';\n\n const redirectUrl = CUSTOM_AFTER_SIGN_IN_URL;\n\n if (!redirectUrl) {\n throw new Error(\n 'You must provide the NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL environment variable.'\n );\n }\n\n return (\n <CabinIDContext.Provider value={{ user, signInUrl }}>\n {children}\n </CabinIDContext.Provider>\n );\n};\n\nexport { CabinIDProvider };\n"],"mappings":"AAAA,OAAO,WAAW;AAGlB,SAAS,0BAA0B,mBAAmB;AAE/C,MAAM,iBAAiB,MAAM,cAAoC;AAAA,EACtE,WAAW;AAAA,EACX,MAAM;AACR,CAAC;AAED,MAAM,kBAAkB,CAAC,EAAE,SAAS,MAA8B;AAChE,QAAM,CAAC,IAAI,IAAI,MAAM,SAA6B,IAAI;AACtD,QAAM,YAAY,eAAe;AAEjC,QAAM,cAAc;AAEpB,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SACE,oCAAC,eAAe,UAAf,EAAwB,OAAO,EAAE,MAAM,UAAU,KAC/C,QACH;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../../src/client/provider.tsx"],"sourcesContent":["import React from 'react';\nimport type { PropsWithChildren } from 'react';\nimport { CabinIDProviderProps, User } from '../types';\nimport { getCurrentUser } from './request';\n\nexport const CabinIDContext = React.createContext<CabinIDProviderProps>({\n user: null,\n});\n\nconst CabinIDProvider = ({ children }: PropsWithChildren<any>) => {\n const [user, setState] = React.useState<User | null>(null);\n\n React.useEffect(() => {\n fetchUser();\n }, []);\n\n const fetchUser = async () => {\n const user = await getCurrentUser();\n setState(user);\n };\n\n return (\n <CabinIDContext.Provider value={{ user }}>\n {children}\n </CabinIDContext.Provider>\n );\n};\n\nexport { CabinIDProvider };\n"],"mappings":"AAAA,OAAO,WAAW;AAGlB,SAAS,sBAAsB;AAExB,MAAM,iBAAiB,MAAM,cAAoC;AAAA,EACtE,MAAM;AACR,CAAC;AAED,MAAM,kBAAkB,CAAC,EAAE,SAAS,MAA8B;AAChE,QAAM,CAAC,MAAM,QAAQ,IAAI,MAAM,SAAsB,IAAI;AAEzD,QAAM,UAAU,MAAM;AACpB,cAAU;AAAA,EACZ,GAAG,CAAC,CAAC;AAEL,QAAM,YAAY,YAAY;AAC5B,UAAMA,QAAO,MAAM,eAAe;AAClC,aAASA,KAAI;AAAA,EACf;AAEA,SACE,oCAAC,eAAe,UAAf,EAAwB,OAAO,EAAE,KAAK,KACpC,QACH;AAEJ;","names":["user"]}
@@ -0,0 +1,19 @@
1
+ "use server";
2
+ import { baseApiUrl, constants } from "../constants";
3
+ import { cookies } from "next/headers";
4
+ const getCurrentUser = async () => {
5
+ var _a;
6
+ const token = (_a = cookies().get(constants.Cookies.Client)) == null ? void 0 : _a.value;
7
+ const response = await fetch(`${baseApiUrl}/user/me`, {
8
+ method: "GET",
9
+ headers: {
10
+ Authorization: `Bearer ${token}`
11
+ }
12
+ });
13
+ const data = await response.json();
14
+ return data;
15
+ };
16
+ export {
17
+ getCurrentUser
18
+ };
19
+ //# sourceMappingURL=request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/client/request.ts"],"sourcesContent":["'use server';\n\nimport { User } from 'src/types';\nimport { baseApiUrl, constants } from '../constants';\nimport { cookies } from 'next/headers';\n\nexport const getCurrentUser = async (): Promise<User | null> => {\n const token = cookies().get(constants.Cookies.Client)?.value;\n const response = await fetch(`${baseApiUrl}/user/me`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n const data: User = await response.json();\n return data;\n};\n"],"mappings":";AAGA,SAAS,YAAY,iBAAiB;AACtC,SAAS,eAAe;AAEjB,MAAM,iBAAiB,YAAkC;AANhE;AAOE,QAAM,SAAQ,aAAQ,EAAE,IAAI,UAAU,QAAQ,MAAM,MAAtC,mBAAyC;AACvD,QAAM,WAAW,MAAM,MAAM,GAAG,UAAU,YAAY;AAAA,IACpD,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,UAAU,KAAK;AAAA,IAChC;AAAA,EACF,CAAC;AACD,QAAM,OAAa,MAAM,SAAS,KAAK;AACvC,SAAO;AACT;","names":[]}
@@ -1 +1,7 @@
1
+ import { CabinIDProvider } from "./client/provider";
2
+ import { useUser } from "./hooks";
3
+ export {
4
+ CabinIDProvider,
5
+ useUser
6
+ };
1
7
  //# sourceMappingURL=component.client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../../src/component.client.ts"],"sourcesContent":["export { CabinIDProvider } from './client/provider';\nexport { useUser } from './hooks';\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,eAAe;","names":[]}
@@ -4,7 +4,7 @@ import { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from "../constants";
4
4
  const SignInButton = () => {
5
5
  const signInUrl = React.useMemo(() => {
6
6
  const params = new URLSearchParams({
7
- redirect_url: CUSTOM_AFTER_SIGN_IN_URL
7
+ redirect_url: CUSTOM_AFTER_SIGN_IN_URL || "/"
8
8
  });
9
9
  return frontendApi ? `http://${frontendApi}/sign-in?${params.toString()}` : "#";
10
10
  }, [frontendApi, CUSTOM_AFTER_SIGN_IN_URL]);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/components/SignInButton.tsx"],"sourcesContent":["import React from 'react';\nimport { CabinLogo } from '../icons/logo';\nimport { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from '../constants';\n\nexport const SignInButton = () => {\n const signInUrl = React.useMemo(() => {\n const params = new URLSearchParams({\n redirect_url: CUSTOM_AFTER_SIGN_IN_URL,\n });\n return frontendApi\n ? `http://${frontendApi}/sign-in?${params.toString()}`\n : '#';\n }, [frontendApi, CUSTOM_AFTER_SIGN_IN_URL]);\n\n return (\n <a\n href={signInUrl}\n className=\"max-w-48 pl-2 py-2 pr-4 bg-blue-600 rounded-full flex flex-row space-x-2 items-center hover:opacity-90 active:bg-blue-700\"\n >\n <CabinLogo />\n <span className=\"text-white text-sm\">Continue to CabinID</span>\n </a>\n );\n};\n"],"mappings":"AAAA,OAAO,WAAW;AAClB,SAAS,iBAAiB;AAC1B,SAAS,0BAA0B,mBAAmB;AAE/C,MAAM,eAAe,MAAM;AAChC,QAAM,YAAY,MAAM,QAAQ,MAAM;AACpC,UAAM,SAAS,IAAI,gBAAgB;AAAA,MACjC,cAAc;AAAA,IAChB,CAAC;AACD,WAAO,cACH,UAAU,WAAW,YAAY,OAAO,SAAS,CAAC,KAClD;AAAA,EACN,GAAG,CAAC,aAAa,wBAAwB,CAAC;AAE1C,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAM;AAAA,MACN,WAAU;AAAA;AAAA,IAEV,oCAAC,eAAU;AAAA,IACX,oCAAC,UAAK,WAAU,wBAAqB,qBAAmB;AAAA,EAC1D;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../../src/components/SignInButton.tsx"],"sourcesContent":["import React from 'react';\nimport { CabinLogo } from '../icons/logo';\nimport { CUSTOM_AFTER_SIGN_IN_URL, frontendApi } from '../constants';\n\nexport const SignInButton = () => {\n const signInUrl = React.useMemo(() => {\n const params = new URLSearchParams({\n redirect_url: CUSTOM_AFTER_SIGN_IN_URL || '/',\n });\n return frontendApi\n ? `http://${frontendApi}/sign-in?${params.toString()}`\n : '#';\n }, [frontendApi, CUSTOM_AFTER_SIGN_IN_URL]);\n\n return (\n <a\n href={signInUrl}\n className=\"max-w-48 pl-2 py-2 pr-4 bg-blue-600 rounded-full flex flex-row space-x-2 items-center hover:opacity-90 active:bg-blue-700\"\n >\n <CabinLogo />\n <span className=\"text-white text-sm\">Continue to CabinID</span>\n </a>\n );\n};\n"],"mappings":"AAAA,OAAO,WAAW;AAClB,SAAS,iBAAiB;AAC1B,SAAS,0BAA0B,mBAAmB;AAE/C,MAAM,eAAe,MAAM;AAChC,QAAM,YAAY,MAAM,QAAQ,MAAM;AACpC,UAAM,SAAS,IAAI,gBAAgB;AAAA,MACjC,cAAc,4BAA4B;AAAA,IAC5C,CAAC;AACD,WAAO,cACH,UAAU,WAAW,YAAY,OAAO,SAAS,CAAC,KAClD;AAAA,EACN,GAAG,CAAC,aAAa,wBAAwB,CAAC;AAE1C,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAM;AAAA,MACN,WAAU;AAAA;AAAA,IAEV,oCAAC,eAAU;AAAA,IACX,oCAAC,UAAK,WAAU,wBAAqB,qBAAmB;AAAA,EAC1D;AAEJ;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import { parsePublishableKey } from "./utils/key";
2
2
  import { joinPaths } from "./utils/path";
3
- const API_URL = "https://api.cabinid.dev/";
3
+ const API_URL = "http://localhost:3001/";
4
4
  const API_VERSION = "v1";
5
5
  const PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_CABIN_ID_PUBLISH_KEY || "";
6
6
  const SECRET_KEY = process.env.CABIN_ID_SECRET_KEY || "";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/constants.ts"],"sourcesContent":["import { parsePublishableKey } from './utils/key';\nimport { joinPaths } from './utils/path';\n\n/* The line `// export const API_URL = 'https://api.cabinid.dev/';` is a commented-out line of code in\nTypeScript. It is currently not active or being used in the code because it is preceded by `//`,\nwhich makes it a comment. */\nexport const API_URL = 'https://api.cabinid.dev/';\n// export const API_URL = 'http://localhost:3001/';\nexport const API_VERSION = 'v1';\nexport const PUBLISHABLE_KEY =\n process.env.NEXT_PUBLIC_CABIN_ID_PUBLISH_KEY! || '';\nexport const SECRET_KEY = process.env.CABIN_ID_SECRET_KEY! || '';\nexport const CUSTOM_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_IN_URL! || '';\nexport const CUSTOM_SIGN_Up_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_UP_URL! || '';\nexport const CUSTOM_AFTER_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL || '';\nexport const CUSTOM_AFTER_SIGN_UP_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_UP_URL || '';\n\nexport const baseApiUrl = joinPaths(API_URL, API_VERSION);\nexport const frontendApi = parsePublishableKey(PUBLISHABLE_KEY);\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Client: '__client',\n User: '__user',\n} as const;\n\nconst QueryParams = {\n UserId: 'user_id',\n Token: 'token',\n} as const;\n\nconst Headers = {\n AuthToken: 'x-cabin-id-auth-token',\n AuthSignature: 'x-cabin-id-auth-signature',\n AuthStatus: 'x-cabin-id-auth-status',\n AuthReason: 'x-cabin-id-auth-reason',\n AuthMessage: 'x-cabin-id-auth-message',\n CabinIdUrl: 'x-cabin-id-cabin-id-url',\n EnableDebug: 'x-cabin-id-debug',\n CabinIdRedirectTo: 'x-cabin-id-redirect-to',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n Authorization: 'authorization',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n ForwardedHost: 'x-forwarded-host',\n Accept: 'accept',\n Referrer: 'referer',\n UserAgent: 'user-agent',\n Origin: 'origin',\n Host: 'host',\n ContentType: 'content-type',\n SecFetchDest: 'sec-fetch-dest',\n Location: 'location',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\nconst NextHeaders = {\n NextRewrite: 'x-middleware-rewrite',\n NextResume: 'x-middleware-next',\n NextRedirect: 'Location',\n // Used by next to identify internal navigation for app router\n NextUrl: 'next-url',\n NextAction: 'next-action',\n // Used by next to identify internal navigation for pages router\n NextjsData: 'x-nextjs-data',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParams,\n NextHeaders,\n} as const;\n\nexport type Constants = typeof constants;\n"],"mappings":"AAAA,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;AAKnB,MAAM,UAAU;AAEhB,MAAM,cAAc;AACpB,MAAM,kBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,aAAa,QAAQ,IAAI,uBAAwB;AACvD,MAAM,qBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,qBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,2BACX,QAAQ,IAAI,0CAA0C;AACjD,MAAM,2BACX,QAAQ,IAAI,0CAA0C;AAEjD,MAAM,aAAa,UAAU,SAAS,WAAW;AACjD,MAAM,cAAc,oBAAoB,eAAe;AAE9D,MAAM,aAAa;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AACZ;AAEA,MAAM,UAAU;AAAA,EACd,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AACR;AAEA,MAAM,cAAc;AAAA,EAClB,QAAQ;AAAA,EACR,OAAO;AACT;AAEA,MAAM,UAAU;AAAA,EACd,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,0BAA0B;AAAA,EAC1B,eAAe;AAAA,EACf,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAAA,EACd,UAAU;AACZ;AAEA,MAAM,eAAe;AAAA,EACnB,MAAM;AACR;AAEA,MAAM,cAAc;AAAA,EAClB,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,cAAc;AAAA;AAAA,EAEd,SAAS;AAAA,EACT,YAAY;AAAA;AAAA,EAEZ,YAAY;AACd;AAKO,MAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/constants.ts"],"sourcesContent":["import { parsePublishableKey } from './utils/key';\nimport { joinPaths } from './utils/path';\n\n// export const API_URL = 'https://api.cabinid.dev/';\nexport const API_URL = 'http://localhost:3001/';\nexport const API_VERSION = 'v1';\nexport const PUBLISHABLE_KEY =\n process.env.NEXT_PUBLIC_CABIN_ID_PUBLISH_KEY! || '';\nexport const SECRET_KEY = process.env.CABIN_ID_SECRET_KEY! || '';\nexport const CUSTOM_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_IN_URL! || '';\nexport const CUSTOM_SIGN_Up_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_SIGN_UP_URL! || '';\nexport const CUSTOM_AFTER_SIGN_IN_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_IN_URL || '';\nexport const CUSTOM_AFTER_SIGN_UP_URL =\n process.env.NEXT_PUBLIC_CABIN_ID_AFTER_SIGN_UP_URL || '';\n\nexport const baseApiUrl = joinPaths(API_URL, API_VERSION);\nexport const frontendApi = parsePublishableKey(PUBLISHABLE_KEY);\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Client: '__client',\n User: '__user',\n} as const;\n\nconst QueryParams = {\n UserId: 'user_id',\n Token: 'token',\n} as const;\n\nconst Headers = {\n AuthToken: 'x-cabin-id-auth-token',\n AuthSignature: 'x-cabin-id-auth-signature',\n AuthStatus: 'x-cabin-id-auth-status',\n AuthReason: 'x-cabin-id-auth-reason',\n AuthMessage: 'x-cabin-id-auth-message',\n CabinIdUrl: 'x-cabin-id-cabin-id-url',\n EnableDebug: 'x-cabin-id-debug',\n CabinIdRedirectTo: 'x-cabin-id-redirect-to',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n Authorization: 'authorization',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n ForwardedHost: 'x-forwarded-host',\n Accept: 'accept',\n Referrer: 'referer',\n UserAgent: 'user-agent',\n Origin: 'origin',\n Host: 'host',\n ContentType: 'content-type',\n SecFetchDest: 'sec-fetch-dest',\n Location: 'location',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\nconst NextHeaders = {\n NextRewrite: 'x-middleware-rewrite',\n NextResume: 'x-middleware-next',\n NextRedirect: 'Location',\n // Used by next to identify internal navigation for app router\n NextUrl: 'next-url',\n NextAction: 'next-action',\n // Used by next to identify internal navigation for pages router\n NextjsData: 'x-nextjs-data',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParams,\n NextHeaders,\n} as const;\n\nexport type Constants = typeof constants;\n"],"mappings":"AAAA,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;AAGnB,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,kBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,aAAa,QAAQ,IAAI,uBAAwB;AACvD,MAAM,qBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,qBACX,QAAQ,IAAI,oCAAqC;AAC5C,MAAM,2BACX,QAAQ,IAAI,0CAA0C;AACjD,MAAM,2BACX,QAAQ,IAAI,0CAA0C;AAEjD,MAAM,aAAa,UAAU,SAAS,WAAW;AACjD,MAAM,cAAc,oBAAoB,eAAe;AAE9D,MAAM,aAAa;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AACZ;AAEA,MAAM,UAAU;AAAA,EACd,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AACR;AAEA,MAAM,cAAc;AAAA,EAClB,QAAQ;AAAA,EACR,OAAO;AACT;AAEA,MAAM,UAAU;AAAA,EACd,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,0BAA0B;AAAA,EAC1B,eAAe;AAAA,EACf,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAAA,EACd,UAAU;AACZ;AAEA,MAAM,eAAe;AAAA,EACnB,MAAM;AACR;AAEA,MAAM,cAAc;AAAA,EAClB,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,cAAc;AAAA;AAAA,EAEd,SAAS;AAAA,EACT,YAAY;AAAA;AAAA,EAEZ,YAAY;AACd;AAKO,MAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -0,0 +1,9 @@
1
+ {
2
+ "sideEffects": false,
3
+ "imports": {
4
+ "#components": {
5
+ "react-server": "./components.server.js",
6
+ "default": "./components.client.js"
7
+ }
8
+ }
9
+ }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/server/getCurrentUser.ts"],"sourcesContent":["import { baseApiUrl, SECRET_KEY } from '../constants';\n\nimport { auth } from './auth';\n\nexport type User = {\n id: string;\n avatar: string | null;\n email: string | null;\n phoneNumber: string;\n firstName: string;\n lastName: string;\n address: string | null;\n createdAt: string;\n updatedAt: string;\n};\n\nexport async function currentUser(): Promise<User | null> {\n const { userId } = auth();\n if (!userId) return null;\n\n const response = await fetch(`${baseApiUrl}/user/${userId}`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${SECRET_KEY}`,\n },\n });\n const data: User = await response.json();\n return data;\n}\n"],"mappings":"AAAA,SAAS,YAAY,kBAAkB;AAEvC,SAAS,YAAY;AAcrB,eAAsB,cAAoC;AACxD,QAAM,EAAE,OAAO,IAAI,KAAK;AACxB,MAAI,CAAC;AAAQ,WAAO;AAEpB,QAAM,WAAW,MAAM,MAAM,GAAG,UAAU,SAAS,MAAM,IAAI;AAAA,IAC3D,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,UAAU,UAAU;AAAA,IACrC;AAAA,EACF,CAAC;AACD,QAAM,OAAa,MAAM,SAAS,KAAK;AACvC,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../../src/server/getCurrentUser.ts"],"sourcesContent":["import { User } from '../types';\nimport { baseApiUrl, SECRET_KEY } from '../constants';\n\nimport { auth } from './auth';\n\nexport async function currentUser(): Promise<User | null> {\n const { userId } = auth();\n if (!userId) return null;\n\n const response = await fetch(`${baseApiUrl}/user/${userId}`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${SECRET_KEY}`,\n },\n });\n\n const data: User = await response.json();\n return data;\n}\n"],"mappings":"AACA,SAAS,YAAY,kBAAkB;AAEvC,SAAS,YAAY;AAErB,eAAsB,cAAoC;AACxD,QAAM,EAAE,OAAO,IAAI,KAAK;AACxB,MAAI,CAAC;AAAQ,WAAO;AAEpB,QAAM,WAAW,MAAM,MAAM,GAAG,UAAU,SAAS,MAAM,IAAI;AAAA,IAC3D,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,UAAU,UAAU;AAAA,IACrC;AAAA,EACF,CAAC;AAED,QAAM,OAAa,MAAM,SAAS,KAAK;AACvC,SAAO;AACT;","names":[]}
@@ -1,7 +1,9 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import {
3
3
  constants,
4
+ CUSTOM_AFTER_SIGN_IN_URL,
4
5
  CUSTOM_SIGN_IN_URL,
6
+ frontendApi,
5
7
  PUBLISHABLE_KEY,
6
8
  SECRET_KEY
7
9
  } from "../constants";
@@ -11,7 +13,7 @@ import {
11
13
  assertKey,
12
14
  redirectAdapter
13
15
  } from "./utils";
14
- import { isRedirect, mergeResponses, setHeader } from "../utils/response";
16
+ import { isRedirect, setHeader } from "../utils/response";
15
17
  import { createRedirect } from "./createRedirect";
16
18
  const DEFAULT_CONFIG_MATCHER = [
17
19
  "/((?!.+\\.[\\w]+$|_next).*)",
@@ -46,12 +48,6 @@ const authMiddleware = (...args) => {
46
48
  const isPublicRoute = createRouteMatcher(
47
49
  withDefaultPublicRoutes(options.publicRoutes)
48
50
  );
49
- const isApiRoute = createApiRoutes(options.apiRoutes);
50
- const defaultAfterAuth = createDefaultAfterAuth(
51
- isPublicRoute,
52
- isApiRoute,
53
- options
54
- );
55
51
  return async (_req, evt) => {
56
52
  const url = _req.nextUrl;
57
53
  const accessToken = url.searchParams.get(constants.QueryParams.Token);
@@ -74,21 +70,6 @@ const authMiddleware = (...args) => {
74
70
  "before-auth-redirect"
75
71
  );
76
72
  }
77
- const requestState = {
78
- token: accessToken,
79
- userId
80
- };
81
- const auth = {
82
- ...requestState,
83
- isPublicRoute: isPublicRoute(nextRequest),
84
- isApiRoute: isApiRoute(nextRequest)
85
- };
86
- const afterAuthRes = await (options.afterAuth || defaultAfterAuth)(
87
- auth,
88
- nextRequest,
89
- evt
90
- );
91
- const finalRes = mergeResponses(beforeAuthRes, afterAuthRes) || NextResponse.next();
92
73
  if (accessToken && userId) {
93
74
  const path = url.pathname;
94
75
  const response = NextResponse.redirect(new URL(path || "/", _req.url));
@@ -96,10 +77,7 @@ const authMiddleware = (...args) => {
96
77
  response.cookies.set(constants.Cookies.User, userId);
97
78
  return response;
98
79
  }
99
- const result = (
100
- // decorateRequest(_req, finalRes, requestState, secretKey) ||
101
- NextResponse.next()
102
- );
80
+ const result = checkAuth(_req);
103
81
  return result;
104
82
  };
105
83
  };
@@ -156,6 +134,26 @@ const createDefaultAfterAuth = (isPublicRoute, isApiRoute, options) => {
156
134
  return NextResponse.next();
157
135
  };
158
136
  };
137
+ const checkAuth = (req) => {
138
+ const accessToken = req.cookies.get(constants.Cookies.Client);
139
+ if (!accessToken && req.nextUrl.href !== CUSTOM_SIGN_IN_URL) {
140
+ if (CUSTOM_SIGN_IN_URL) {
141
+ return NextResponse.redirect(new URL(CUSTOM_SIGN_IN_URL));
142
+ }
143
+ if (frontendApi) {
144
+ const params = new URLSearchParams({
145
+ redirect_url: CUSTOM_AFTER_SIGN_IN_URL || "/"
146
+ });
147
+ return NextResponse.redirect(
148
+ new URL(`${frontendApi}/sign-in?${params.toString()}`)
149
+ );
150
+ }
151
+ throw new Error(
152
+ "You are not authentication. Please provide CABIN ID PUBLISH KEY to redirect to authentication page"
153
+ );
154
+ }
155
+ return NextResponse.next();
156
+ };
159
157
  export {
160
158
  DEFAULT_API_ROUTES,
161
159
  DEFAULT_CONFIG_MATCHER,