@tsed/passport 8.0.1 → 8.0.3

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/package.json CHANGED
@@ -2,13 +2,14 @@
2
2
  "name": "@tsed/passport",
3
3
  "description": "Passport package for Ts.ED framework",
4
4
  "type": "module",
5
- "version": "8.0.1",
5
+ "version": "8.0.3",
6
6
  "source": "./src/index.ts",
7
7
  "main": "./lib/esm/index.js",
8
8
  "module": "./lib/esm/index.js",
9
9
  "typings": "./lib/types/index.d.ts",
10
10
  "exports": {
11
11
  ".": {
12
+ "@tsed/source": "./src/index.ts",
12
13
  "types": "./lib/types/index.d.ts",
13
14
  "import": "./lib/esm/index.js",
14
15
  "default": "./lib/esm/index.js"
@@ -27,12 +28,12 @@
27
28
  "tslib": "2.7.0"
28
29
  },
29
30
  "devDependencies": {
30
- "@tsed/barrels": "8.0.1",
31
- "@tsed/core": "8.0.1",
32
- "@tsed/di": "8.0.1",
33
- "@tsed/platform-http": "8.0.1",
34
- "@tsed/platform-router": "8.0.1",
35
- "@tsed/typescript": "8.0.1",
31
+ "@tsed/barrels": "8.0.3",
32
+ "@tsed/core": "8.0.3",
33
+ "@tsed/di": "8.0.3",
34
+ "@tsed/platform-http": "8.0.3",
35
+ "@tsed/platform-router": "8.0.3",
36
+ "@tsed/typescript": "8.0.3",
36
37
  "@types/passport": "1.0.16",
37
38
  "@types/passport-http": "0.3.11",
38
39
  "@types/passport-local": "1.0.38",
@@ -46,7 +47,7 @@
46
47
  "vitest": "2.1.2"
47
48
  },
48
49
  "peerDependencies": {
49
- "@tsed/platform-http": "8.0.1",
50
+ "@tsed/platform-http": "8.0.3",
50
51
  "passport": ">=0.4.1"
51
52
  },
52
53
  "peerDependenciesMeta": {
@@ -0,0 +1,75 @@
1
+ import "../src/index.js";
2
+
3
+ import {PlatformApplication} from "@tsed/platform-http";
4
+ import {PlatformTest} from "@tsed/platform-http/testing";
5
+ import Passport from "passport";
6
+
7
+ import {PassportModule} from "./PassportModule.js";
8
+
9
+ vi.mock("passport");
10
+
11
+ beforeEach(() => {
12
+ (Passport.initialize as any).mockReturnValue("initializeMiddleware");
13
+ (Passport.session as any).mockReturnValue("sessionMiddleware");
14
+ });
15
+ describe("PassportModule", () => {
16
+ describe("passport.session() - disabled", () => {
17
+ beforeEach(() =>
18
+ PlatformTest.create({
19
+ PLATFORM_NAME: "express",
20
+ passport: {
21
+ disableSession: true
22
+ }
23
+ })
24
+ );
25
+ afterEach(PlatformTest.reset);
26
+ it("should not add the passport.session to the express application", async () => {
27
+ const app = {
28
+ use: vi.fn()
29
+ };
30
+ const passportModule = await PlatformTest.invoke<PassportModule>(PassportModule, [
31
+ {
32
+ token: PlatformApplication,
33
+ use: app
34
+ }
35
+ ]);
36
+
37
+ passportModule.$beforeRoutesInit();
38
+
39
+ expect(app.use).toHaveBeenCalledWith("initializeMiddleware");
40
+ expect(app.use).not.toHaveBeenCalledWith("sessionMiddleware");
41
+ expect(Passport.initialize).toHaveBeenCalledWith({userProperty: undefined});
42
+ });
43
+ });
44
+
45
+ describe("passport.session() - enabled", () => {
46
+ beforeEach(() =>
47
+ PlatformTest.create({
48
+ PLATFORM_NAME: "express",
49
+ passport: {
50
+ disableSession: false
51
+ }
52
+ })
53
+ );
54
+ afterEach(PlatformTest.reset);
55
+
56
+ it("should add the passport.session to the express application", async () => {
57
+ const app = {
58
+ use: vi.fn()
59
+ };
60
+ const passportModule = await PlatformTest.invoke<PassportModule>(PassportModule, [
61
+ {
62
+ token: PlatformApplication,
63
+ use: app
64
+ }
65
+ ]);
66
+
67
+ passportModule.$beforeRoutesInit();
68
+
69
+ expect(app.use).toHaveBeenCalledWith("initializeMiddleware");
70
+ expect(app.use).toHaveBeenCalledWith("sessionMiddleware");
71
+ expect(Passport.initialize).toHaveBeenCalledWith({userProperty: undefined});
72
+ expect(Passport.session).toHaveBeenCalledWith({pauseStream: undefined});
73
+ });
74
+ });
75
+ });
@@ -0,0 +1,58 @@
1
+ import {Constant, Inject, Module, type OnInit, Provider} from "@tsed/di";
2
+ import {Logger} from "@tsed/logger";
3
+ import {BeforeRoutesInit, PlatformApplication} from "@tsed/platform-http";
4
+ import Passport from "passport";
5
+
6
+ import {PassportSerializerService} from "./services/PassportSerializerService.js";
7
+ import {ProtocolsService} from "./services/ProtocolsService.js";
8
+
9
+ /**
10
+ * @ignore
11
+ */
12
+ @Module()
13
+ export class PassportModule implements OnInit, BeforeRoutesInit {
14
+ @Constant("passport.userProperty")
15
+ userProperty: string;
16
+
17
+ @Constant("passport.pauseStream")
18
+ pauseStream: boolean;
19
+
20
+ @Constant("passport.disableSession", false)
21
+ disableSession: boolean;
22
+
23
+ @Constant("PLATFORM_NAME")
24
+ platformName: string;
25
+
26
+ @Inject()
27
+ logger: Logger;
28
+
29
+ constructor(
30
+ private app: PlatformApplication,
31
+ private protocolsService: ProtocolsService,
32
+ private passportSerializer: PassportSerializerService
33
+ ) {}
34
+
35
+ async $onInit(): Promise<any> {
36
+ Passport.serializeUser(this.passportSerializer.serialize.bind(this.passportSerializer));
37
+ Passport.deserializeUser(this.passportSerializer.deserialize.bind(this.passportSerializer));
38
+
39
+ const promises = this.protocolsService.getProtocols().map((provider: Provider) => this.protocolsService.invoke(provider));
40
+
41
+ await Promise.all(promises);
42
+ return undefined;
43
+ }
44
+
45
+ $beforeRoutesInit(): void | Promise<any> {
46
+ const {userProperty, pauseStream} = this;
47
+ switch (this.platformName) {
48
+ case "express":
49
+ this.app.use(Passport.initialize({userProperty}));
50
+ !this.disableSession && this.app.use(Passport.session({pauseStream}));
51
+
52
+ return;
53
+
54
+ default:
55
+ this.logger.warn(`Platform "${this.platformName}" not supported by @tsed/passport`);
56
+ }
57
+ }
58
+ }
@@ -0,0 +1 @@
1
+ export const PROVIDER_TYPE_PROTOCOL = "protocol";
@@ -0,0 +1,53 @@
1
+ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2
+
3
+ exports[`@Authorize > should support inheritance 1`] = `
4
+ {
5
+ "paths": {
6
+ "/admin/allEntries": {
7
+ "get": {
8
+ "operationId": "abstractAdminControllerGetAllEntries",
9
+ "parameters": [],
10
+ "responses": {
11
+ "200": {
12
+ "description": "Success",
13
+ },
14
+ },
15
+ "tags": [
16
+ "AdminController",
17
+ ],
18
+ },
19
+ },
20
+ },
21
+ "tags": [
22
+ {
23
+ "name": "AdminController",
24
+ },
25
+ ],
26
+ }
27
+ `;
28
+
29
+ exports[`@Authorize > should support inheritance 2`] = `
30
+ {
31
+ "paths": {
32
+ "/admin/bucket/allEntries": {
33
+ "get": {
34
+ "operationId": "abstractAdminControllerGetAllEntries",
35
+ "parameters": [],
36
+ "responses": {
37
+ "200": {
38
+ "description": "Success",
39
+ },
40
+ },
41
+ "tags": [
42
+ "BucketAdminController",
43
+ ],
44
+ },
45
+ },
46
+ },
47
+ "tags": [
48
+ {
49
+ "name": "BucketAdminController",
50
+ },
51
+ ],
52
+ }
53
+ `;
@@ -0,0 +1,28 @@
1
+ import {ParamTypes} from "@tsed/platform-params";
2
+ import {JsonParameterStore} from "@tsed/schema";
3
+
4
+ import {Arg, Args} from "./args.js";
5
+
6
+ describe("@Args", () => {
7
+ it("should register a new parameter instance with the correct property", () => {
8
+ class Ctrl {
9
+ test(@Args() args: any[]) {}
10
+ }
11
+
12
+ const param = JsonParameterStore.get(Ctrl, "test", 0);
13
+ expect(param.expression).toBe("PROTOCOL_ARGS");
14
+ expect(param.paramType).toBe(ParamTypes.$CTX);
15
+ });
16
+ });
17
+
18
+ describe("@Arg", () => {
19
+ it("should register a new parameter instance with the correct property", () => {
20
+ class Ctrl {
21
+ test(@Arg(0) args: any[]) {}
22
+ }
23
+
24
+ const param = JsonParameterStore.get(Ctrl, "test", 0);
25
+ expect(param.expression).toBe("PROTOCOL_ARGS.0");
26
+ expect(param.paramType).toBe(ParamTypes.$CTX);
27
+ });
28
+ });
@@ -0,0 +1,14 @@
1
+ import {useDecorators} from "@tsed/core";
2
+ import {Context} from "@tsed/platform-params";
3
+
4
+ /**
5
+ * Inject args resolve by the passport strategy on verify method.
6
+ * @decorator
7
+ */
8
+ export function Args() {
9
+ return useDecorators(Context("PROTOCOL_ARGS"));
10
+ }
11
+
12
+ export function Arg(index: number) {
13
+ return useDecorators(Context(`PROTOCOL_ARGS.${index}`));
14
+ }
@@ -0,0 +1,55 @@
1
+ import {Store} from "@tsed/core";
2
+ import {Security} from "@tsed/schema";
3
+
4
+ import {Authenticate, PassportMiddleware} from "../index.js";
5
+
6
+ describe("@Authenticate", () => {
7
+ it("should store data", () => {
8
+ class Test {
9
+ @Authenticate("local", {
10
+ security: {
11
+ test: ["scope"]
12
+ }
13
+ })
14
+ test() {}
15
+ }
16
+
17
+ const store = Store.fromMethod(Test, "test");
18
+
19
+ expect(store.get(PassportMiddleware)).toEqual({
20
+ method: "authenticate",
21
+ options: {
22
+ security: {
23
+ test: ["scope"]
24
+ }
25
+ },
26
+ protocol: "local",
27
+ originalUrl: true
28
+ });
29
+ });
30
+ it("should store data (without originalUrl)", () => {
31
+ class Test {
32
+ @Authenticate("local", {
33
+ security: {
34
+ test: ["scope"]
35
+ },
36
+ originalUrl: false
37
+ })
38
+ test() {}
39
+ }
40
+
41
+ const store = Store.fromMethod(Test, "test");
42
+
43
+ expect(store.get(PassportMiddleware)).toEqual({
44
+ method: "authenticate",
45
+ options: {
46
+ security: {
47
+ test: ["scope"]
48
+ },
49
+ originalUrl: false
50
+ },
51
+ protocol: "local",
52
+ originalUrl: false
53
+ });
54
+ });
55
+ });
@@ -0,0 +1,25 @@
1
+ import {useDecorators} from "@tsed/core";
2
+ import {UseAuth} from "@tsed/platform-middlewares";
3
+ import {Security} from "@tsed/schema";
4
+ import {AuthenticateOptions as PassportAuthenticateOptions} from "passport";
5
+
6
+ import {PassportMiddleware} from "../middlewares/PassportMiddleware.js";
7
+
8
+ export interface AuthenticateOptions extends PassportAuthenticateOptions {
9
+ security?: Record<string, string[]>;
10
+ originalUrl?: boolean;
11
+ }
12
+
13
+ export function Authenticate(protocol: string | string[] = "*", options: AuthenticateOptions = {}): Function {
14
+ return useDecorators(
15
+ UseAuth(PassportMiddleware, {
16
+ protocol,
17
+ method: "authenticate",
18
+ originalUrl: options.originalUrl === undefined ? true : options.originalUrl,
19
+ options
20
+ }),
21
+ ...Object.entries(options.security || {}).map(([key, value]) => {
22
+ return Security(key, ...value);
23
+ })
24
+ );
25
+ }
@@ -0,0 +1,96 @@
1
+ import {Store} from "@tsed/core";
2
+ import {Controller, inject} from "@tsed/di";
3
+ import {Middleware, UseBefore} from "@tsed/platform-middlewares";
4
+ import {Get, getSpec} from "@tsed/schema";
5
+
6
+ import {Authorize, PassportMiddleware} from "../index.js";
7
+
8
+ @Middleware()
9
+ class AuthoriseBucket {
10
+ use() {}
11
+ }
12
+
13
+ describe("@Authorize", () => {
14
+ it("should store data", () => {
15
+ class Test {
16
+ @Authorize("local", {
17
+ security: {
18
+ test: ["scope"]
19
+ }
20
+ })
21
+ test() {}
22
+ }
23
+
24
+ const store = Store.fromMethod(Test, "test");
25
+
26
+ expect(store.get(PassportMiddleware)).toEqual({
27
+ method: "authorize",
28
+ options: {
29
+ security: {
30
+ test: ["scope"]
31
+ }
32
+ },
33
+ originalUrl: true,
34
+ protocol: "local"
35
+ });
36
+ });
37
+ it("should store data (without originalUrl)", () => {
38
+ class Test {
39
+ @Authorize("local", {
40
+ security: {
41
+ test: ["scope"]
42
+ },
43
+ originalUrl: false
44
+ })
45
+ test() {}
46
+ }
47
+
48
+ const store = Store.fromMethod(Test, "test");
49
+
50
+ expect(store.get(PassportMiddleware)).toEqual({
51
+ method: "authorize",
52
+ options: {
53
+ security: {
54
+ test: ["scope"]
55
+ },
56
+ originalUrl: false
57
+ },
58
+ originalUrl: false,
59
+ protocol: "local"
60
+ });
61
+ });
62
+ it("should support inheritance", async () => {
63
+ abstract class AbstractAdminController {
64
+ @Get("/allEntries")
65
+ getAllEntries(): Promise<unknown> {
66
+ return Promise.resolve({});
67
+ }
68
+ }
69
+
70
+ @Authorize("loginAuthProvider")
71
+ @Controller("/admin")
72
+ class AdminController extends AbstractAdminController {}
73
+
74
+ @Controller("/admin/bucket")
75
+ @UseBefore(AuthoriseBucket)
76
+ class BucketAdminController extends AbstractAdminController {}
77
+
78
+ expect(getSpec(AdminController)).toMatchSnapshot();
79
+ expect(getSpec(BucketAdminController)).toMatchSnapshot();
80
+ expect(Reflect.getOwnPropertyDescriptor(AdminController.prototype, "getAllEntries")).toBeDefined();
81
+ expect(Reflect.getOwnPropertyDescriptor(BucketAdminController.prototype, "getAllEntries")).not.toBeDefined();
82
+
83
+ const adminController = inject(AdminController);
84
+
85
+ expect(await adminController.getAllEntries()).toEqual({});
86
+
87
+ expect(Store.fromMethod(BucketAdminController, "getAllEntries").get(PassportMiddleware)).toEqual(undefined);
88
+ expect(Store.fromMethod(AbstractAdminController, "getAllEntries").get(PassportMiddleware)).toEqual(undefined);
89
+ expect(Store.fromMethod(AdminController, "getAllEntries").get(PassportMiddleware)).toEqual({
90
+ method: "authorize",
91
+ options: {},
92
+ originalUrl: true,
93
+ protocol: "loginAuthProvider"
94
+ });
95
+ });
96
+ });
@@ -0,0 +1,25 @@
1
+ import {useDecorators} from "@tsed/core";
2
+ import {UseAuth} from "@tsed/platform-middlewares";
3
+ import {Security} from "@tsed/schema";
4
+ import {AuthenticateOptions} from "passport";
5
+
6
+ import {PassportMiddleware} from "../middlewares/PassportMiddleware.js";
7
+
8
+ export interface AuthorizeOptions extends AuthenticateOptions {
9
+ security?: Record<string, string[]>;
10
+ originalUrl?: boolean;
11
+ }
12
+
13
+ export function Authorize(protocol: string | string[] = "*", options: AuthorizeOptions = {}): Function {
14
+ return useDecorators(
15
+ UseAuth(PassportMiddleware, {
16
+ protocol,
17
+ method: "authorize",
18
+ originalUrl: options.originalUrl === undefined ? true : options.originalUrl,
19
+ options
20
+ }),
21
+ ...Object.entries(options.security || {}).map(([key, value]) => {
22
+ return Security(key, ...value);
23
+ })
24
+ );
25
+ }
@@ -0,0 +1,29 @@
1
+ import {StoreSet, useDecorators} from "@tsed/core";
2
+ import {Configuration, Injectable} from "@tsed/di";
3
+
4
+ import {PROVIDER_TYPE_PROTOCOL} from "../contants/constants.js";
5
+ import {ProtocolOptions} from "../interfaces/ProtocolOptions.js";
6
+
7
+ /**
8
+ * Declare a new Protocol base on a Passport Strategy
9
+ *
10
+ * @decorator
11
+ * @class
12
+ */
13
+ export function Protocol<T = any>(options: ProtocolOptionsDecorator<T>) {
14
+ return useDecorators(
15
+ Injectable({
16
+ type: PROVIDER_TYPE_PROTOCOL
17
+ }),
18
+ StoreSet("protocol", options),
19
+ Configuration({
20
+ passport: {
21
+ protocols: {
22
+ [options.name]: options
23
+ }
24
+ }
25
+ })
26
+ );
27
+ }
28
+
29
+ export type ProtocolOptionsDecorator<T = any> = {name: string} & Partial<ProtocolOptions<T>>;
@@ -0,0 +1,13 @@
1
+ import {Format, Property} from "@tsed/schema";
2
+
3
+ export class UserInfo {
4
+ @Property()
5
+ id: string;
6
+
7
+ @Property()
8
+ @Format("email")
9
+ email: string;
10
+
11
+ @Property()
12
+ password: string;
13
+ }
@@ -0,0 +1,8 @@
1
+ import {Exception} from "@tsed/exceptions";
2
+
3
+ export class PassportException extends Exception {
4
+ constructor(error: any) {
5
+ super(error.status || 500, error.message);
6
+ this.name = error.name || this.name;
7
+ }
8
+ }
@@ -0,0 +1,10 @@
1
+ import {Unauthorized} from "@tsed/exceptions";
2
+
3
+ export class PassportMessage extends Unauthorized {
4
+ constructor(
5
+ message: string,
6
+ public opts: Record<string, unknown> = {}
7
+ ) {
8
+ super(message);
9
+ }
10
+ }
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @file Automatically generated by @tsed/barrels.
3
+ */
4
+ export * from "./contants/constants.js";
5
+ export * from "./decorators/args.js";
6
+ export * from "./decorators/authenticate.js";
7
+ export * from "./decorators/authorize.js";
8
+ export * from "./decorators/protocol.js";
9
+ export * from "./domain/UserInfo.js";
10
+ export * from "./errors/PassportException.js";
11
+ export * from "./errors/PassportMessage.js";
12
+ export * from "./interfaces/BeforeInstall.js";
13
+ export * from "./interfaces/interfaces.js";
14
+ export * from "./interfaces/OnInstall.js";
15
+ export * from "./interfaces/OnVerify.js";
16
+ export * from "./interfaces/ProtocolMethods.js";
17
+ export * from "./interfaces/ProtocolOptions.js";
18
+ export * from "./middlewares/PassportMiddleware.js";
19
+ export * from "./PassportModule.js";
20
+ export * from "./services/PassportSerializerService.js";
21
+ export * from "./services/ProtocolsService.js";
22
+ export * from "./utils/getProtocolsFromRequest.js";
@@ -0,0 +1,3 @@
1
+ export interface BeforeInstall<Settings = any> {
2
+ $beforeInstall(setting: Settings): Promise<Settings> | Settings | void;
3
+ }
@@ -0,0 +1,5 @@
1
+ import {Strategy} from "passport";
2
+
3
+ export interface OnInstall {
4
+ $onInstall(strategy: Strategy): void | Promise<void>;
5
+ }
@@ -0,0 +1,3 @@
1
+ export interface OnVerify {
2
+ $onVerify(...args: any[]): Promise<any | any[]> | any | any[];
3
+ }
@@ -0,0 +1,5 @@
1
+ import {BeforeInstall} from "./BeforeInstall.js";
2
+ import {OnInstall} from "./OnInstall.js";
3
+ import {OnVerify} from "./OnVerify.js";
4
+
5
+ export interface ProtocolMethods<Settings = any> extends OnVerify, OnInstall, BeforeInstall<Settings> {}
@@ -0,0 +1,8 @@
1
+ import {Type} from "@tsed/core";
2
+ import {Strategy} from "passport";
3
+
4
+ export interface ProtocolOptions<Settings = any> {
5
+ name: string;
6
+ useStrategy: Type<Strategy>;
7
+ settings: Settings;
8
+ }
@@ -0,0 +1,21 @@
1
+ import {Type} from "@tsed/core";
2
+ import {PassportStatic} from "passport";
3
+
4
+ import {ProtocolOptions} from "./ProtocolOptions.js";
5
+
6
+ declare global {
7
+ namespace TsED {
8
+ interface Configuration {
9
+ passport: {
10
+ userProperty?: string;
11
+ pauseStream?: string;
12
+ disableSession?: boolean;
13
+ userInfoModel?: Type<any> | false;
14
+ module?: PassportStatic;
15
+ protocols?: {
16
+ [protocolName: string]: Partial<ProtocolOptions>;
17
+ };
18
+ };
19
+ }
20
+ }
21
+ }