@redmix/auth-auth0-web 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,13 @@
1
+ import type { Auth0Client, LogoutOptions, RedirectLoginOptions } from '@auth0/auth0-spa-js';
2
+ import type { CurrentUser } from '@redmix/auth';
3
+ export interface Auth0User {
4
+ }
5
+ export declare function createAuth(auth0Client: Auth0Client, customProviderHooks?: {
6
+ useCurrentUser?: () => Promise<CurrentUser>;
7
+ useHasRole?: (currentUser: CurrentUser | null) => (rolesToCheck: string | string[]) => boolean;
8
+ }): {
9
+ AuthContext: import("react").Context<import("@redmix/auth").AuthContextInterface<import("@auth0/auth0-spa-js").User, RedirectLoginOptions<any>, void, LogoutOptions, void, RedirectLoginOptions<any>, void, unknown, unknown, unknown, unknown, Auth0Client> | undefined>;
10
+ AuthProvider: ({ children }: import("@redmix/auth").AuthProviderProps) => import("react").JSX.Element;
11
+ useAuth: () => import("@redmix/auth").AuthContextInterface<import("@auth0/auth0-spa-js").User, RedirectLoginOptions<any>, void, LogoutOptions, void, RedirectLoginOptions<any>, void, unknown, unknown, unknown, unknown, Auth0Client>;
12
+ };
13
+ //# sourceMappingURL=auth0.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth0.d.ts","sourceRoot":"","sources":["../src/auth0.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,aAAa,EACb,oBAAoB,EACrB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAK/C,MAAM,WAAW,SAAS;CAAG;AAE7B,wBAAgB,UAAU,CACxB,WAAW,EAAE,WAAW,EACxB,mBAAmB,CAAC,EAAE;IACpB,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,WAAW,CAAC,CAAA;IAC3C,UAAU,CAAC,EAAE,CACX,WAAW,EAAE,WAAW,GAAG,IAAI,KAC5B,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,EAAE,KAAK,OAAO,CAAA;CAClD;;wCAqBG,cAEU,+BAA+B,OAC9C;;EAnBA"}
package/dist/auth0.js ADDED
@@ -0,0 +1,35 @@
1
+ import { createAuthentication } from "@redmix/auth";
2
+ function createAuth(auth0Client, customProviderHooks) {
3
+ const authImplementation = createAuthImplementation(auth0Client);
4
+ return createAuthentication(authImplementation, customProviderHooks);
5
+ }
6
+ function createAuthImplementation(auth0Client) {
7
+ return {
8
+ type: "auth0",
9
+ client: auth0Client,
10
+ restoreAuthState: async () => {
11
+ if (globalThis?.location?.search?.includes("code=") && globalThis?.location?.search?.includes("state=")) {
12
+ const { appState } = await auth0Client.handleRedirectCallback();
13
+ const url = appState?.targetUrl ? appState.targetUrl : window.location.pathname;
14
+ globalThis?.location?.assign(url);
15
+ }
16
+ },
17
+ login: async (options) => auth0Client.loginWithRedirect(options),
18
+ logout: async (options) => auth0Client.logout(options),
19
+ signup: async (options) => auth0Client.loginWithRedirect({
20
+ ...options,
21
+ authorizationParams: {
22
+ screen_hint: "signup",
23
+ prompt: "login"
24
+ }
25
+ }),
26
+ getToken: () => auth0Client.getTokenSilently(),
27
+ getUserMetadata: async () => {
28
+ const user = await auth0Client.getUser();
29
+ return user || null;
30
+ }
31
+ };
32
+ }
33
+ export {
34
+ createAuth
35
+ };
@@ -0,0 +1,13 @@
1
+ import type { Auth0Client, LogoutOptions, RedirectLoginOptions } from '@auth0/auth0-spa-js';
2
+ import type { CurrentUser } from '@redmix/auth';
3
+ export interface Auth0User {
4
+ }
5
+ export declare function createAuth(auth0Client: Auth0Client, customProviderHooks?: {
6
+ useCurrentUser?: () => Promise<CurrentUser>;
7
+ useHasRole?: (currentUser: CurrentUser | null) => (rolesToCheck: string | string[]) => boolean;
8
+ }): {
9
+ AuthContext: import("react").Context<import("@redmix/auth").AuthContextInterface<import("@auth0/auth0-spa-js").User, RedirectLoginOptions<any>, void, LogoutOptions, void, RedirectLoginOptions<any>, void, unknown, unknown, unknown, unknown, Auth0Client> | undefined>;
10
+ AuthProvider: ({ children }: import("@redmix/auth").AuthProviderProps) => import("react").JSX.Element;
11
+ useAuth: () => import("@redmix/auth").AuthContextInterface<import("@auth0/auth0-spa-js").User, RedirectLoginOptions<any>, void, LogoutOptions, void, RedirectLoginOptions<any>, void, unknown, unknown, unknown, unknown, Auth0Client>;
12
+ };
13
+ //# sourceMappingURL=auth0.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth0.d.ts","sourceRoot":"","sources":["../../src/auth0.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,aAAa,EACb,oBAAoB,EACrB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAK/C,MAAM,WAAW,SAAS;CAAG;AAE7B,wBAAgB,UAAU,CACxB,WAAW,EAAE,WAAW,EACxB,mBAAmB,CAAC,EAAE;IACpB,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,WAAW,CAAC,CAAA;IAC3C,UAAU,CAAC,EAAE,CACX,WAAW,EAAE,WAAW,GAAG,IAAI,KAC5B,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,EAAE,KAAK,OAAO,CAAA;CAClD;;wCAqBG,cAEU,+BAA+B,OAC9C;;EAnBA"}
@@ -0,0 +1,59 @@
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 auth0_exports = {};
20
+ __export(auth0_exports, {
21
+ createAuth: () => createAuth
22
+ });
23
+ module.exports = __toCommonJS(auth0_exports);
24
+ var import_auth = require("@redmix/auth");
25
+ function createAuth(auth0Client, customProviderHooks) {
26
+ const authImplementation = createAuthImplementation(auth0Client);
27
+ return (0, import_auth.createAuthentication)(authImplementation, customProviderHooks);
28
+ }
29
+ function createAuthImplementation(auth0Client) {
30
+ return {
31
+ type: "auth0",
32
+ client: auth0Client,
33
+ restoreAuthState: async () => {
34
+ if (globalThis?.location?.search?.includes("code=") && globalThis?.location?.search?.includes("state=")) {
35
+ const { appState } = await auth0Client.handleRedirectCallback();
36
+ const url = appState?.targetUrl ? appState.targetUrl : window.location.pathname;
37
+ globalThis?.location?.assign(url);
38
+ }
39
+ },
40
+ login: async (options) => auth0Client.loginWithRedirect(options),
41
+ logout: async (options) => auth0Client.logout(options),
42
+ signup: async (options) => auth0Client.loginWithRedirect({
43
+ ...options,
44
+ authorizationParams: {
45
+ screen_hint: "signup",
46
+ prompt: "login"
47
+ }
48
+ }),
49
+ getToken: () => auth0Client.getTokenSilently(),
50
+ getUserMetadata: async () => {
51
+ const user = await auth0Client.getUser();
52
+ return user || null;
53
+ }
54
+ };
55
+ }
56
+ // Annotate the CommonJS export names for ESM import in node:
57
+ 0 && (module.exports = {
58
+ createAuth
59
+ });
@@ -0,0 +1,2 @@
1
+ export { createAuth } from './auth0.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA"}
@@ -0,0 +1,28 @@
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 index_exports = {};
20
+ __export(index_exports, {
21
+ createAuth: () => import_auth0.createAuth
22
+ });
23
+ module.exports = __toCommonJS(index_exports);
24
+ var import_auth0 = require("./auth0.js");
25
+ // Annotate the CommonJS export names for ESM import in node:
26
+ 0 && (module.exports = {
27
+ createAuth
28
+ });
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,2 @@
1
+ export { createAuth } from './auth0.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { createAuth } from "./auth0.js";
2
+ export {
3
+ createAuth
4
+ };
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@redmix/auth-auth0-web",
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/auth0/web"
8
+ },
9
+ "license": "MIT",
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "import": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "default": {
18
+ "types": "./dist/cjs/index.d.ts",
19
+ "default": "./dist/cjs/index.js"
20
+ }
21
+ },
22
+ "./dist/auth0": {
23
+ "import": {
24
+ "types": "./dist/auth0.d.ts",
25
+ "default": "./dist/auth0.js"
26
+ },
27
+ "default": {
28
+ "types": "./dist/cjs/auth0.d.ts",
29
+ "default": "./dist/cjs/auth0.js"
30
+ }
31
+ }
32
+ },
33
+ "main": "./dist/cjs/index.js",
34
+ "module": "./dist/index.js",
35
+ "types": "./dist/index.d.ts",
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "scripts": {
40
+ "build": "tsx ./build.ts",
41
+ "build:pack": "yarn pack -o redmix-auth-auth0-web.tgz",
42
+ "build:types": "tsc --build --verbose ./tsconfig.build.json",
43
+ "build:types-cjs": "tsc --build --verbose ./tsconfig.cjs.json",
44
+ "build:watch": "nodemon --watch src --ext \"js,jsx,ts,tsx,template\" --ignore dist --exec \"yarn build\"",
45
+ "check:attw": "yarn rw-fwtools-attw",
46
+ "check:package": "concurrently npm:check:attw yarn:publint",
47
+ "prepublishOnly": "NODE_ENV=production yarn build",
48
+ "test": "vitest run",
49
+ "test:watch": "vitest watch"
50
+ },
51
+ "dependencies": {
52
+ "@redmix/auth": "0.0.1"
53
+ },
54
+ "devDependencies": {
55
+ "@auth0/auth0-spa-js": "2.1.3",
56
+ "@redmix/framework-tools": "0.0.1",
57
+ "@types/react": "^18.2.55",
58
+ "concurrently": "8.2.2",
59
+ "publint": "0.3.11",
60
+ "react": "19.0.0-rc-f2df5694-20240916",
61
+ "tsx": "4.19.3",
62
+ "typescript": "5.6.2",
63
+ "vitest": "2.1.9"
64
+ },
65
+ "peerDependencies": {
66
+ "@auth0/auth0-spa-js": "2.1.3"
67
+ },
68
+ "publishConfig": {
69
+ "access": "public"
70
+ },
71
+ "gitHead": "688027c97502c500ebbede9cdc7cc51545a8dcf3"
72
+ }