@loopback/authentication-passport 0.1.0

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,25 @@
1
+ Copyright (c) IBM Corp. 2017,2019. All Rights Reserved.
2
+ Node module: @loopback/authentication-passport
3
+ This project is licensed under the MIT License, full text below.
4
+
5
+ --------
6
+
7
+ MIT license
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,189 @@
1
+ # Passport Strategy Adapter
2
+
3
+ _Important: We strongly suggest that users understand LoopBack's
4
+ [authentication system](https://loopback.io/doc/en/lb4/Loopback-component-authentication.html)
5
+ before using this module_
6
+
7
+ This is an adapter module created for plugging in
8
+ [`passport`](https://www.npmjs.com/package/passport) based strategies to the
9
+ authentication system in `@loopback/authentication@2.x`.
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ npm i @loopback/authentication-passport --save
15
+ ```
16
+
17
+ ## Background
18
+
19
+ `@loopback/authentication@2.x` allows users to register authentication
20
+ strategies that implement the interface
21
+ [`AuthenticationStrategy`](https://apidocs.strongloop.com/@loopback%2fdocs/authentication.html#AuthenticationStrategy)
22
+
23
+ Since `AuthenticationStrategy` describes a strategy with different contracts
24
+ than the passport
25
+ [`Strategy`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/passport/index.d.ts#L79),
26
+ and we'd like to support the existing 500+ community passport strategies, an
27
+ **adapter class** is created in this package to convert a passport strategy to
28
+ the one that LoopBack 4 authentication system wants.
29
+
30
+ ## Usage
31
+
32
+ ### Simple Usage
33
+
34
+ 1. Create an instance of the passport strategy
35
+
36
+ Taking the basic strategy exported from
37
+ [`passport-http`](https://github.com/jaredhanson/passport-http) as an example,
38
+ first create an instance of the basic strategy with your `verify` function.
39
+
40
+ ```ts
41
+ import {BasicStrategy} from 'passport-http';
42
+
43
+ function verify(username: string, password: string, cb: Function) {
44
+ users.find(username, password, cb);
45
+ }
46
+ const basicStrategy = new BasicStrategy(verify);
47
+ ```
48
+
49
+ It's a similar configuration as you do when adding a strategy to a `passport` by
50
+ calling `passport.use()`.
51
+
52
+ 2. Apply the adapter to the strategy
53
+
54
+ ```ts
55
+ const AUTH_STRATEGY_NAME = 'basic';
56
+
57
+ const basicAuthStrategy = new StrategyAdapter(
58
+ // The configured basic strategy instance
59
+ basicStrategy,
60
+ // Give the strategy a name
61
+ // You'd better define your strategy name as a constant, like
62
+ // `const AUTH_STRATEGY_NAME = 'basic'`.
63
+ // You will need to decorate the APIs later with the same name.
64
+ AUTH_STRATEGY_NAME,
65
+ );
66
+ ```
67
+
68
+ 3. Register(bind) the strategy to app
69
+
70
+ ```ts
71
+ import {Application, CoreTags} from '@loopback/core';
72
+ import {AuthenticationBindings} from '@loopback/authentication';
73
+
74
+ app
75
+ .bind('authentication.strategies.basicAuthStrategy')
76
+ .to(basicAuthStrategy)
77
+ .tag({
78
+ [CoreTags.EXTENSION_FOR]:
79
+ AuthenticationBindings.AUTHENTICATION_STRATEGY_EXTENSION_POINT_NAME,
80
+ });
81
+ ```
82
+
83
+ ### With Provider
84
+
85
+ If you need to inject stuff (e.g. the verify function) when configuring the
86
+ strategy, you may want to provide your strategy as a provider.
87
+
88
+ _Note: If you are not familiar with LoopBack providers, check the documentation
89
+ in
90
+ [Extending LoopBack 4](https://loopback.io/doc/en/lb4/Extending-LoopBack-4.html)_
91
+
92
+ 1. Create a provider for the strategy
93
+
94
+ Use `passport-http` as the example again:
95
+
96
+ ```ts
97
+ class PassportBasicAuthProvider implements Provider<AuthenticationStrategy> {
98
+ value(): AuthenticationStrategy {
99
+ // The code that returns the converted strategy
100
+ }
101
+ }
102
+ ```
103
+
104
+ The Provider should have two functions:
105
+
106
+ - A function that takes in the verify callback function and returns a configured
107
+ basic strategy. To know more about the configuration, please check
108
+ [the configuration guide in module `passport-http`](https://github.com/jaredhanson/passport-http#usage-of-http-basic).
109
+
110
+ - A function that applies the `StrategyAdapter` to the configured basic strategy
111
+ instance. Then in the `value()` function, you return the converted strategy.
112
+
113
+ So a full implementation of the provider is:
114
+
115
+ ```ts
116
+ import {BasicStrategy, BasicVerifyFunction} from 'passport-http';
117
+ import {StrategyAdapter} from `@loopback/passport-adapter`;
118
+ import {AuthenticationStrategy} from '@loopback/authentication';
119
+
120
+ class PassportBasicAuthProvider implements Provider<AuthenticationStrategy> {
121
+ constructor(
122
+ @inject('authentication.basic.verify') verifyFn: BasicVerifyFunction,
123
+ );
124
+ value(): AuthenticationStrategy {
125
+ const basicStrategy = this.configuredBasicStrategy(verify);
126
+ return this.convertToAuthStrategy(basicStrategy);
127
+ }
128
+
129
+ // Takes in the verify callback function and returns a configured basic strategy.
130
+ configuredBasicStrategy(verifyFn: BasicVerifyFunction): BasicStrategy {
131
+ return new BasicStrategy(verifyFn);
132
+ }
133
+
134
+ // Applies the `StrategyAdapter` to the configured basic strategy instance.
135
+ // You'd better define your strategy name as a constant, like
136
+ // `const AUTH_STRATEGY_NAME = 'basic'`
137
+ // You will need to decorate the APIs later with the same name
138
+ convertToAuthStrategy(basic: BasicStrategy): AuthenticationStrategy {
139
+ return new StrategyAdapter(basic, AUTH_STRATEGY_NAME);
140
+ }
141
+ }
142
+ ```
143
+
144
+ 2. Register the strategy provider
145
+
146
+ Register the strategy provider in your LoopBack application so that the
147
+ authentication system can look for your strategy by name and invoke it:
148
+
149
+ ```ts
150
+ // In the main file
151
+
152
+ import {addExtension} from '@loopback/core';
153
+ import {MyApplication} from '<path_to_your_app>';
154
+ import {PassportBasicAuthProvider} from '<path_to_the_provider>';
155
+ import {
156
+ AuthenticationBindings,
157
+ registerAuthenticationStrategy,
158
+ } from '@loopback/authentication';
159
+
160
+ const app = new MyApplication();
161
+
162
+ // In a real app the function would be imported from a community module
163
+ function verify(username: string, password: string, cb: Function) {
164
+ users.find(username, password, cb);
165
+ }
166
+
167
+ app.bind('authentication.basic.verify').to(verify);
168
+ registerAuthenticationStrategy(app, PassportBasicAuthProvider);
169
+ ```
170
+
171
+ 3. Decorate your endpoint
172
+
173
+ To authenticate your request with the basic strategy, decorate your controller
174
+ function like:
175
+
176
+ ```ts
177
+ class MyController {
178
+ constructor(
179
+ @inject(AuthenticationBindings.CURRENT_USER) private user: UserProfile,
180
+ ) {}
181
+
182
+ // Define your strategy name as a constant so that
183
+ // it is consistent with the name you provide in the adapter
184
+ @authenticate(AUTH_STRATEGY_NAME)
185
+ async whoAmI(): Promise<string> {
186
+ return this.user.id;
187
+ }
188
+ }
189
+ ```
@@ -0,0 +1 @@
1
+ export * from './strategy-adapter';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ __export(require("./strategy-adapter"));
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,wCAAmC"}
@@ -0,0 +1,28 @@
1
+ import { AuthenticationStrategy, UserProfile } from '@loopback/authentication';
2
+ import { Request } from '@loopback/rest';
3
+ import { Strategy } from 'passport';
4
+ /**
5
+ * Adapter class to invoke passport-strategy
6
+ * 1. provides express dependencies to the passport strategies
7
+ * 2. provides shimming of requests for passport authentication
8
+ * 3. provides lifecycle similar to express to the passport-strategy
9
+ * 4. provides state methods to the strategy instance
10
+ * see: https://github.com/jaredhanson/passport
11
+ */
12
+ export declare class StrategyAdapter implements AuthenticationStrategy {
13
+ private readonly strategy;
14
+ readonly name: string;
15
+ /**
16
+ * @param strategy instance of a class which implements a passport-strategy;
17
+ * @description http://passportjs.org/
18
+ */
19
+ constructor(strategy: Strategy, name: string);
20
+ /**
21
+ * The function to invoke the contained passport strategy.
22
+ * 1. Create an instance of the strategy
23
+ * 2. add success and failure state handlers
24
+ * 3. authenticate using the strategy
25
+ * @param request The incoming request.
26
+ */
27
+ authenticate(request: Request): Promise<UserProfile>;
28
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ // Copyright IBM Corp. 2017,2019. All Rights Reserved.
3
+ // Node module: @loopback/authentication-passport
4
+ // This file is licensed under the MIT License.
5
+ // License text available at https://opensource.org/licenses/MIT
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const rest_1 = require("@loopback/rest");
8
+ const passportRequestMixin = require('passport/lib/http/request');
9
+ /**
10
+ * Adapter class to invoke passport-strategy
11
+ * 1. provides express dependencies to the passport strategies
12
+ * 2. provides shimming of requests for passport authentication
13
+ * 3. provides lifecycle similar to express to the passport-strategy
14
+ * 4. provides state methods to the strategy instance
15
+ * see: https://github.com/jaredhanson/passport
16
+ */
17
+ class StrategyAdapter {
18
+ /**
19
+ * @param strategy instance of a class which implements a passport-strategy;
20
+ * @description http://passportjs.org/
21
+ */
22
+ constructor(strategy, name) {
23
+ this.strategy = strategy;
24
+ this.name = name;
25
+ }
26
+ /**
27
+ * The function to invoke the contained passport strategy.
28
+ * 1. Create an instance of the strategy
29
+ * 2. add success and failure state handlers
30
+ * 3. authenticate using the strategy
31
+ * @param request The incoming request.
32
+ */
33
+ authenticate(request) {
34
+ return new Promise((resolve, reject) => {
35
+ // mix-in passport additions like req.logIn and req.logOut
36
+ for (const key in passportRequestMixin) {
37
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
+ request[key] = passportRequestMixin[key];
39
+ }
40
+ // create a prototype chain of an instance of a passport strategy
41
+ const strategy = Object.create(this.strategy);
42
+ // add success state handler to strategy instance
43
+ strategy.success = function (user) {
44
+ resolve(user);
45
+ };
46
+ // add failure state handler to strategy instance
47
+ strategy.fail = function (challenge) {
48
+ reject(new rest_1.HttpErrors.Unauthorized(challenge));
49
+ };
50
+ // add error state handler to strategy instance
51
+ strategy.error = function (error) {
52
+ reject(new rest_1.HttpErrors.InternalServerError(error));
53
+ };
54
+ // authenticate
55
+ strategy.authenticate(request);
56
+ });
57
+ }
58
+ }
59
+ exports.StrategyAdapter = StrategyAdapter;
60
+ //# sourceMappingURL=strategy-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy-adapter.js","sourceRoot":"","sources":["../src/strategy-adapter.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,iDAAiD;AACjD,+CAA+C;AAC/C,gEAAgE;;AAGhE,yCAAmD;AAGnD,MAAM,oBAAoB,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AAElE;;;;;;;GAOG;AACH,MAAa,eAAe;IAC1B;;;OAGG;IACH,YAA6B,QAAkB,EAAW,IAAY;QAAzC,aAAQ,GAAR,QAAQ,CAAU;QAAW,SAAI,GAAJ,IAAI,CAAQ;IAAG,CAAC;IAE1E;;;;;;OAMG;IACH,YAAY,CAAC,OAAgB;QAC3B,OAAO,IAAI,OAAO,CAAc,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAClD,0DAA0D;YAC1D,KAAK,MAAM,GAAG,IAAI,oBAAoB,EAAE;gBACtC,8DAA8D;gBAC7D,OAAe,CAAC,GAAG,CAAC,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;aACnD;YAED,iEAAiE;YACjE,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAE9C,iDAAiD;YACjD,QAAQ,CAAC,OAAO,GAAG,UAAS,IAAiB;gBAC3C,OAAO,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC;YAEF,iDAAiD;YACjD,QAAQ,CAAC,IAAI,GAAG,UAAS,SAAiB;gBACxC,MAAM,CAAC,IAAI,iBAAU,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC;YACjD,CAAC,CAAC;YAEF,+CAA+C;YAC/C,QAAQ,CAAC,KAAK,GAAG,UAAS,KAAa;gBACrC,MAAM,CAAC,IAAI,iBAAU,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC,CAAC;YACpD,CAAC,CAAC;YAEF,eAAe;YACf,QAAQ,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA5CD,0CA4CC"}
package/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ // Copyright IBM Corp. 2017,2018. All Rights Reserved.
2
+ // Node module: @loopback/authentication-passport
3
+ // This file is licensed under the MIT License.
4
+ // License text available at https://opensource.org/licenses/MIT
5
+
6
+ export * from './dist';
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // Copyright IBM Corp. 2017,2018. All Rights Reserved.
2
+ // Node module: @loopback/authentication-passport
3
+ // This file is licensed under the MIT License.
4
+ // License text available at https://opensource.org/licenses/MIT
5
+
6
+ module.exports = require('./dist');
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@loopback/authentication-passport",
3
+ "version": "0.1.0",
4
+ "description": "A package creating adapters between the passport module and @loopback/authentication",
5
+ "engines": {
6
+ "node": ">=8.9"
7
+ },
8
+ "scripts": {
9
+ "acceptance": "lb-mocha \"dist/__tests__/acceptance/**/*.js\"",
10
+ "build:apidocs": "lb-apidocs",
11
+ "build": "lb-tsc",
12
+ "clean": "lb-clean loopback-authentication-passport*.tgz dist tsconfig.build.tsbuildinfo package",
13
+ "pretest": "npm run build",
14
+ "test": "lb-mocha \"dist/__tests__/**/*.js\"",
15
+ "unit": "lb-mocha \"dist/__tests__/unit/**/*.js\"",
16
+ "verify": "npm pack && tar xf loopback-authentication-passport*.tgz && tree package && npm run clean"
17
+ },
18
+ "author": "IBM Corp.",
19
+ "copyright.owner": "IBM Corp.",
20
+ "license": "MIT",
21
+ "keywords": [
22
+ "Passport",
23
+ "Authentication",
24
+ "TypeScript"
25
+ ],
26
+ "files": [
27
+ "README.md",
28
+ "index.js",
29
+ "index.d.ts",
30
+ "dist",
31
+ "src",
32
+ "!*/__tests__"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/strongloop/loopback-next.git"
40
+ },
41
+ "dependencies": {
42
+ "@loopback/authentication": "^2.0.0",
43
+ "@loopback/context": "^1.16.0",
44
+ "@loopback/core": "^1.7.1",
45
+ "@loopback/metadata": "^1.1.5",
46
+ "@loopback/openapi-v3": "^1.4.0",
47
+ "@loopback/rest": "^1.11.2",
48
+ "passport": "^0.4.0",
49
+ "util-promisifyall": "^1.0.6"
50
+ },
51
+ "devDependencies": {
52
+ "@loopback/build": "^1.5.5",
53
+ "@loopback/openapi-spec-builder": "^1.1.11",
54
+ "@loopback/testlab": "^1.2.10",
55
+ "@loopback/eslint-config": "^1.1.1",
56
+ "@types/node": "^10.14.8",
57
+ "@types/passport": "^1.0.0",
58
+ "@types/passport-http": "^0.3.8",
59
+ "passport-http": "^0.3.0"
60
+ }
61
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './strategy-adapter';
@@ -0,0 +1,64 @@
1
+ // Copyright IBM Corp. 2017,2019. All Rights Reserved.
2
+ // Node module: @loopback/authentication-passport
3
+ // This file is licensed under the MIT License.
4
+ // License text available at https://opensource.org/licenses/MIT
5
+
6
+ import {AuthenticationStrategy, UserProfile} from '@loopback/authentication';
7
+ import {HttpErrors, Request} from '@loopback/rest';
8
+ import {Strategy} from 'passport';
9
+
10
+ const passportRequestMixin = require('passport/lib/http/request');
11
+
12
+ /**
13
+ * Adapter class to invoke passport-strategy
14
+ * 1. provides express dependencies to the passport strategies
15
+ * 2. provides shimming of requests for passport authentication
16
+ * 3. provides lifecycle similar to express to the passport-strategy
17
+ * 4. provides state methods to the strategy instance
18
+ * see: https://github.com/jaredhanson/passport
19
+ */
20
+ export class StrategyAdapter implements AuthenticationStrategy {
21
+ /**
22
+ * @param strategy instance of a class which implements a passport-strategy;
23
+ * @description http://passportjs.org/
24
+ */
25
+ constructor(private readonly strategy: Strategy, readonly name: string) {}
26
+
27
+ /**
28
+ * The function to invoke the contained passport strategy.
29
+ * 1. Create an instance of the strategy
30
+ * 2. add success and failure state handlers
31
+ * 3. authenticate using the strategy
32
+ * @param request The incoming request.
33
+ */
34
+ authenticate(request: Request): Promise<UserProfile> {
35
+ return new Promise<UserProfile>((resolve, reject) => {
36
+ // mix-in passport additions like req.logIn and req.logOut
37
+ for (const key in passportRequestMixin) {
38
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ (request as any)[key] = passportRequestMixin[key];
40
+ }
41
+
42
+ // create a prototype chain of an instance of a passport strategy
43
+ const strategy = Object.create(this.strategy);
44
+
45
+ // add success state handler to strategy instance
46
+ strategy.success = function(user: UserProfile) {
47
+ resolve(user);
48
+ };
49
+
50
+ // add failure state handler to strategy instance
51
+ strategy.fail = function(challenge: string) {
52
+ reject(new HttpErrors.Unauthorized(challenge));
53
+ };
54
+
55
+ // add error state handler to strategy instance
56
+ strategy.error = function(error: string) {
57
+ reject(new HttpErrors.InternalServerError(error));
58
+ };
59
+
60
+ // authenticate
61
+ strategy.authenticate(request);
62
+ });
63
+ }
64
+ }