@redmix/auth-dbauth-middleware 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 +21 -0
- package/README.md +88 -0
- package/dist/cjs/defaultGetRoles.d.ts +2 -0
- package/dist/cjs/defaultGetRoles.d.ts.map +1 -0
- package/dist/cjs/defaultGetRoles.js +39 -0
- package/dist/cjs/index.d.ts +14 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +158 -0
- package/dist/cjs/package.json +1 -0
- package/dist/defaultGetRoles.d.ts +2 -0
- package/dist/defaultGetRoles.d.ts.map +1 -0
- package/dist/defaultGetRoles.js +15 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +124 -0
- package/package.json +60 -0
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,88 @@
|
|
1
|
+
# DbAuth Middleware
|
2
|
+
|
3
|
+
### Example instantiation
|
4
|
+
|
5
|
+
```tsx filename='entry.server.tsx'
|
6
|
+
import type { TagDescriptor } from '@redmix/web'
|
7
|
+
|
8
|
+
import App from './App'
|
9
|
+
import initDbAuthMiddleware from '@redmix/auth-dbauth-middleware'
|
10
|
+
import { Document } from './Document'
|
11
|
+
|
12
|
+
import { handler as dbAuthHandler } from '$api/src/functions/auth'
|
13
|
+
import { cookieName } from '$api/src/lib/auth'
|
14
|
+
import { getCurrentUser } from '$api/src/lib/auth'
|
15
|
+
interface Props {
|
16
|
+
css: string[]
|
17
|
+
meta?: TagDescriptor[]
|
18
|
+
}
|
19
|
+
|
20
|
+
export const registerMiddleware = () => {
|
21
|
+
// This actually returns [dbAuthMiddleware, '*']
|
22
|
+
const authMw = initDbAuthMiddleware({
|
23
|
+
dbAuthHandler,
|
24
|
+
getCurrentUser,
|
25
|
+
// cookieName optional
|
26
|
+
// getRoles optional
|
27
|
+
// dbAuthUrl? optional
|
28
|
+
})
|
29
|
+
|
30
|
+
return [authMw]
|
31
|
+
}
|
32
|
+
|
33
|
+
export const ServerEntry: React.FC<Props> = ({ css, meta }) => {
|
34
|
+
return (
|
35
|
+
<Document css={css} meta={meta}>
|
36
|
+
<App />
|
37
|
+
</Document>
|
38
|
+
)
|
39
|
+
}
|
40
|
+
```
|
41
|
+
|
42
|
+
### Roles handling
|
43
|
+
|
44
|
+
By default the middleware assumes your roles will be in `currentUser.roles` - either as a string or an array of strings.
|
45
|
+
|
46
|
+
For example
|
47
|
+
|
48
|
+
```js
|
49
|
+
|
50
|
+
// If this is your current user:
|
51
|
+
{
|
52
|
+
email: 'user-1@example.com',
|
53
|
+
id: 'mocked-current-user-1',
|
54
|
+
roles: 'admin'
|
55
|
+
}
|
56
|
+
|
57
|
+
// In the ServerAuthState
|
58
|
+
{
|
59
|
+
cookieHeader: 'session=session_cookie',
|
60
|
+
currentUser: {
|
61
|
+
email: 'user-1@example.com',
|
62
|
+
id: 'mocked-current-user-1',
|
63
|
+
roles: 'admin' // <-- you sent back 'admin' as string
|
64
|
+
},
|
65
|
+
hasError: false,
|
66
|
+
isAuthenticated: true,
|
67
|
+
loading: false,
|
68
|
+
userMetadata: /*..*/
|
69
|
+
roles: ['admin'] // <-- converted to array
|
70
|
+
}
|
71
|
+
```
|
72
|
+
|
73
|
+
You can customise this by passing a custom `getRoles` function into `initDbAuthMiddleware`. For example:
|
74
|
+
|
75
|
+
```ts
|
76
|
+
const authMw = initDbAuthMiddleware({
|
77
|
+
dbAuthHandler,
|
78
|
+
getCurrentUser,
|
79
|
+
getRoles: (decoded) => {
|
80
|
+
// Assuming you want to get roles from a property called org
|
81
|
+
if (decoded.currentUser.org) {
|
82
|
+
return [decoded.currentUser.org]
|
83
|
+
} else {
|
84
|
+
return []
|
85
|
+
}
|
86
|
+
},
|
87
|
+
})
|
88
|
+
```
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"defaultGetRoles.d.ts","sourceRoot":"","sources":["../../src/defaultGetRoles.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,YACjB,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,SAAS,GAAG,IAAI,KAC9C,MAAM,EAYR,CAAA"}
|
@@ -0,0 +1,39 @@
|
|
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 defaultGetRoles_exports = {};
|
20
|
+
__export(defaultGetRoles_exports, {
|
21
|
+
defaultGetRoles: () => defaultGetRoles
|
22
|
+
});
|
23
|
+
module.exports = __toCommonJS(defaultGetRoles_exports);
|
24
|
+
const defaultGetRoles = (decoded) => {
|
25
|
+
try {
|
26
|
+
const roles = decoded?.currentUser?.roles;
|
27
|
+
if (Array.isArray(roles)) {
|
28
|
+
return roles;
|
29
|
+
} else {
|
30
|
+
return roles ? [roles] : [];
|
31
|
+
}
|
32
|
+
} catch {
|
33
|
+
return [];
|
34
|
+
}
|
35
|
+
};
|
36
|
+
// Annotate the CommonJS export names for ESM import in node:
|
37
|
+
0 && (module.exports = {
|
38
|
+
defaultGetRoles
|
39
|
+
});
|
@@ -0,0 +1,14 @@
|
|
1
|
+
import type { APIGatewayProxyEvent, Context } from 'aws-lambda';
|
2
|
+
import type { DbAuthResponse } from '@redmix/auth-dbauth-api';
|
3
|
+
import type { GetCurrentUser } from '@redmix/graphql-server';
|
4
|
+
import type { Middleware } from '@redmix/web/middleware';
|
5
|
+
export interface DbAuthMiddlewareOptions {
|
6
|
+
cookieName?: string;
|
7
|
+
dbAuthUrl?: string;
|
8
|
+
dbAuthHandler: (req: Request | APIGatewayProxyEvent, context?: Context) => DbAuthResponse;
|
9
|
+
getRoles?: (decoded: any) => string[];
|
10
|
+
getCurrentUser: GetCurrentUser;
|
11
|
+
}
|
12
|
+
export declare const initDbAuthMiddleware: ({ dbAuthHandler, getCurrentUser, getRoles, cookieName, dbAuthUrl, }: DbAuthMiddlewareOptions) => [Middleware, "*"];
|
13
|
+
export default initDbAuthMiddleware;
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAI7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAA;AAE5D,OAAO,KAAK,EAAE,UAAU,EAAqB,MAAM,wBAAwB,CAAA;AAI3E,MAAM,WAAW,uBAAuB;IACtC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAGlB,aAAa,EAAE,CACb,GAAG,EAAE,OAAO,GAAG,oBAAoB,EACnC,OAAO,CAAC,EAAE,OAAO,KACd,cAAc,CAAA;IACnB,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,MAAM,EAAE,CAAA;IACrC,cAAc,EAAE,cAAc,CAAA;CAC/B;AAED,eAAO,MAAM,oBAAoB,wEAM9B,uBAAuB,KAAG,CAAC,UAAU,EAAE,GAAG,CAkG5C,CAAA;AA8DD,eAAe,oBAAoB,CAAA"}
|
@@ -0,0 +1,158 @@
|
|
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 index_exports = {};
|
30
|
+
__export(index_exports, {
|
31
|
+
default: () => index_default,
|
32
|
+
initDbAuthMiddleware: () => initDbAuthMiddleware
|
33
|
+
});
|
34
|
+
module.exports = __toCommonJS(index_exports);
|
35
|
+
var import_auth_dbauth_api = __toESM(require("@redmix/auth-dbauth-api"), 1);
|
36
|
+
var import_middleware = require("@redmix/web/middleware");
|
37
|
+
var import_defaultGetRoles = require("./defaultGetRoles.js");
|
38
|
+
const { dbAuthSession, cookieName: cookieNameCreator } = import_auth_dbauth_api.default;
|
39
|
+
const initDbAuthMiddleware = ({
|
40
|
+
dbAuthHandler,
|
41
|
+
getCurrentUser,
|
42
|
+
getRoles = import_defaultGetRoles.defaultGetRoles,
|
43
|
+
cookieName,
|
44
|
+
dbAuthUrl = "/middleware/dbauth"
|
45
|
+
}) => {
|
46
|
+
const mw = async (req, res = import_middleware.MiddlewareResponse.next()) => {
|
47
|
+
console.log("dbAuthUrl", dbAuthUrl);
|
48
|
+
console.log("req.url", req.url);
|
49
|
+
if (req.url.includes(dbAuthUrl)) {
|
50
|
+
if (req.url.includes(`${dbAuthUrl}/currentUser`)) {
|
51
|
+
const validatedSession2 = await validateSession({
|
52
|
+
req,
|
53
|
+
cookieName,
|
54
|
+
getCurrentUser
|
55
|
+
});
|
56
|
+
if (validatedSession2) {
|
57
|
+
return new import_middleware.MiddlewareResponse(
|
58
|
+
JSON.stringify({ currentUser: validatedSession2.currentUser })
|
59
|
+
);
|
60
|
+
} else {
|
61
|
+
return new import_middleware.MiddlewareResponse(JSON.stringify({ currentUser: null }));
|
62
|
+
}
|
63
|
+
} else {
|
64
|
+
const output = await dbAuthHandler(req);
|
65
|
+
console.log("output", output);
|
66
|
+
const finalHeaders = new Headers();
|
67
|
+
Object.entries(output.headers).forEach(([key, value]) => {
|
68
|
+
if (Array.isArray(value)) {
|
69
|
+
value.forEach((mvhHeader) => finalHeaders.append(key, mvhHeader));
|
70
|
+
} else {
|
71
|
+
finalHeaders.append(key, value);
|
72
|
+
}
|
73
|
+
});
|
74
|
+
return new import_middleware.MiddlewareResponse(output.body, {
|
75
|
+
headers: finalHeaders,
|
76
|
+
status: output.statusCode
|
77
|
+
});
|
78
|
+
}
|
79
|
+
}
|
80
|
+
const cookieHeader = req.headers.get("Cookie");
|
81
|
+
if (!cookieHeader?.includes("auth-provider")) {
|
82
|
+
return res;
|
83
|
+
}
|
84
|
+
const validatedSession = await validateSession({
|
85
|
+
req,
|
86
|
+
cookieName,
|
87
|
+
getCurrentUser
|
88
|
+
});
|
89
|
+
if (validatedSession) {
|
90
|
+
const { currentUser, decryptedSession } = validatedSession;
|
91
|
+
req.serverAuthState.set({
|
92
|
+
currentUser,
|
93
|
+
loading: false,
|
94
|
+
isAuthenticated: !!currentUser,
|
95
|
+
hasError: false,
|
96
|
+
userMetadata: currentUser,
|
97
|
+
// dbAuth doesn't have userMetadata
|
98
|
+
cookieHeader,
|
99
|
+
roles: getRoles(decryptedSession)
|
100
|
+
});
|
101
|
+
} else {
|
102
|
+
req.serverAuthState.clear();
|
103
|
+
res.cookies.unset(cookieNameCreator(cookieName));
|
104
|
+
res.cookies.unset("auth-provider");
|
105
|
+
}
|
106
|
+
return res;
|
107
|
+
};
|
108
|
+
return [mw, "*"];
|
109
|
+
};
|
110
|
+
async function validateSession({
|
111
|
+
req,
|
112
|
+
cookieName,
|
113
|
+
getCurrentUser
|
114
|
+
}) {
|
115
|
+
let decryptedSession;
|
116
|
+
try {
|
117
|
+
decryptedSession = dbAuthSession(
|
118
|
+
req,
|
119
|
+
cookieNameCreator(cookieName)
|
120
|
+
);
|
121
|
+
} catch (e) {
|
122
|
+
if (process.env.NODE_ENV === "development") {
|
123
|
+
console.debug("Could not decrypt dbAuth session", e);
|
124
|
+
}
|
125
|
+
return void 0;
|
126
|
+
}
|
127
|
+
if (!decryptedSession) {
|
128
|
+
if (process.env.NODE_ENV === "development") {
|
129
|
+
console.debug(
|
130
|
+
"No dbAuth session cookie found. Looking for a cookie named:",
|
131
|
+
cookieName
|
132
|
+
);
|
133
|
+
}
|
134
|
+
return void 0;
|
135
|
+
}
|
136
|
+
const currentUser = await getCurrentUser(
|
137
|
+
decryptedSession,
|
138
|
+
{
|
139
|
+
type: "dbAuth",
|
140
|
+
schema: "cookie",
|
141
|
+
// @MARK: We pass the entire cookie header as a token. This isn't
|
142
|
+
// actually the token!
|
143
|
+
// At this point the Cookie header is guaranteed, because otherwise a
|
144
|
+
// decryptionError would have been thrown
|
145
|
+
token: req.headers.get("Cookie")
|
146
|
+
},
|
147
|
+
{
|
148
|
+
// MWRequest is a superset of Request
|
149
|
+
event: req
|
150
|
+
}
|
151
|
+
);
|
152
|
+
return { currentUser, decryptedSession };
|
153
|
+
}
|
154
|
+
var index_default = initDbAuthMiddleware;
|
155
|
+
// Annotate the CommonJS export names for ESM import in node:
|
156
|
+
0 && (module.exports = {
|
157
|
+
initDbAuthMiddleware
|
158
|
+
});
|
@@ -0,0 +1 @@
|
|
1
|
+
{"type":"commonjs"}
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"defaultGetRoles.d.ts","sourceRoot":"","sources":["../src/defaultGetRoles.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,YACjB,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,SAAS,GAAG,IAAI,KAC9C,MAAM,EAYR,CAAA"}
|
@@ -0,0 +1,15 @@
|
|
1
|
+
const defaultGetRoles = (decoded) => {
|
2
|
+
try {
|
3
|
+
const roles = decoded?.currentUser?.roles;
|
4
|
+
if (Array.isArray(roles)) {
|
5
|
+
return roles;
|
6
|
+
} else {
|
7
|
+
return roles ? [roles] : [];
|
8
|
+
}
|
9
|
+
} catch {
|
10
|
+
return [];
|
11
|
+
}
|
12
|
+
};
|
13
|
+
export {
|
14
|
+
defaultGetRoles
|
15
|
+
};
|
package/dist/index.d.ts
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
import type { APIGatewayProxyEvent, Context } from 'aws-lambda';
|
2
|
+
import type { DbAuthResponse } from '@redmix/auth-dbauth-api';
|
3
|
+
import type { GetCurrentUser } from '@redmix/graphql-server';
|
4
|
+
import type { Middleware } from '@redmix/web/middleware';
|
5
|
+
export interface DbAuthMiddlewareOptions {
|
6
|
+
cookieName?: string;
|
7
|
+
dbAuthUrl?: string;
|
8
|
+
dbAuthHandler: (req: Request | APIGatewayProxyEvent, context?: Context) => DbAuthResponse;
|
9
|
+
getRoles?: (decoded: any) => string[];
|
10
|
+
getCurrentUser: GetCurrentUser;
|
11
|
+
}
|
12
|
+
export declare const initDbAuthMiddleware: ({ dbAuthHandler, getCurrentUser, getRoles, cookieName, dbAuthUrl, }: DbAuthMiddlewareOptions) => [Middleware, "*"];
|
13
|
+
export default initDbAuthMiddleware;
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAI7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAA;AAE5D,OAAO,KAAK,EAAE,UAAU,EAAqB,MAAM,wBAAwB,CAAA;AAI3E,MAAM,WAAW,uBAAuB;IACtC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAGlB,aAAa,EAAE,CACb,GAAG,EAAE,OAAO,GAAG,oBAAoB,EACnC,OAAO,CAAC,EAAE,OAAO,KACd,cAAc,CAAA;IACnB,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,MAAM,EAAE,CAAA;IACrC,cAAc,EAAE,cAAc,CAAA;CAC/B;AAED,eAAO,MAAM,oBAAoB,wEAM9B,uBAAuB,KAAG,CAAC,UAAU,EAAE,GAAG,CAkG5C,CAAA;AA8DD,eAAe,oBAAoB,CAAA"}
|
package/dist/index.js
ADDED
@@ -0,0 +1,124 @@
|
|
1
|
+
import dbAuthApi from "@redmix/auth-dbauth-api";
|
2
|
+
const { dbAuthSession, cookieName: cookieNameCreator } = dbAuthApi;
|
3
|
+
import { MiddlewareResponse } from "@redmix/web/middleware";
|
4
|
+
import { defaultGetRoles } from "./defaultGetRoles.js";
|
5
|
+
const initDbAuthMiddleware = ({
|
6
|
+
dbAuthHandler,
|
7
|
+
getCurrentUser,
|
8
|
+
getRoles = defaultGetRoles,
|
9
|
+
cookieName,
|
10
|
+
dbAuthUrl = "/middleware/dbauth"
|
11
|
+
}) => {
|
12
|
+
const mw = async (req, res = MiddlewareResponse.next()) => {
|
13
|
+
console.log("dbAuthUrl", dbAuthUrl);
|
14
|
+
console.log("req.url", req.url);
|
15
|
+
if (req.url.includes(dbAuthUrl)) {
|
16
|
+
if (req.url.includes(`${dbAuthUrl}/currentUser`)) {
|
17
|
+
const validatedSession2 = await validateSession({
|
18
|
+
req,
|
19
|
+
cookieName,
|
20
|
+
getCurrentUser
|
21
|
+
});
|
22
|
+
if (validatedSession2) {
|
23
|
+
return new MiddlewareResponse(
|
24
|
+
JSON.stringify({ currentUser: validatedSession2.currentUser })
|
25
|
+
);
|
26
|
+
} else {
|
27
|
+
return new MiddlewareResponse(JSON.stringify({ currentUser: null }));
|
28
|
+
}
|
29
|
+
} else {
|
30
|
+
const output = await dbAuthHandler(req);
|
31
|
+
console.log("output", output);
|
32
|
+
const finalHeaders = new Headers();
|
33
|
+
Object.entries(output.headers).forEach(([key, value]) => {
|
34
|
+
if (Array.isArray(value)) {
|
35
|
+
value.forEach((mvhHeader) => finalHeaders.append(key, mvhHeader));
|
36
|
+
} else {
|
37
|
+
finalHeaders.append(key, value);
|
38
|
+
}
|
39
|
+
});
|
40
|
+
return new MiddlewareResponse(output.body, {
|
41
|
+
headers: finalHeaders,
|
42
|
+
status: output.statusCode
|
43
|
+
});
|
44
|
+
}
|
45
|
+
}
|
46
|
+
const cookieHeader = req.headers.get("Cookie");
|
47
|
+
if (!cookieHeader?.includes("auth-provider")) {
|
48
|
+
return res;
|
49
|
+
}
|
50
|
+
const validatedSession = await validateSession({
|
51
|
+
req,
|
52
|
+
cookieName,
|
53
|
+
getCurrentUser
|
54
|
+
});
|
55
|
+
if (validatedSession) {
|
56
|
+
const { currentUser, decryptedSession } = validatedSession;
|
57
|
+
req.serverAuthState.set({
|
58
|
+
currentUser,
|
59
|
+
loading: false,
|
60
|
+
isAuthenticated: !!currentUser,
|
61
|
+
hasError: false,
|
62
|
+
userMetadata: currentUser,
|
63
|
+
// dbAuth doesn't have userMetadata
|
64
|
+
cookieHeader,
|
65
|
+
roles: getRoles(decryptedSession)
|
66
|
+
});
|
67
|
+
} else {
|
68
|
+
req.serverAuthState.clear();
|
69
|
+
res.cookies.unset(cookieNameCreator(cookieName));
|
70
|
+
res.cookies.unset("auth-provider");
|
71
|
+
}
|
72
|
+
return res;
|
73
|
+
};
|
74
|
+
return [mw, "*"];
|
75
|
+
};
|
76
|
+
async function validateSession({
|
77
|
+
req,
|
78
|
+
cookieName,
|
79
|
+
getCurrentUser
|
80
|
+
}) {
|
81
|
+
let decryptedSession;
|
82
|
+
try {
|
83
|
+
decryptedSession = dbAuthSession(
|
84
|
+
req,
|
85
|
+
cookieNameCreator(cookieName)
|
86
|
+
);
|
87
|
+
} catch (e) {
|
88
|
+
if (process.env.NODE_ENV === "development") {
|
89
|
+
console.debug("Could not decrypt dbAuth session", e);
|
90
|
+
}
|
91
|
+
return void 0;
|
92
|
+
}
|
93
|
+
if (!decryptedSession) {
|
94
|
+
if (process.env.NODE_ENV === "development") {
|
95
|
+
console.debug(
|
96
|
+
"No dbAuth session cookie found. Looking for a cookie named:",
|
97
|
+
cookieName
|
98
|
+
);
|
99
|
+
}
|
100
|
+
return void 0;
|
101
|
+
}
|
102
|
+
const currentUser = await getCurrentUser(
|
103
|
+
decryptedSession,
|
104
|
+
{
|
105
|
+
type: "dbAuth",
|
106
|
+
schema: "cookie",
|
107
|
+
// @MARK: We pass the entire cookie header as a token. This isn't
|
108
|
+
// actually the token!
|
109
|
+
// At this point the Cookie header is guaranteed, because otherwise a
|
110
|
+
// decryptionError would have been thrown
|
111
|
+
token: req.headers.get("Cookie")
|
112
|
+
},
|
113
|
+
{
|
114
|
+
// MWRequest is a superset of Request
|
115
|
+
event: req
|
116
|
+
}
|
117
|
+
);
|
118
|
+
return { currentUser, decryptedSession };
|
119
|
+
}
|
120
|
+
var index_default = initDbAuthMiddleware;
|
121
|
+
export {
|
122
|
+
index_default as default,
|
123
|
+
initDbAuthMiddleware
|
124
|
+
};
|
package/package.json
ADDED
@@ -0,0 +1,60 @@
|
|
1
|
+
{
|
2
|
+
"name": "@redmix/auth-dbauth-middleware",
|
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/dbAuth/middleware"
|
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
|
+
"require": {
|
18
|
+
"types": "./dist/cjs/index.d.ts",
|
19
|
+
"default": "./dist/cjs/index.js"
|
20
|
+
}
|
21
|
+
}
|
22
|
+
},
|
23
|
+
"main": "./dist/index.js",
|
24
|
+
"types": "./dist/index.d.ts",
|
25
|
+
"files": [
|
26
|
+
"dist"
|
27
|
+
],
|
28
|
+
"scripts": {
|
29
|
+
"build": "tsx ./build.mts",
|
30
|
+
"build:pack": "yarn pack -o redmix-auth-dbauth-middleware.tgz",
|
31
|
+
"build:types": "tsc --build --verbose ./tsconfig.build.json",
|
32
|
+
"build:types-cjs": "tsc --build --verbose tsconfig.cjs.json",
|
33
|
+
"check:attw": "yarn attw -P",
|
34
|
+
"check:package": "concurrently npm:check:attw yarn:publint",
|
35
|
+
"prepublishOnly": "NODE_ENV=production yarn build",
|
36
|
+
"test": "vitest run",
|
37
|
+
"test:watch": "vitest watch"
|
38
|
+
},
|
39
|
+
"dependencies": {
|
40
|
+
"@redmix/auth-dbauth-api": "0.0.1",
|
41
|
+
"@redmix/web": "0.0.1"
|
42
|
+
},
|
43
|
+
"devDependencies": {
|
44
|
+
"@arethetypeswrong/cli": "0.16.4",
|
45
|
+
"@redmix/api": "0.0.1",
|
46
|
+
"@redmix/framework-tools": "0.0.1",
|
47
|
+
"@redmix/graphql-server": "0.0.1",
|
48
|
+
"@types/aws-lambda": "8.10.145",
|
49
|
+
"concurrently": "8.2.2",
|
50
|
+
"publint": "0.3.11",
|
51
|
+
"ts-toolbelt": "9.6.0",
|
52
|
+
"tsx": "4.19.3",
|
53
|
+
"typescript": "5.6.2",
|
54
|
+
"vitest": "2.1.9"
|
55
|
+
},
|
56
|
+
"publishConfig": {
|
57
|
+
"access": "public"
|
58
|
+
},
|
59
|
+
"gitHead": "25a2481ac394049b7c864eda26381814a0124a79"
|
60
|
+
}
|