orange-auth 1.2.0 → 1.3.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 (63) hide show
  1. package/COPYING +674 -0
  2. package/README.md +81 -124
  3. package/dist/IProvider-BH8TjziQ.d.mts +461 -0
  4. package/dist/IProvider-BH8TjziQ.d.mts.map +1 -0
  5. package/dist/client.d.ts +470 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +19 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/index-D-dMFhOD.d.mts +55 -0
  10. package/dist/index-D-dMFhOD.d.mts.map +1 -0
  11. package/dist/index-DjPz5vTX.d.mts +37 -0
  12. package/dist/index-DjPz5vTX.d.mts.map +1 -0
  13. package/dist/index.d.mts +70 -0
  14. package/dist/index.d.mts.map +1 -0
  15. package/dist/index.mjs +19 -0
  16. package/dist/index.mjs.map +1 -0
  17. package/dist/providers.d.mts +20 -0
  18. package/dist/providers.mjs +19 -0
  19. package/dist/providers.mjs.map +1 -0
  20. package/dist/strategies.d.mts +20 -0
  21. package/dist/strategies.mjs +19 -0
  22. package/dist/strategies.mjs.map +1 -0
  23. package/package.json +53 -31
  24. package/LICENSE +0 -21
  25. package/dist/@types/globals.d.ts +0 -97
  26. package/dist/@types/globals.d.ts.map +0 -1
  27. package/dist/@types/globals.js +0 -1
  28. package/dist/@types/internals.d.ts +0 -13
  29. package/dist/@types/internals.d.ts.map +0 -1
  30. package/dist/@types/internals.js +0 -1
  31. package/dist/functions/index.d.ts +0 -3
  32. package/dist/functions/index.d.ts.map +0 -1
  33. package/dist/functions/index.js +0 -2
  34. package/dist/functions/jwt.d.ts +0 -11
  35. package/dist/functions/jwt.d.ts.map +0 -1
  36. package/dist/functions/jwt.js +0 -20
  37. package/dist/functions/urlencodedToJson.d.ts +0 -2
  38. package/dist/functions/urlencodedToJson.d.ts.map +0 -1
  39. package/dist/functions/urlencodedToJson.js +0 -8
  40. package/dist/index.d.ts +0 -5
  41. package/dist/index.d.ts.map +0 -1
  42. package/dist/index.js +0 -4
  43. package/dist/lib.d.ts +0 -46
  44. package/dist/lib.d.ts.map +0 -1
  45. package/dist/lib.js +0 -161
  46. package/dist/providers/Credentials.d.ts +0 -33
  47. package/dist/providers/Credentials.d.ts.map +0 -1
  48. package/dist/providers/Credentials.js +0 -42
  49. package/dist/providers/IProvider.d.ts +0 -29
  50. package/dist/providers/IProvider.d.ts.map +0 -1
  51. package/dist/providers/IProvider.js +0 -20
  52. package/dist/providers/index.d.ts +0 -3
  53. package/dist/providers/index.d.ts.map +0 -1
  54. package/dist/providers/index.js +0 -2
  55. package/dist/strategies/IStrategy.d.ts +0 -48
  56. package/dist/strategies/IStrategy.d.ts.map +0 -1
  57. package/dist/strategies/IStrategy.js +0 -11
  58. package/dist/strategies/index.d.ts +0 -3
  59. package/dist/strategies/index.d.ts.map +0 -1
  60. package/dist/strategies/index.js +0 -2
  61. package/dist/strategies/jwt.d.ts +0 -19
  62. package/dist/strategies/jwt.d.ts.map +0 -1
  63. package/dist/strategies/jwt.js +0 -51
package/dist/lib.js DELETED
@@ -1,161 +0,0 @@
1
- import Cookies from "universal-cookie";
2
- import { serialize as cookie } from "cookie";
3
- import { assign, find, isNil, isString, merge } from "lodash-es";
4
- import { params } from "@universal-middleware/core";
5
- /**
6
- * Deserialize a user's session based of the headers
7
- * @param globalCfg The global auth config
8
- * @param req An object having a headers field
9
- * @returns A user's token and session, if found and valid
10
- */
11
- const getSession = async (globalCfg, req) => {
12
- if (isNil(req.headers))
13
- return {
14
- session: null,
15
- token: null,
16
- };
17
- // Find the correct cookie header
18
- const cookieHeader = req.headers instanceof Headers ? req.headers.get("cookie") : req.headers["cookie"];
19
- const cookie = new Cookies(cookieHeader);
20
- if (isNil(cookie))
21
- return {
22
- session: null,
23
- token: null,
24
- };
25
- // Tries to extract the specific cookie.
26
- const token = cookie.get(globalCfg.cookieName);
27
- if (isNil(token))
28
- return {
29
- session: null,
30
- token: null,
31
- };
32
- // Tries to deserialize it
33
- return {
34
- session: (await globalCfg.strategy.deserialize(token, globalCfg)),
35
- token: token,
36
- };
37
- };
38
- /**
39
- * Initializes the auth. This should be called once per backend.
40
- * @param req Something that has a `headers` field; either a Headers instance, or just a plain object.
41
- * @returns A session if found and valid, or `null`.
42
- */
43
- export const CreateAuth = ((config) => {
44
- const { secret, strategy, cookieName, providers, cookieSettings, basePath, callbacks } = config;
45
- if (isNil(secret)) {
46
- throw new Error('[ERROR]: Auth secret missing! Make sure to set the "secret" variable in the auth\'s config.');
47
- }
48
- if (isNil(strategy)) {
49
- throw new Error('[ERROR]: No strategy chosen! Make sure to set the "strategy" variable in the auth\'s config.');
50
- }
51
- // We set the global config on startup, and not on the route handler,
52
- // otherwise a session cannot be accessed until someone logs in
53
- const globalCfg = {
54
- cookieName: cookieName ?? "orange.auth",
55
- providers: providers ?? [],
56
- secret,
57
- strategy,
58
- cookieSettings: cookieSettings ?? {
59
- path: "/",
60
- httpOnly: true,
61
- sameSite: "lax",
62
- secure: true,
63
- maxAge: 3600,
64
- },
65
- callbacks: merge({}, { login: () => ({}), logout: () => ({}) }, callbacks),
66
- };
67
- return {
68
- /**
69
- * Universal handler route. You can use this with the `createHandler()` method
70
- * @returns
71
- */
72
- handler: () => async (req, _, runtime) => {
73
- // Tries to get the action and provider info from the url
74
- const routeParams = params(req, runtime, basePath);
75
- if (isNil(routeParams?.["action"]) || isNil(routeParams["provider"])) {
76
- throw new Error('[ERROR]: Base path is missing! Make sure to set the "basePath" variable in the auth\'s config.');
77
- }
78
- // Finds the requested provider by name
79
- const path = routeParams["provider"];
80
- const provider = find(providers, (p) => p.ID === path);
81
- if (isNil(provider)) {
82
- return new Response("Page not found", { status: 404 });
83
- }
84
- // Handles each action independently
85
- switch (routeParams["action"]) {
86
- case "login": {
87
- // Use the found provider to login
88
- const token = await provider.logIn(req, globalCfg).catch(() => null);
89
- // If failed, return Bad Request response
90
- if (isNil(token))
91
- return new Response(null, { status: 400 });
92
- const params = await getSession(globalCfg, {
93
- // The cookie header is faked here, since the request does not have any token yet.
94
- headers: { cookie: cookie(globalCfg.cookieName, token) },
95
- });
96
- // If there is no session at this point, something as gone wrong
97
- if (isNil(params.session) || isNil(params.token)) {
98
- console.error("[AUTH ERROR]: Missing session after login");
99
- return new Response("internal server error", { status: 500 });
100
- }
101
- // Run the login callback
102
- const customRes = await globalCfg.callbacks.login({
103
- headers: req.headers,
104
- token: params.token,
105
- session: params.session,
106
- });
107
- // If the result is false, fail the login
108
- if (customRes === false) {
109
- return new Response("Bad Request", { status: 400 });
110
- }
111
- // If the result is a string, assume it is a redirection path
112
- if (isString(customRes)) {
113
- const headers = new Headers();
114
- headers.set("Location", customRes);
115
- return new Response(null, { status: 308, headers });
116
- }
117
- // Creates the set-cookie header
118
- const headers = new Headers();
119
- headers.set("Set-Cookie", cookie(globalCfg.cookieName, token, globalCfg.cookieSettings));
120
- // And return it
121
- return new Response(null, { status: 200, headers });
122
- }
123
- case "logout": {
124
- const params = await getSession(globalCfg, req);
125
- // If there is no session, no need to call the callback
126
- if (!isNil(params.session) && !isNil(params.token)) {
127
- await globalCfg.callbacks.logout({
128
- headers: req.headers,
129
- token: params.token,
130
- session: params.session,
131
- });
132
- }
133
- // Use the strategy to logout
134
- await globalCfg.strategy.logOut(req, globalCfg);
135
- // Clears the header.
136
- const headers = new Headers();
137
- headers.set("Set-Cookie", cookie(globalCfg.cookieName, "deleted",
138
- // Use the same cookie config, but make sure it is expired
139
- assign({}, globalCfg.cookieSettings, {
140
- expires: new Date(0),
141
- maxAge: undefined,
142
- })));
143
- // And send them
144
- return new Response(null, { status: 200, headers });
145
- }
146
- default:
147
- // If a wrong action is requested, return a 404
148
- return new Response("Page not found", { status: 404 });
149
- }
150
- },
151
- /**
152
- * Deserialize a user's session.
153
- * @param globalCfg The global auth config
154
- * @param req An object having a headers field
155
- * @returns A user's token and session, if found and valid
156
- */
157
- getSession: (req) =>
158
- // Only returns the session
159
- getSession(globalCfg, req).then((doc) => doc.session),
160
- };
161
- });
@@ -1,33 +0,0 @@
1
- import { IProvider } from "./IProvider";
2
- import type { ConfigOptions } from "../@types/internals";
3
- import type { Session, MaybePromise } from "../@types/globals";
4
- /**
5
- * Configuration options of the Credentials provider
6
- */
7
- export type CredentialsConfig<TCredentials extends string> = Readonly<{
8
- /**
9
- * The name of this provider, should not be changed unless you are
10
- * using multiple instance of the same provider.
11
- */
12
- name?: "credentials" | (string & {});
13
- /**
14
- * The available fields coming from the request containing credentials.
15
- */
16
- credentials: TCredentials[];
17
- /**
18
- * Function that gets called when a user tries to login.
19
- * This is where you should look inside your database for the user.
20
- * @param credentials An object containing the credentials from the request's body.
21
- * @returns A session object if a user is found, or `null`.
22
- */
23
- authorize: (credentials: Record<TCredentials, string>) => MaybePromise<Session | null>;
24
- }>;
25
- /**
26
- * Provider used to login a user using basic credentials.
27
- */
28
- export declare class Credentials<TCredentials extends string = string> extends IProvider {
29
- private config;
30
- constructor(config: CredentialsConfig<TCredentials>);
31
- logIn(req: Request, globalCfg: ConfigOptions): Promise<string | null>;
32
- }
33
- //# sourceMappingURL=Credentials.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Credentials.d.ts","sourceRoot":"","sources":["../../src/providers/Credentials.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAE/D;;GAEG;AACH,MAAM,MAAM,iBAAiB,CAAC,YAAY,SAAS,MAAM,IAAI,QAAQ,CAAC;IAClE;;;OAGG;IACH,IAAI,CAAC,EAAE,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;IACrC;;OAEG;IACH,WAAW,EAAE,YAAY,EAAE,CAAC;IAC5B;;;;;OAKG;IACH,SAAS,EAAE,CAAC,WAAW,EAAE,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,KAAK,YAAY,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;CAC1F,CAAC,CAAC;AAEH;;GAEG;AACH,qBAAa,WAAW,CAAC,YAAY,SAAS,MAAM,GAAG,MAAM,CAAE,SAAQ,SAAS;IAC5E,OAAO,CAAC,MAAM,CAAkC;gBAEpC,MAAM,EAAE,iBAAiB,CAAC,YAAY,CAAC;IAK7B,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CAgC9F"}
@@ -1,42 +0,0 @@
1
- import { isNil } from "lodash-es";
2
- import { IProvider } from "./IProvider";
3
- import { urlencodedToJson } from "../functions";
4
- /**
5
- * Provider used to login a user using basic credentials.
6
- */
7
- export class Credentials extends IProvider {
8
- config;
9
- constructor(config) {
10
- super(config.name ?? "credentials");
11
- this.config = config;
12
- }
13
- async logIn(req, globalCfg) {
14
- const contentType = req.headers.get("Content-Type")?.split(";")[0] ?? "text/plain";
15
- let body;
16
- switch (contentType) {
17
- case "application/json":
18
- body = await req.json();
19
- break;
20
- case "application/x-www-urlencoded":
21
- body = await req.text().then((urlencodedToJson));
22
- break;
23
- case "multipart/form-data":
24
- const data = await req.formData();
25
- body = Object.fromEntries(data);
26
- break;
27
- // fields should come from a form, so every un-supported types will be failing.
28
- case "text/plain":
29
- default:
30
- return null;
31
- }
32
- // Calls the user defined authorize callback
33
- const session = await this.config.authorize(body);
34
- if (isNil(session))
35
- return null;
36
- // Create a token
37
- return globalCfg.strategy.serialize(session, globalCfg).catch((err) => {
38
- console.log(err);
39
- return null;
40
- });
41
- }
42
- }
@@ -1,29 +0,0 @@
1
- import type { ConfigOptions } from "../@types/internals";
2
- /**
3
- * Available url callback actions.
4
- */
5
- export type Actions = "login" | "logout";
6
- /**
7
- * Providers are used to implement certain services (E.g. facebook, github, credentials) as login methods.
8
- * Every provider should inherit from this.
9
- */
10
- declare abstract class IProvider {
11
- /**
12
- * This is used to map a callback to a provider.
13
- */
14
- private readonly __ID;
15
- constructor(ID: string);
16
- /**
17
- * The provider ID.
18
- */
19
- get ID(): string;
20
- /**
21
- * Login function. This is used to call all the login flows of each provider.
22
- * For now, the request's body **MUST** be JSON.
23
- * @param req The request object.
24
- * @param globalCfg The global auth config.
25
- */
26
- abstract logIn(req: Request, globalCfg: ConfigOptions): Promise<string | null>;
27
- }
28
- export { IProvider };
29
- //# sourceMappingURL=IProvider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"IProvider.d.ts","sourceRoot":"","sources":["../../src/providers/IProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEzC;;;GAGG;AACH,uBAAe,SAAS;IACpB;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;gBAElB,EAAE,EAAE,MAAM;IAItB;;OAEG;IACH,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED;;;;;OAKG;aACa,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CACxF;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -1,20 +0,0 @@
1
- /**
2
- * Providers are used to implement certain services (E.g. facebook, github, credentials) as login methods.
3
- * Every provider should inherit from this.
4
- */
5
- class IProvider {
6
- /**
7
- * This is used to map a callback to a provider.
8
- */
9
- __ID;
10
- constructor(ID) {
11
- this.__ID = ID;
12
- }
13
- /**
14
- * The provider ID.
15
- */
16
- get ID() {
17
- return this.__ID;
18
- }
19
- }
20
- export { IProvider };
@@ -1,3 +0,0 @@
1
- export * from "./IProvider";
2
- export * from "./Credentials";
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC"}
@@ -1,2 +0,0 @@
1
- export * from "./IProvider";
2
- export * from "./Credentials";
@@ -1,48 +0,0 @@
1
- import { type MaybePromise, type Session } from "../@types/globals";
2
- import type { ConfigOptions } from "../@types/internals";
3
- /**
4
- * Strategies callbacks
5
- */
6
- export type Callbacks = Partial<{
7
- /**
8
- * Pre-serialization callback. This can be used to add some steps to this process.
9
- * @param session The session to be serialized.
10
- * @returns A boolean representing if the serialization should occur.
11
- */
12
- serialize: (session: Session) => MaybePromise<boolean>;
13
- /**
14
- * Post-deserialization callback. This can be used to add some validation to this process.
15
- * @param session The token that was deserialized.
16
- * @returns A boolean representing if the deserialization is valid.
17
- */
18
- deserialize: (token: string, session: Session) => MaybePromise<boolean>;
19
- }>;
20
- /**
21
- * A strategy is used to handle the creation, validation and accessing a user's session.
22
- */
23
- declare abstract class IStrategy {
24
- protected callbacks: Callbacks;
25
- constructor(callbacks: Callbacks);
26
- /**
27
- * Handles how a session token is generated.
28
- * @param session The validated session object.
29
- * @param globalCfg The global auth config.
30
- * @returns A newly generated token that will be sent as a cookie.
31
- */
32
- abstract serialize(session: Session, globalCfg: ConfigOptions): Promise<string>;
33
- /**
34
- * Handles how a token is validated and deserialized into a session object.
35
- * @param token A user's token.
36
- * @param globalCfg The global auth config.
37
- * @returns A user's session if validated and found, else `null`.
38
- */
39
- abstract deserialize(token: string, globalCfg: ConfigOptions): Promise<Session | null>;
40
- /**
41
- * Handles how a session is destroyed when a user is logging out.
42
- * @param req The request object.
43
- * @param globalCfg The global auth config.
44
- */
45
- abstract logOut(req: Request, globalCfg: ConfigOptions): Promise<void>;
46
- }
47
- export { IStrategy };
48
- //# sourceMappingURL=IStrategy.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"IStrategy.d.ts","sourceRoot":"","sources":["../../src/strategies/IStrategy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC;IAC5B;;;;OAIG;IACH,SAAS,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,YAAY,CAAC,OAAO,CAAC,CAAC;IACvD;;;;OAIG;IACH,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,YAAY,CAAC,OAAO,CAAC,CAAC;CAC3E,CAAC,CAAC;AAEH;;GAEG;AACH,uBAAe,SAAS;IACpB,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC;gBAEnB,SAAS,EAAE,SAAS;IAIhC;;;;;OAKG;aACa,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAEtF;;;;;OAKG;aACa,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAE7F;;;;OAIG;aACa,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAChF;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -1,11 +0,0 @@
1
- import {} from "../@types/globals";
2
- /**
3
- * A strategy is used to handle the creation, validation and accessing a user's session.
4
- */
5
- class IStrategy {
6
- callbacks;
7
- constructor(callbacks) {
8
- this.callbacks = callbacks;
9
- }
10
- }
11
- export { IStrategy };
@@ -1,3 +0,0 @@
1
- export * from "./jwt";
2
- export * from "./IStrategy";
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/strategies/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC;AACtB,cAAc,aAAa,CAAC"}
@@ -1,2 +0,0 @@
1
- export * from "./jwt";
2
- export * from "./IStrategy";
@@ -1,19 +0,0 @@
1
- import type { SignOptions } from "jsonwebtoken";
2
- import type { Session } from "../@types/globals";
3
- import { IStrategy, type Callbacks } from "./IStrategy";
4
- import type { ConfigOptions } from "../@types/internals";
5
- /**
6
- * Basic JWT strategy
7
- */
8
- declare class JWT extends IStrategy {
9
- /**
10
- * Forwarded standard JWT options
11
- */
12
- private signOptions;
13
- constructor(options?: SignOptions, callbacks?: Callbacks);
14
- serialize(session: Session, globalCfg: ConfigOptions): Promise<string>;
15
- deserialize(token: string, globalCfg: ConfigOptions): Promise<Session | null>;
16
- logOut(): Promise<void>;
17
- }
18
- export { JWT };
19
- //# sourceMappingURL=jwt.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../../src/strategies/jwt.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAgBzD;;GAEG;AACH,cAAM,GAAI,SAAQ,SAAS;IACvB;;OAEG;IACH,OAAO,CAAC,WAAW,CAAc;gBAErB,OAAO,GAAE,WAAiC,EAAE,SAAS,GAAE,SAAc;IAM3D,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAY5E,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAS7E,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;CAI1C;AAED,OAAO,EAAE,GAAG,EAAE,CAAC"}
@@ -1,51 +0,0 @@
1
- import { isNil, isString } from "lodash-es";
2
- import { verify, sign } from "../functions/jwt";
3
- import { IStrategy } from "./IStrategy";
4
- /**
5
- * Retrieves either the secret or a private key, depending on the used JWT algorithm
6
- * @param secret Secret key, or key pair
7
- * @returns The secret or private key
8
- */
9
- const secretOrPrivateKey = (secret) => (isString(secret) ? secret : secret.privateKey);
10
- /**
11
- * Retrieves either the secret or a public key, depending on the used JWT algorithm
12
- * @param secret Secret key, or key pair
13
- * @returns The secret or public key
14
- */
15
- const secretOrPublicKey = (secret) => (isString(secret) ? secret : secret.publicKey);
16
- /**
17
- * Basic JWT strategy
18
- */
19
- class JWT extends IStrategy {
20
- /**
21
- * Forwarded standard JWT options
22
- */
23
- signOptions;
24
- constructor(options = { expiresIn: "1h" }, callbacks = {}) {
25
- super(callbacks);
26
- this.signOptions = options;
27
- }
28
- async serialize(session, globalCfg) {
29
- // If there is no callback set, we can just run normally, so fallback to true.
30
- const shouldRun = await Promise.resolve(this.callbacks.serialize?.(session) ?? true);
31
- if (!shouldRun) {
32
- return Promise.reject("Serialize callback rejection");
33
- }
34
- // Directly call the sign function, but make it async.
35
- return Promise.resolve(sign(session, secretOrPrivateKey(globalCfg.secret), this.signOptions));
36
- }
37
- deserialize(token, globalCfg) {
38
- // The verify function does everything for us, in this case.
39
- return verify(token, secretOrPublicKey(globalCfg.secret)).then(async (session) => {
40
- if (isNil(session))
41
- return null;
42
- const isValid = await Promise.resolve(this.callbacks.deserialize?.(token, session) ?? true);
43
- return isValid ? session : null;
44
- });
45
- }
46
- logOut() {
47
- // Since a JWT does not have any data in a DB, there is nothing to do here.
48
- return Promise.resolve();
49
- }
50
- }
51
- export { JWT };