@redmix/auth-clerk-setup 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Redmix
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # Authentication
2
+
3
+ ## Contributing
4
+
5
+ If you want to contribute a new auth provider integration we recommend you
6
+ start by implementing it as a custom auth provider in a Redwood App first. When
7
+ that works you can package it up as an npm package and publish it on your own.
8
+ You can then create a PR on this repo with support for your new auth provider
9
+ in our `yarn rw setup auth` cli command. The easiest option is probably to just
10
+ look at one of the existing auth providers in
11
+ `packages/cli/src/commands/setup/auth/providers` and the corresponding
12
+ templates in `../templates`.
13
+
14
+ If you need help setting up a custom auth provider you can read the auth docs
15
+ on the web.
16
+
17
+ ### Contributing to the base auth implementation
18
+
19
+ If you want to contribute to our auth implementation, the interface towards
20
+ both auth service providers and RW apps we recommend you start looking in
21
+ `authFactory.ts` and then continue to `AuthProvider.tsx`. `AuthProvider.tsx`
22
+ has most of our implementation together with all the custom hooks it uses.
23
+ Another file to be accustomed with is `AuthContext.ts`. The interface in there
24
+ has pretty good code comments, and is what will be exposed to RW apps.
25
+
26
+ ## getCurrentUser
27
+
28
+ `getCurrentUser` returns the user information together with
29
+ an optional collection of roles used by requireAuth() to check if the user is authenticated or has role-based access.
30
+
31
+ Use in conjunction with `requireAuth` in your services to check that a user is logged in, whether or not they are assigned a role, and optionally raise an error if they're not.
32
+
33
+ ```js
34
+ @param decoded - The decoded access token containing user info and JWT claims like `sub`
35
+ @param { token, SupportedAuthTypes type } - The access token itself as well as the auth provider type
36
+ @param { APIGatewayEvent event, Context context } - An object which contains information from the invoker
37
+ such as headers and cookies, and the context information about the invocation such as IP Address
38
+ ```
39
+
40
+ ### Examples
41
+
42
+ #### Checks if currentUser is authenticated
43
+
44
+ This example is the standard use of `getCurrentUser`.
45
+
46
+ ```js
47
+ export const getCurrentUser = async (
48
+ decoded,
49
+ { _token, _type },
50
+ { _event, _context },
51
+ ) => {
52
+ return { ...decoded, roles: parseJWT({ decoded }).roles }
53
+ }
54
+ ```
55
+
56
+ #### User details fetched via database query
57
+
58
+ ```js
59
+ export const getCurrentUser = async (decoded) => {
60
+ return await db.user.findUnique({ where: { decoded.email } })
61
+ }
62
+ ```
63
+
64
+ #### User info is decoded from the access token
65
+
66
+ ```js
67
+ export const getCurrentUser = async (decoded) => {
68
+ return { ...decoded }
69
+ }
70
+ ```
71
+
72
+ #### User info is contained in the decoded token and roles extracted
73
+
74
+ ```js
75
+ export const getCurrentUser = async (decoded) => {
76
+ return { ...decoded, roles: parseJWT({ decoded }).roles }
77
+ }
78
+ ```
79
+
80
+ #### User record query by email with namespaced app_metadata roles as Auth0 requires custom JWT claims to be namespaced
81
+
82
+ ```js
83
+ export const getCurrentUser = async (decoded) => {
84
+ const currentUser = await db.user.findUnique({
85
+ where: { email: decoded.email },
86
+ })
87
+
88
+ return {
89
+ ...currentUser,
90
+ roles: parseJWT({ decoded: decoded, namespace: NAMESPACE }).roles,
91
+ }
92
+ }
93
+ ```
94
+
95
+ #### User record query by an identity with app_metadata roles
96
+
97
+ ```js
98
+ const getCurrentUser = async (decoded) => {
99
+ const currentUser = await db.user.findUnique({
100
+ where: { userIdentity: decoded.sub },
101
+ })
102
+ return {
103
+ ...currentUser,
104
+ roles: parseJWT({ decoded: decoded }).roles,
105
+ }
106
+ }
107
+ ```
108
+
109
+ #### Cookies and other request information are available in the req parameter, just in case
110
+
111
+ ```js
112
+ const getCurrentUser = async (_decoded, _raw, { event, _context }) => {
113
+ const cookies = cookie(event.headers.cookies)
114
+ const session = cookies['my.cookie.name']
115
+ const currentUser = await db.sessions.findUnique({ where: { id: session } })
116
+ return currentUser
117
+ }
118
+ ```
119
+
120
+ ## requireAuth
121
+
122
+ Use `requireAuth` in your services to check that a user is logged in, whether or not they are assigned a role, and optionally raise an error if they're not.
123
+
124
+ ```js
125
+ @param {string=} roles - An optional role or list of roles
126
+ @param {string[]=} roles - An optional list of roles
127
+
128
+ @returns {boolean} - If the currentUser is authenticated (and assigned one of the given roles)
129
+
130
+ @throws {AuthenticationError} - If the currentUser is not authenticated
131
+ @throws {ForbiddenError} If the currentUser is not allowed due to role permissions
132
+ ```
133
+
134
+ ### Examples
135
+
136
+ #### Checks if currentUser is authenticated
137
+
138
+ ```js
139
+ requireAuth()
140
+ ```
141
+
142
+ #### Checks if currentUser is authenticated and assigned one of the given roles
143
+
144
+ ```js
145
+ requireAuth({ role: 'admin' })
146
+ requireAuth({ role: ['editor', 'author'] })
147
+ requireAuth({ role: ['publisher'] })
148
+ ```
@@ -0,0 +1,2 @@
1
+ export * from './setup';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
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 __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var index_exports = {};
17
+ module.exports = __toCommonJS(index_exports);
18
+ __reExport(index_exports, require("./setup"), module.exports);
19
+ // Annotate the CommonJS export names for ESM import in node:
20
+ 0 && (module.exports = {
21
+ ...require("./setup")
22
+ });
@@ -0,0 +1,13 @@
1
+ import type yargs from 'yargs';
2
+ export declare const command = "clerk";
3
+ export declare const description = "Set up auth for for Clerk";
4
+ export declare function builder(yargs: yargs.Argv): yargs.Argv<{
5
+ force: boolean;
6
+ } & {
7
+ verbose: boolean;
8
+ }>;
9
+ export interface Args {
10
+ force: boolean;
11
+ }
12
+ export declare function handler(options: Args): Promise<void>;
13
+ //# sourceMappingURL=setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAI9B,eAAO,MAAM,OAAO,UAAU,CAAA;AAC9B,eAAO,MAAM,WAAW,8BAA8B,CAAA;AAEtD,wBAAgB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI;;;;GAExC;AAED,MAAM,WAAW,IAAI;IACnB,KAAK,EAAE,OAAO,CAAA;CACf;AAED,wBAAsB,OAAO,CAAC,OAAO,EAAE,IAAI,iBAG1C"}
package/dist/setup.js ADDED
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var setup_exports = {};
30
+ __export(setup_exports, {
31
+ builder: () => builder,
32
+ command: () => command,
33
+ description: () => description,
34
+ handler: () => handler
35
+ });
36
+ module.exports = __toCommonJS(setup_exports);
37
+ var import_cli_helpers = require("@redmix/cli-helpers");
38
+ const command = "clerk";
39
+ const description = "Set up auth for for Clerk";
40
+ function builder(yargs) {
41
+ return (0, import_cli_helpers.standardAuthBuilder)(yargs);
42
+ }
43
+ async function handler(options) {
44
+ const { handler: handler2 } = await import("./setupHandler.js");
45
+ return handler2(options);
46
+ }
47
+ // Annotate the CommonJS export names for ESM import in node:
48
+ 0 && (module.exports = {
49
+ builder,
50
+ command,
51
+ description,
52
+ handler
53
+ });
@@ -0,0 +1,3 @@
1
+ import type { Args } from './setup';
2
+ export declare const handler: ({ force: forceArg }: Args) => Promise<void>;
3
+ //# sourceMappingURL=setupHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setupHandler.d.ts","sourceRoot":"","sources":["../src/setupHandler.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AAMnC,eAAO,MAAM,OAAO,wBAA+B,IAAI,kBA4BtD,CAAA"}
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var setupHandler_exports = {};
30
+ __export(setupHandler_exports, {
31
+ handler: () => handler
32
+ });
33
+ module.exports = __toCommonJS(setupHandler_exports);
34
+ var import_fs = __toESM(require("fs"));
35
+ var import_path = __toESM(require("path"));
36
+ var import_cli_helpers = require("@redmix/cli-helpers");
37
+ const { version } = JSON.parse(
38
+ import_fs.default.readFileSync(import_path.default.resolve(__dirname, "../package.json"), "utf-8")
39
+ );
40
+ const handler = async ({ force: forceArg }) => {
41
+ (0, import_cli_helpers.standardAuthHandler)({
42
+ basedir: __dirname,
43
+ forceArg,
44
+ authDecoderImport: `import { clerkAuthDecoder as authDecoder } from '@redmix/auth-clerk-api'`,
45
+ provider: "clerk",
46
+ webPackages: ["@clerk/clerk-react@^4", `@redmix/auth-clerk-web@${version}`],
47
+ apiPackages: [`@redmix/auth-clerk-api@${version}`],
48
+ notes: [
49
+ "You'll need to add two env vars to your .env file:",
50
+ "",
51
+ '```title=".env"',
52
+ 'CLERK_PUBLISHABLE_KEY="..."',
53
+ 'CLERK_SECRET_KEY="..."',
54
+ "```",
55
+ "",
56
+ `You can find their values under "API Keys" on your Clerk app's dashboard.`,
57
+ "Be sure to include `CLERK_PUBLISHABLE_KEY` in the `includeEnvironmentVariables` array in redwood.toml.",
58
+ "",
59
+ '```toml title="redwood.toml"',
60
+ "includeEnvironmentVariables = [",
61
+ ' "CLERK_PUBLISHABLE_KEY"',
62
+ "]",
63
+ "```",
64
+ "",
65
+ "Also see https://redwoodjs.com/docs/auth/clerk for a full walkthrough."
66
+ ]
67
+ });
68
+ };
69
+ // Annotate the CommonJS export names for ESM import in node:
70
+ 0 && (module.exports = {
71
+ handler
72
+ });
@@ -0,0 +1,118 @@
1
+ import { AuthenticationError, ForbiddenError } from '@redmix/graphql-server'
2
+
3
+ import { logger } from 'src/lib/logger'
4
+
5
+ /**
6
+ * getCurrentUser returns the user information.
7
+ * Once you're ready you can also return a collection of roles
8
+ * for `requireAuth` and the Router to use.
9
+ *
10
+ * @param decoded - The decoded access token containing user info and JWT claims like `sub`. Note could be null.
11
+ * @param { token, SupportedAuthTypes type } - The access token itself as well as the auth provider type
12
+ * @param { APIGatewayEvent event, Context context } - An object which contains information from the invoker
13
+ * such as headers and cookies, and the context information about the invocation such as IP Address
14
+ *
15
+ * @see https://github.com/redmix-run/redmix/tree/main/packages/auth for examples
16
+ */
17
+ export const getCurrentUser = async (
18
+ decoded,
19
+ /* eslint-disable-next-line @typescript-eslint/no-unused-vars */
20
+ { token, type },
21
+ /* eslint-disable-next-line @typescript-eslint/no-unused-vars */
22
+ { event, context }
23
+ ) => {
24
+ if (!decoded) {
25
+ logger.warn('Missing decoded user')
26
+ return null
27
+ }
28
+
29
+ const { id, ..._rest } = decoded
30
+
31
+ // Be careful to only return information that should be accessible on the web side.
32
+ return { id }
33
+ }
34
+
35
+ /**
36
+ * The user is authenticated if there is a currentUser in the context
37
+ *
38
+ * @returns {boolean} - If the currentUser is authenticated
39
+ */
40
+ export const isAuthenticated = () => {
41
+ return !!context.currentUser
42
+ }
43
+
44
+ /**
45
+ * When checking role membership, roles can be a single value, a list, or none.
46
+ * You can use Prisma enums too (if you're using them for roles), just import your enum type from `@prisma/client`
47
+ */
48
+ type AllowedRoles = string | string[] | undefined
49
+
50
+ /**
51
+ * When checking role membership, roles can be a single value, a list, or none.
52
+ * You can use Prisma enums too (if you're using them for roles), just import your enum type from `@prisma/client`
53
+ */
54
+
55
+ /**
56
+ * Checks if the currentUser is authenticated (and assigned one of the given roles)
57
+ *
58
+ * @param roles: {@link AllowedRoles} - Checks if the currentUser is assigned one of these roles
59
+ *
60
+ * @returns {boolean} - Returns true if the currentUser is logged in and assigned one of the given roles,
61
+ * or when no roles are provided to check against. Otherwise returns false.
62
+ */
63
+ export const hasRole = (roles: AllowedRoles): boolean => {
64
+ if (!isAuthenticated()) {
65
+ return false
66
+ }
67
+
68
+ const currentUserRoles = context.currentUser?.roles
69
+
70
+ if (typeof roles === 'string') {
71
+ if (typeof currentUserRoles === 'string') {
72
+ // roles to check is a string, currentUser.roles is a string
73
+ return currentUserRoles === roles
74
+ } else if (Array.isArray(currentUserRoles)) {
75
+ // roles to check is a string, currentUser.roles is an array
76
+ return currentUserRoles?.some((allowedRole) => roles === allowedRole)
77
+ }
78
+ }
79
+
80
+ if (Array.isArray(roles)) {
81
+ if (Array.isArray(currentUserRoles)) {
82
+ // roles to check is an array, currentUser.roles is an array
83
+ return currentUserRoles?.some((allowedRole) =>
84
+ roles.includes(allowedRole)
85
+ )
86
+ } else if (typeof currentUserRoles === 'string') {
87
+ // roles to check is an array, currentUser.roles is a string
88
+ return roles.some((allowedRole) => currentUserRoles === allowedRole)
89
+ }
90
+ }
91
+
92
+ // roles not found
93
+ return false
94
+ }
95
+
96
+ /**
97
+ * Use requireAuth in your services to check that a user is logged in,
98
+ * whether or not they are assigned a role, and optionally raise an
99
+ * error if they're not.
100
+ *
101
+ * @param roles: {@link AllowedRoles} - When checking role membership, these roles grant access.
102
+ *
103
+ * @returns - If the currentUser is authenticated (and assigned one of the given roles)
104
+ *
105
+ * @throws {@link AuthenticationError} - If the currentUser is not authenticated
106
+ * @throws {@link ForbiddenError} If the currentUser is not allowed due to role permissions
107
+ *
108
+ * @see https://github.com/redmix-run/redmix/tree/main/packages/auth for examples
109
+ */
110
+ export const requireAuth = ({ roles }: { roles?: AllowedRoles } = {}) => {
111
+ if (!isAuthenticated()) {
112
+ throw new AuthenticationError("You don't have permission to do that.")
113
+ }
114
+
115
+ if (roles && !hasRole(roles)) {
116
+ throw new ForbiddenError("You don't have access to do that.")
117
+ }
118
+ }
@@ -0,0 +1,66 @@
1
+ 'use client'
2
+
3
+ import React, { useEffect } from 'react'
4
+
5
+ import { ClerkProvider, useUser } from '@clerk/clerk-react'
6
+
7
+ import { createAuth } from '@redmix/auth-clerk-web'
8
+ import { navigate } from '@redmix/router'
9
+
10
+ export const { AuthProvider: ClerkRwAuthProvider, useAuth } = createAuth()
11
+
12
+ const ClerkStatusUpdater = () => {
13
+ const { isSignedIn, user, isLoaded } = useUser()
14
+ const { reauthenticate } = useAuth()
15
+
16
+ useEffect(() => {
17
+ if (isLoaded) {
18
+ reauthenticate()
19
+ }
20
+ }, [isSignedIn, user, reauthenticate, isLoaded])
21
+
22
+ return null
23
+ }
24
+
25
+ type ClerkOptions =
26
+ | { publishableKey: string; frontendApi?: never }
27
+ | { publishableKey?: never; frontendApi: string }
28
+
29
+ interface Props {
30
+ children: React.ReactNode
31
+ }
32
+
33
+ const ClerkProviderWrapper = ({
34
+ children,
35
+ clerkOptions,
36
+ }: Props & { clerkOptions: ClerkOptions }) => {
37
+ const { reauthenticate } = useAuth()
38
+
39
+ return (
40
+ <ClerkProvider
41
+ {...clerkOptions}
42
+ navigate={(to) => reauthenticate().then(() => navigate(to))}
43
+ >
44
+ {children}
45
+ <ClerkStatusUpdater />
46
+ </ClerkProvider>
47
+ )
48
+ }
49
+
50
+ export const AuthProvider = ({ children }: Props) => {
51
+ const publishableKey = process.env.CLERK_PUBLISHABLE_KEY
52
+ const frontendApi =
53
+ process.env.CLERK_FRONTEND_API_URL || process.env.CLERK_FRONTEND_API
54
+
55
+ const clerkOptions: ClerkOptions = publishableKey
56
+ ? { publishableKey }
57
+ : { frontendApi }
58
+
59
+ return (
60
+ <ClerkRwAuthProvider>
61
+ <ClerkProviderWrapper clerkOptions={clerkOptions}>
62
+ {children}
63
+ </ClerkProviderWrapper>
64
+ </ClerkRwAuthProvider>
65
+ )
66
+ }
@@ -0,0 +1,64 @@
1
+ import React, { useEffect } from 'react'
2
+
3
+ import { ClerkProvider, useUser } from '@clerk/clerk-react'
4
+
5
+ import { createAuth } from '@redmix/auth-clerk-web'
6
+ import { navigate } from '@redmix/router'
7
+
8
+ export const { AuthProvider: ClerkRwAuthProvider, useAuth } = createAuth()
9
+
10
+ const ClerkStatusUpdater = () => {
11
+ const { isSignedIn, user, isLoaded } = useUser()
12
+ const { reauthenticate } = useAuth()
13
+
14
+ useEffect(() => {
15
+ if (isLoaded) {
16
+ reauthenticate()
17
+ }
18
+ }, [isSignedIn, user, reauthenticate, isLoaded])
19
+
20
+ return null
21
+ }
22
+
23
+ type ClerkOptions =
24
+ | { publishableKey: string; frontendApi?: never }
25
+ | { publishableKey?: never; frontendApi: string }
26
+
27
+ interface Props {
28
+ children: React.ReactNode
29
+ }
30
+
31
+ const ClerkProviderWrapper = ({
32
+ children,
33
+ clerkOptions,
34
+ }: Props & { clerkOptions: ClerkOptions }) => {
35
+ const { reauthenticate } = useAuth()
36
+
37
+ return (
38
+ <ClerkProvider
39
+ {...clerkOptions}
40
+ navigate={(to) => reauthenticate().then(() => navigate(to))}
41
+ >
42
+ {children}
43
+ <ClerkStatusUpdater />
44
+ </ClerkProvider>
45
+ )
46
+ }
47
+
48
+ export const AuthProvider = ({ children }: Props) => {
49
+ const publishableKey = process.env.CLERK_PUBLISHABLE_KEY
50
+ const frontendApi =
51
+ process.env.CLERK_FRONTEND_API_URL || process.env.CLERK_FRONTEND_API
52
+
53
+ const clerkOptions: ClerkOptions = publishableKey
54
+ ? { publishableKey }
55
+ : { frontendApi }
56
+
57
+ return (
58
+ <ClerkRwAuthProvider>
59
+ <ClerkProviderWrapper clerkOptions={clerkOptions}>
60
+ {children}
61
+ </ClerkProviderWrapper>
62
+ </ClerkRwAuthProvider>
63
+ )
64
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@redmix/auth-clerk-setup",
3
+ "version": "0.0.1",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/redmix-run/redmix.git",
7
+ "directory": "packages/auth-providers/clerk/setup"
8
+ },
9
+ "license": "MIT",
10
+ "type": "commonjs",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./dist/setup": {
17
+ "types": "./dist/setup.d.ts",
18
+ "default": "./dist/setup.js"
19
+ },
20
+ "./dist/setupHandler": {
21
+ "types": "./dist/setupHandler.d.ts",
22
+ "default": "./dist/setupHandler.js"
23
+ }
24
+ },
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsx ./build.mts && yarn build:types",
32
+ "build:pack": "yarn pack -o redmix-auth-clerk-setup.tgz",
33
+ "build:types": "tsc --build --verbose ./tsconfig.json",
34
+ "build:watch": "nodemon --watch src --ext \"js,jsx,ts,tsx,template\" --ignore dist --exec \"yarn build\"",
35
+ "check:attw": "yarn attw -P",
36
+ "check:package": "concurrently npm:check:attw yarn:publint",
37
+ "prepublishOnly": "NODE_ENV=production yarn build"
38
+ },
39
+ "dependencies": {
40
+ "@redmix/cli-helpers": "0.0.1"
41
+ },
42
+ "devDependencies": {
43
+ "@arethetypeswrong/cli": "0.16.4",
44
+ "@redmix/framework-tools": "0.0.1",
45
+ "@types/yargs": "17.0.33",
46
+ "concurrently": "8.2.2",
47
+ "publint": "0.3.11",
48
+ "tsx": "4.19.3",
49
+ "typescript": "5.6.2"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "gitHead": "688027c97502c500ebbede9cdc7cc51545a8dcf3"
55
+ }