@midwayjs/passport 3.0.0-beta.8 → 3.0.2

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/README.md CHANGED
@@ -87,7 +87,7 @@ import { Inject, Provide } from '@midwayjs/decorator';
87
87
  import { PassportMiddleware } from '@midwayjs/passport';
88
88
  import { Context } from '@midwayjs/express';
89
89
 
90
- @Provide('local') // 此处可以使用一个简短的identifier
90
+ @Provide()
91
91
  export class LocalPassportMiddleware extends PassportMiddleware(LocalStrategy) {
92
92
  // 设置 AuthenticateOptions
93
93
  getAuthenticateOptions(): Promise<passport.AuthenticateOptions> | passport.AuthenticateOptions {
@@ -107,7 +107,7 @@ import { Provide, Post, Inject, Controller } from '@midwayjs/decorator';
107
107
  @Controller('/')
108
108
  export class LocalController {
109
109
 
110
- @Post('/passport/local', { middleware: ['local'] })
110
+ @Post('/passport/local', { middleware: [LocalPassportMiddleware] })
111
111
  async localPassport() {
112
112
  console.log('local user: ', this.ctx.req.user);
113
113
  return this.ctx.req.user;
@@ -186,7 +186,7 @@ export class JwtController {
186
186
  @Inject()
187
187
  ctx: any;
188
188
 
189
- @Post('/passport/jwt', { middleware: ['jwtPassportMiddleware'] })
189
+ @Post('/passport/jwt', { middleware: [JwtPassportMiddleware] })
190
190
  async jwtPassport() {
191
191
  console.log('jwt user: ', this.ctx.req.user);
192
192
  return this.ctx.req.user;
@@ -259,10 +259,10 @@ export class AuthController {
259
259
  @Inject()
260
260
  ctx: any;
261
261
 
262
- @Get('/github', { middleware: ['githubPassportMiddleware'] })
262
+ @Get('/github', { middleware: [GithubPassportMiddleware] })
263
263
  async githubOAuth() {}
264
264
 
265
- @Get('/github/cb', { middleware: ['githubPassportMiddleware'] })
265
+ @Get('/github/cb', { middleware: [GithubPassportMiddleware] })
266
266
  async githubOAuthCallback() {
267
267
  return this.ctx.req.user;
268
268
  }
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.passport = void 0;
4
4
  exports.passport = {
5
- session: false,
5
+ session: true,
6
6
  userProperty: 'user',
7
7
  };
8
8
  //# sourceMappingURL=config.default.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.default.js","sourceRoot":"","sources":["../../src/config/config.default.ts"],"names":[],"mappings":";;;AAAa,QAAA,QAAQ,GAAG;IACtB,OAAO,EAAE,IAAI;IACb,YAAY,EAAE,MAAM;CACrB,CAAC","sourcesContent":["export const passport = {\n session: true,\n userProperty: 'user',\n};\n"]}
@@ -1,6 +1,7 @@
1
+ import { IMidwayContainer, MidwayApplicationManager, MidwayConfigService } from '@midwayjs/core';
1
2
  export declare class PassportConfiguration {
2
- app: any;
3
- passportConfig: any;
4
- onReady(): Promise<void>;
3
+ applicationManager: MidwayApplicationManager;
4
+ configService: MidwayConfigService;
5
+ onReady(container: IMidwayContainer): Promise<void>;
5
6
  }
6
7
  //# sourceMappingURL=configuration.d.ts.map
@@ -13,23 +13,29 @@ exports.PassportConfiguration = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const DefaultConfig = require("./config/config.default");
15
15
  const util_1 = require("./util");
16
+ const core_1 = require("@midwayjs/core");
16
17
  let PassportConfiguration = class PassportConfiguration {
17
- async onReady() {
18
+ async onReady(container) {
19
+ const passportConfig = this.configService.getConfiguration('passport');
18
20
  const passport = (0, util_1.getPassport)();
19
- this.app.useMiddleware(passport.initialize());
20
- if (this.passportConfig.session) {
21
- this.app.useMiddleware(passport.session());
22
- }
21
+ this.applicationManager
22
+ .getApplications(['express', 'koa', 'egg', 'faas'])
23
+ .forEach(app => {
24
+ app.useMiddleware(passport.initialize());
25
+ if (passportConfig.session) {
26
+ app.useMiddleware(passport.session());
27
+ }
28
+ });
23
29
  }
24
30
  };
25
31
  __decorate([
26
- (0, decorator_1.App)(),
27
- __metadata("design:type", Object)
28
- ], PassportConfiguration.prototype, "app", void 0);
32
+ (0, decorator_1.Inject)(),
33
+ __metadata("design:type", core_1.MidwayApplicationManager)
34
+ ], PassportConfiguration.prototype, "applicationManager", void 0);
29
35
  __decorate([
30
- (0, decorator_1.Config)('passport'),
31
- __metadata("design:type", Object)
32
- ], PassportConfiguration.prototype, "passportConfig", void 0);
36
+ (0, decorator_1.Inject)(),
37
+ __metadata("design:type", core_1.MidwayConfigService)
38
+ ], PassportConfiguration.prototype, "configService", void 0);
33
39
  PassportConfiguration = __decorate([
34
40
  (0, decorator_1.Configuration)({
35
41
  namespace: 'passport',
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configuration.js","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mDAA4D;AAC5D,yDAAyD;AACzD,iCAAqC;AACrC,yCAIwB;AAUxB,IAAa,qBAAqB,GAAlC,MAAa,qBAAqB;IAOhC,KAAK,CAAC,OAAO,CAAC,SAA2B;QACvC,MAAM,cAAc,GAAG,IAAI,CAAC,aAAa,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC;QACvE,MAAM,QAAQ,GAAG,IAAA,kBAAW,GAAE,CAAC;QAC/B,IAAI,CAAC,kBAAkB;aACpB,eAAe,CAAC,CAAC,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;aAClD,OAAO,CAAC,GAAG,CAAC,EAAE;YACb,GAAG,CAAC,aAAa,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;YACzC,IAAI,cAAc,CAAC,OAAO,EAAE;gBAC1B,GAAG,CAAC,aAAa,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;aACvC;QACH,CAAC,CAAC,CAAC;IACP,CAAC;CACF,CAAA;AAjBC;IADC,IAAA,kBAAM,GAAE;8BACW,+BAAwB;iEAAC;AAG7C;IADC,IAAA,kBAAM,GAAE;8BACM,0BAAmB;4DAAC;AALxB,qBAAqB;IARjC,IAAA,yBAAa,EAAC;QACb,SAAS,EAAE,UAAU;QACrB,aAAa,EAAE;YACb;gBACE,OAAO,EAAE,aAAa;aACvB;SACF;KACF,CAAC;GACW,qBAAqB,CAmBjC;AAnBY,sDAAqB","sourcesContent":["import { Inject, Configuration } from '@midwayjs/decorator';\nimport * as DefaultConfig from './config/config.default';\nimport { getPassport } from './util';\nimport {\n IMidwayContainer,\n MidwayApplicationManager,\n MidwayConfigService,\n} from '@midwayjs/core';\n\n@Configuration({\n namespace: 'passport',\n importConfigs: [\n {\n default: DefaultConfig,\n },\n ],\n})\nexport class PassportConfiguration {\n @Inject()\n applicationManager: MidwayApplicationManager;\n\n @Inject()\n configService: MidwayConfigService;\n\n async onReady(container: IMidwayContainer) {\n const passportConfig = this.configService.getConfiguration('passport');\n const passport = getPassport();\n this.applicationManager\n .getApplications(['express', 'koa', 'egg', 'faas'])\n .forEach(app => {\n app.useMiddleware(passport.initialize());\n if (passportConfig.session) {\n app.useMiddleware(passport.session());\n }\n });\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy.js","sourceRoot":"","sources":["../../src/decorator/strategy.ts"],"names":[],"mappings":";;;AAAA,mDAAgE;AAEhE,SAAgB,cAAc;IAC5B,OAAO,MAAM,CAAC,EAAE;QACd,IAAA,iBAAK,EAAC,qBAAS,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC;QACnC,IAAA,mBAAO,GAAE,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC;AALD,wCAKC","sourcesContent":["import { Provide, Scope, ScopeEnum } from '@midwayjs/decorator';\n\nexport function CustomStrategy(): ClassDecorator {\n return target => {\n Scope(ScopeEnum.Singleton)(target);\n Provide()(target);\n };\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,iDAAyE;AAAhE,8GAAA,qBAAqB,OAAiB;AAC/C,uDAAqC;AACrC,qDAAmC","sourcesContent":["export { PassportConfiguration as Configuration } from './configuration';\nexport * from './decorator/strategy';\nexport * from './service/passport';\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interface.js","sourceRoot":"","sources":["../src/interface.ts"],"names":[],"mappings":";;;AAUA,MAAsB,gBAAgB;CAGrC;AAHD,4CAGC;AAMD,MAAsB,0BAA0B;CAG/C;AAHD,gEAGC","sourcesContent":["import * as passport from 'passport';\n\nexport interface IPassportStrategy {\n validate(...args): any;\n getStrategyOptions(): any;\n serializeUser?(user: any, done: (err: any, id?: any) => void): void;\n deserializeUser?(id: any, done: (err: any, user?: any) => void): void;\n transformAuthInfo?(info: any, done: (err: any, info: any) => void): void;\n}\n\nexport abstract class AbstractStrategy implements IPassportStrategy {\n abstract validate(...args): any;\n abstract getStrategyOptions(): any;\n}\n\nexport interface IPassportMiddleware {\n authenticate?(options: passport.AuthenticateOptions, callback: Function);\n}\n\nexport abstract class AbstractPassportMiddleware implements IPassportMiddleware {\n abstract getAuthenticateOptions(): Promise<passport.AuthenticateOptions> | passport.AuthenticateOptions;\n authenticate?(options: passport.AuthenticateOptions, callback?: Function);\n}\n"]}
@@ -39,6 +39,10 @@ function initialize(passport) {
39
39
  const login = req.login;
40
40
  ctx.login = ctx.logIn = function (user, options) {
41
41
  return new Promise((resolve, reject) => {
42
+ // fix session manager missing
43
+ if (!req._sessionManager) {
44
+ req._sessionManager = passport._sm;
45
+ }
42
46
  login.call(req, user, options, err => {
43
47
  if (err)
44
48
  reject(err);
@@ -0,0 +1 @@
1
+ {"version":3,"file":"koa.js","sourceRoot":"","sources":["../../../src/proxy/framework/koa.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;GAEG;AACH,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAErC;;GAEG;AACH,MAAM,WAAW,GAAG,OAAO,CAAC,oCAAoC,CAAC,CAAC;AAClE,MAAM,aAAa,GAAG,OAAO,CAAC,sCAAsC,CAAC,CAAC;AACtE,MAAM,aAAa,GAAG,OAAO,CAAC,WAAW,CA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AAC,GAAG,CAAC,CAAC;;oBAChB,OAAO,CAAC,MAAM,CAAC,CAAC;YACvB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["'use strict';\n\n/**\n * Module dependencies.\n */\nconst passport = require('passport');\n\n/**\n * Passport's default/connect middleware.\n */\nconst _initialize = require('passport/lib/middleware/initialize');\nconst _authenticate = require('passport/lib/middleware/authenticate');\nconst createReqMock = require('./request').create;\n\n/**\n * Passport's initialization middleware for Koa.\n *\n * @return {GeneratorFunction}\n * @api private\n */\nfunction initialize(passport) {\n const middleware = promisify(_initialize(passport));\n return function passportInitialize(ctx, next) {\n // koa <-> connect compatibility:\n const userProperty = passport._userProperty || 'user';\n // check ctx.req has the userProperty\n // eslint-disable-next-line no-prototype-builtins\n if (!ctx.req.hasOwnProperty(userProperty)) {\n Object.defineProperty(ctx.req, userProperty, {\n enumerable: true,\n get: function () {\n return ctx.state[userProperty];\n },\n set: function (val) {\n ctx.state[userProperty] = val;\n },\n });\n }\n\n // create mock object for express' req object\n const req = createReqMock(ctx, userProperty);\n\n // add Promise-based login method\n const login = req.login;\n ctx.login = ctx.logIn = function (user, options) {\n return new Promise<void>((resolve, reject) => {\n // fix session manager missing\n if (!req._sessionManager) {\n req._sessionManager = passport._sm;\n }\n login.call(req, user, options, err => {\n if (err) reject(err);\n else resolve();\n });\n });\n };\n\n // add aliases for passport's request extensions to Koa's context\n ctx.logout = ctx.logOut = req.logout.bind(req);\n ctx.isAuthenticated = req.isAuthenticated.bind(req);\n ctx.isUnauthenticated = req.isUnauthenticated.bind(req);\n\n return middleware(req, ctx).then(() => {\n return next();\n });\n };\n}\n\n/**\n * Passport's authenticate middleware for Koa.\n *\n * @param {String|Array} name\n * @param {Object} options\n * @param {GeneratorFunction} callback\n * @return {GeneratorFunction}\n * @api private\n */\nfunction authenticate(passport, name, options, callback) {\n // normalize arguments\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n if (callback) {\n // When the callback is set, neither `next`, `res.redirect` or `res.end`\n // are called. That is, a workaround to catch the `callback` is required.\n // The `passportAuthenticate()` method below will therefore set\n // `callback.resolve` and `callback.reject`. Then, once the authentication\n // finishes, the modified callback calls the original one and afterwards\n // triggers either `callback.resolve` or `callback.reject` to inform\n // `passportAuthenticate()` that we are ready.\n const _callback = callback;\n callback = function (err, user, info, status) {\n try {\n Promise.resolve(_callback(err, user, info, status))\n .then(() => callback.resolve(false))\n .catch(err => callback.reject(err));\n } catch (err) {\n callback.reject(err);\n }\n };\n }\n\n const middleware = promisify(\n _authenticate(passport, name, options, callback)\n );\n\n return function passportAuthenticate(ctx, next) {\n // this functions wraps the connect middleware\n // to catch `next`, `res.redirect` and `res.end` calls\n const p = new Promise((resolve, reject) => {\n // mock the `req` object\n const req = createReqMock(\n ctx,\n options.assignProperty || passport._userProperty || 'user'\n );\n\n function setBodyAndResolve(content) {\n if (content) ctx.body = content;\n resolve(false);\n }\n\n // mock the `res` object\n const res = {\n redirect: function (url) {\n ctx.redirect(url);\n resolve(false);\n },\n set: ctx.set.bind(ctx),\n setHeader: ctx.set.bind(ctx),\n end: setBodyAndResolve,\n send: setBodyAndResolve,\n set statusCode(status) {\n ctx.status = status;\n },\n get statusCode() {\n return ctx.status;\n },\n };\n\n req.res = res;\n\n // update the custom callback above\n if (callback) {\n callback.resolve = resolve;\n callback.reject = reject;\n }\n\n // call the connect middleware\n middleware(req, res).then(resolve, reject);\n });\n\n return p.then(cont => {\n // cont equals `false` when `res.redirect` or `res.end` got called\n // in this case, call next to continue through Koa's middleware stack\n if (cont !== false) {\n return next();\n }\n });\n };\n}\n\n/**\n * Passport's authorize middleware for Koa.\n *\n * @param {String|Array} name\n * @param {Object} options\n * @param {GeneratorFunction} callback\n * @return {GeneratorFunction}\n * @api private\n */\nfunction authorize(passport, name, options, callback) {\n options = options || {};\n options.assignProperty = 'account';\n\n return authenticate(passport, name, options, callback);\n}\n\n/**\n * Framework support for Koa.\n *\n * This module provides support for using Passport with Koa. It exposes\n * middleware that conform to the `fn*(next)` signature and extends\n * Node's built-in HTTP request object with useful authentication-related\n * functions.\n *\n * @return {Object}\n * @api protected\n */\nmodule.exports = function () {\n return {\n initialize: initialize,\n authenticate: authenticate,\n authorize: authorize,\n };\n};\n\nfunction promisify(expressMiddleware) {\n return function (req, res) {\n return new Promise((resolve, reject) => {\n expressMiddleware(req, res, (err, result) => {\n if (err) reject(err);\n else resolve(result);\n });\n });\n };\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.js","sourceRoot":"","sources":["../../../src/proxy/framework/request.ts"],"names":[],"mappings":"AAAA,oBAAoB;AAEpB,6EAA6E;AAC7E,2BAA2B;AAC3B,2EAA2E;AAC3E,uEAAuE;AACvE,2EAA2E;AAC3E,2EAA2E;AAC3E,yEAAyE;AACzE,6EAA6E;AAC7E,4BAA4B;AAC5B,EAAE;AACF,gCAAgC;AAChC,uEAAuE;AACvE,4EAA4E;AAC5E,4BAA4B;AAC5B,gDAAgD;AAChD,qCAAqC;AACrC,iFAAiF;AACjF,QAAQ;AACR,QAAQ;AACR,IAAI;AACJ,EAAE;AACF,sEAAsE;AACtE,uDAAuD;AACvD,EAAE;AACF,8EAA8E;AAC9E,wBAAwB;AAExB,wCAAwC;AACxC,IAAI,IAAI,GAAG;IACT,WAAW;IACX,WAAW;IACX,UAAU;IAEV,uBAAuB;IACvB,aAAa;IACb,SAAS;IACT,UAAU;IACV,YAAY;IACZ,QAAQ;IACR,KAAK;IACL,YAAY;IACZ,QAAQ;IACR,YAAY;IACZ,UAAU;IAEV,gBAAgB;IAChB,SAAS;IACT,OAAO;IACP,IAAI;IAEJ,2EAA2E;IAC3E,OAAO;IACP,QAAQ;IACR,OAAO;IACP,KAAK;IACL,SAAS;IACT,SAAS;IACT,MAAM;IACN,OAAO;CACR,CAAC;AAEF,oBAAoB;AACpB,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAA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C,MAAM,GAAG,kBAAkB,CAAC,MAAM,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,kBAAkB,CAAC,MAAM,CAAC;IACvC,GAAG,CAAC,eAAe,GAAG,kBAAkB,CAAC,eAAe,CAAC;IACzD,GAAG,CAAC,iBAAiB,GAAG,kBAAkB,CAAC,iBAAiB,CAAC;IAE7D,OAAO,GAAG,CAAC;AACb,CAAC,CAAC","sourcesContent":["/* eslint-disable */\n\n// Koa and Express are fundamental different in how they deal with extensions\n// to the incoming request.\n// Express pollutes Node's IncomingRequest directly, while Koa keeps Node's\n// IncomingRequest untouched and adds is own high-level request object.\n// These both approaches are not directly compatible with each other, since\n// properties/methods found in Express' `req` object are now spread between\n// Koa's context, Koa's request object and the original incoming request.\n// This makes moking the Express `req` object an ugly task. With ES6 we could\n// simply use a Proxy, e.g.:\n//\n// function createReqMock(ctx) {\n// // Use a proxy that forwards `req` reads to either `ctx.passport`,\n// // Node's request, Koa's request or Koa's context. Writes are persistet\n// // into `ctx.passport`.\n// return Proxy.create(handler(ctx.passport, {\n// get: function(receiver, key) {\n// return ctx.passport[key] || ctx.req[key] || ctx.request[key] || ctx[key]\n// }\n// }))\n// }\n//\n// However, the current Proxy implementation does not allow debugging.\n// See: https://github.com/rkusa/koa-passport/issues/17\n//\n// Until this is fixed, koa-passport tries to properly delegate every possible\n// used property/method.\n\n// Property/Method names to be delegated\nlet keys = [\n // passport\n '_passport',\n 'authInfo',\n\n // http.IncomingMessage\n 'httpVersion',\n 'headers',\n 'trailers',\n 'setTimeout',\n 'method',\n 'url',\n 'statusCode',\n 'socket',\n 'connection',\n 'protocol',\n\n // Koa's context\n 'cookies',\n 'throw',\n 'ip',\n\n // Others. Are not supported directly - require proper plugins/middlewares.\n 'param',\n 'params',\n 'route',\n 'xhr',\n 'baseUrl',\n 'session',\n 'body',\n 'flash',\n];\n\n// remove duplicates\nkeys = keys.filter((key, i, self) => {\n return self.indexOf(key) === i;\n});\n\n// create a delegate for each key\nconst properties = {\n // mock express' .get('trust proxy')\n app: {\n // getter returning a mock for `req.app` containing\n // the `.get()` method\n get: function () {\n const ctx = this.ctx;\n return {\n get: function (key) {\n if (key === 'trust proxy') {\n return ctx.app.proxy;\n }\n\n return undefined;\n },\n };\n },\n },\n};\n\nkeys.forEach(key => {\n properties[key] = {\n get: function () {\n const obj = getObject(this.ctx, key);\n if (!obj) return undefined;\n\n // if its a function, call with the proper context\n if (typeof obj[key] === 'function') {\n return function () {\n return obj[key].apply(obj, arguments);\n };\n }\n\n // otherwise, simply return it\n return obj[key];\n },\n set: function (value) {\n const obj = getObject(this.ctx, key) || this.ctx.state;\n obj[key] = value;\n },\n };\n});\n\n// test where the key is available, either in `ctx.state`, Node's request,\n// Koa's request or Koa's context\nfunction getObject(ctx, key) {\n if (ctx.state && key in ctx.state) {\n return ctx.state;\n }\n\n if (key in ctx.request) {\n return ctx.request;\n }\n\n if (key in ctx.req) {\n return ctx.req;\n }\n\n if (key in ctx) {\n return ctx;\n }\n\n return undefined;\n}\n\nconst IncomingMessageExt = require('passport/lib/http/request');\n\nexports.create = function (ctx, userProperty) {\n const req = Object.create(ctx.request, properties);\n\n Object.defineProperty(req, userProperty, {\n enumerable: true,\n get: function () {\n return ctx.state[userProperty];\n },\n set: function (val) {\n ctx.state[userProperty] = val;\n },\n });\n\n Object.defineProperty(req, 'ctx', {\n enumerable: true,\n get: function () {\n return ctx;\n },\n });\n\n // add passport http.IncomingMessage extensions\n req.login = IncomingMessageExt.logIn;\n req.logIn = IncomingMessageExt.logIn;\n req.logout = IncomingMessageExt.logOut;\n req.logOut = IncomingMessageExt.logOut;\n req.isAuthenticated = IncomingMessageExt.isAuthenticated;\n req.isUnauthenticated = IncomingMessageExt.isUnauthenticated;\n\n return req;\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/proxy/index.ts"],"names":[],"mappings":";;;AAAA,wCAAwC;AACxC,MAAM,OAAO,GAAG,OAAO,CAAC,gCAAgC,CAAC,CAAC;AAC1D,OAAO,CAAC,iBAAiB,GAAG,cAAa,CAAC,CAAC;AAE3C,0CAA0C;AAC1C,MAAM,cAAc,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAC3C,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC;AAC9C,MAAM,SAAS,GAAG,OAAO,CAAC,iBAAiB,CAAC,EAAE,CAAC;AAE/C,cAAc,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;AAEpC,MAAa,WAAY,SAAQ,QAAQ;IACvC;QACE,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC5B,CAAC;CACF;AALD,kCAKC;AAED,4BAA4B;AACf,QAAA,QAAQ,GAAG,cAAc,CAAC","sourcesContent":["// prevent passport from monkey patching\nconst connect = require('passport/lib/framework/connect');\nconnect.__monkeypatchNode = function () {};\n\n// load passport and add the koa framework\nconst originPassport = require('passport');\nconst Passport = require('passport').Passport;\nconst framework = require('./framework/koa')();\n\noriginPassport.framework(framework);\n\nexport class KoaPassport extends Passport {\n constructor() {\n super();\n this.framework(framework);\n }\n}\n\n// Export default singleton.\nexport const passport = originPassport;\n"]}
@@ -13,6 +13,7 @@ exports.PassportMiddleware = exports.PassportStrategy = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const util_1 = require("../util");
15
15
  const interface_1 = require("../interface");
16
+ const core_1 = require("@midwayjs/core");
16
17
  function PassportStrategy(Strategy, name) {
17
18
  class InnerStrategyAbstractClass extends interface_1.AbstractStrategy {
18
19
  async init() {
@@ -132,7 +133,7 @@ function PassportMiddleware(strategy) {
132
133
  return;
133
134
  }
134
135
  else {
135
- res.status(401);
136
+ throw new core_1.httpError.UnauthorizedError();
136
137
  }
137
138
  }
138
139
  next();
@@ -195,7 +196,7 @@ function PassportMiddleware(strategy) {
195
196
  return;
196
197
  }
197
198
  else {
198
- ctx.status = 401;
199
+ throw new core_1.httpError.UnauthorizedError();
199
200
  }
200
201
  }
201
202
  await next();
@@ -207,6 +208,9 @@ function PassportMiddleware(strategy) {
207
208
  }.bind(this);
208
209
  }
209
210
  }
211
+ static getName() {
212
+ return 'passport';
213
+ }
210
214
  }
211
215
  __decorate([
212
216
  (0, decorator_1.Config)('passport'),
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passport.js","sourceRoot":"","sources":["../../src/service/passport.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,mDAAwD;AACxD,kCAAqD;AACrD,4CAA4E;AAC5E,yCAA2C;AAE3C,SAAgB,gBAAgB,CAC9B,QAA4C,EAC5C,IAAa;IAEb,MAAe,0BAA2B,SAAQ,4BAAgB;QAIhE,KAAK,CAAC,IAAI;YACR,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,MAAa,EAAE,EAAE;gBACpC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;gBACvC,IAAI;oBACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC;oBAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;wBACzB,IAAI,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,CAAC;qBACvB;yBAAM;wBACL,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;qBACpB;iBACF;gBAAC,OAAO,GAAG,EAAE;oBACZ,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;iBACjB;YACH,CAAC,CAAC;YAEF,IAAI,CAAC,QAAQ,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,EAAE,CAAC,CAAC;YAE5D,MAAM,QAAQ,GAAG,IAAA,kBAAW,GAA6B,CAAC;YAC1D,IAAI,IAAI,EAAE;gBACR,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,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AAC,IAAI,EAAE,OAAO,CAAC,CAAC;iCAChC;gCACD,IAAI,OAAO,CAAC,eAAe,EAAE;oCAC3B,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;oCACtC,OAAO;iCACR;6BACF;iCAAM;gCACL,IAAI,OAAO,CAAC,eAAe,EAAE;oCAC3B,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;oCACtC,OAAO;iCACR;qCAAM;oCACL,MAAM,IAAI,gBAAS,CAAC,iBAAiB,EAAE,CAAC;iCACzC;6BACF;4BACD,MAAM,IAAI,EAAE,CAAC;yBACd;wBAAC,OAAO,GAAG,EAAE;4BACZ,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;yBAChB;qBACF;gBACH,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACd;QACH,CAAC;QAED,MAAM,CAAC,OAAO;YACZ,OAAO,UAAU,CAAC;QACpB,CAAC;KACF;IAtKC;QADC,IAAA,kBAAM,EAAC,UAAU,CAAC;;mEACJ;IAGf;QADC,IAAA,eAAG,GAAE;;wDACF;IAoKN,OAAO,uBAA8B,CAAC;AACxC,CAAC;AA7KD,gDA6KC","sourcesContent":["import * as passport from 'passport';\nimport { App, Config, Init } from '@midwayjs/decorator';\nimport { getPassport, isExpressMode } from '../util';\nimport { AbstractPassportMiddleware, AbstractStrategy } from '../interface';\nimport { httpError } from '@midwayjs/core';\n\nexport function PassportStrategy(\n Strategy: new (...args) => passport.Strategy,\n name?: string\n): new (...args) => AbstractStrategy {\n abstract class InnerStrategyAbstractClass extends AbstractStrategy {\n private strategy;\n\n @Init()\n async init() {\n const cb = async (...params: any[]) => {\n const done = params[params.length - 1];\n try {\n const result = await this.validate(...params);\n if (Array.isArray(result)) {\n done(null, ...result);\n } else {\n done(null, result);\n }\n } catch (err) {\n done(err, null);\n }\n };\n\n this.strategy = new Strategy(this.getStrategyOptions(), cb);\n\n const passport = getPassport() as passport.PassportStatic;\n if (name) {\n passport.use(name, this.strategy);\n } else {\n passport.use(this.strategy);\n }\n if (this['serializeUser']) {\n passport.serializeUser(this['serializeUser']);\n }\n\n if (this['deserializeUser']) {\n passport.deserializeUser(this['deserializeUser']);\n }\n\n if (this['transformAuthInfo']) {\n passport.transformAuthInfo(this['transformAuthInfo']);\n }\n }\n\n getStrategy() {\n return this.strategy;\n }\n }\n return InnerStrategyAbstractClass as any;\n}\n\nexport type StrategyClass = new (...args) => AbstractStrategy;\n\nexport function PassportMiddleware(\n strategy: StrategyClass | StrategyClass[]\n): new (...args) => AbstractPassportMiddleware {\n abstract class InnerPassportMiddleware extends AbstractPassportMiddleware {\n @Config('passport')\n passportConfig;\n\n @App()\n app;\n\n resolve() {\n if (isExpressMode()) {\n return async function passportMiddleware(req, res, next) {\n return this.authenticate(await this.getAuthenticateOptions())(\n req,\n res,\n next\n );\n }.bind(this);\n } else {\n return async function passportMiddleware(ctx, next) {\n return this.authenticate(await this.getAuthenticateOptions())(\n ctx,\n next\n );\n }.bind(this);\n }\n }\n\n getAuthenticateOptions():\n | Promise<passport.AuthenticateOptions>\n | passport.AuthenticateOptions {\n return undefined;\n }\n\n authenticate(options: passport.AuthenticateOptions): any {\n if (!Array.isArray(strategy)) {\n strategy = [strategy];\n }\n\n if (isExpressMode()) {\n return async (req, res, next) => {\n // merge options with default options\n const authOptions = {\n ...this.passportConfig,\n ...options,\n };\n\n if (authOptions.session && req.session[authOptions.userProperty]) {\n req[authOptions.userProperty] =\n req.session[authOptions.userProperty];\n }\n // ignore user has exists\n if (req[authOptions.userProperty]) {\n next();\n } else {\n const passport = getPassport() as passport.PassportStatic;\n const strategyList = [];\n for (const strategySingle of strategy as StrategyClass[]) {\n // got strategy\n const strategyInstance = await this.app\n .getApplicationContext()\n .getAsync(strategySingle);\n strategyList.push(strategyInstance.getStrategy());\n }\n\n const user = await new Promise<any>((resolve, reject) => {\n // authenticate\n passport.authenticate(\n strategyList,\n authOptions,\n (err, user, info, status) => {\n if (err) {\n reject(err);\n } else {\n resolve(user);\n }\n }\n )(req, res, err => (err ? reject(err) : resolve(0)));\n });\n if (user) {\n req[authOptions.userProperty] = user;\n if (authOptions.session) {\n req.logIn(user, options, next);\n return;\n }\n } else {\n if (options.failureRedirect) {\n res.redirect(options.failureRedirect);\n return;\n } else {\n throw new httpError.UnauthorizedError();\n }\n }\n next();\n }\n };\n } else {\n return async function bbb(ctx, next) {\n // merge options with default options\n const authOptions = {\n ...this.passportConfig,\n ...options,\n };\n\n if (\n authOptions.session &&\n ctx.session.passport &&\n ctx.session.passport[authOptions.userProperty]\n ) {\n ctx.state[authOptions.userProperty] =\n ctx.session.passport[authOptions.userProperty];\n }\n // ignore user has exists\n if (ctx.state[authOptions.userProperty]) {\n await next();\n } else {\n const passport = getPassport() as passport.PassportStatic;\n const strategyList = [];\n for (const strategySingle of strategy as StrategyClass[]) {\n // got strategy\n const strategyInstance = await this.app\n .getApplicationContext()\n .getAsync(strategySingle);\n strategyList.push(strategyInstance.getStrategy());\n }\n try {\n const user = await new Promise<any>((resolve, reject) => {\n // authenticate\n passport.authenticate(\n strategyList,\n authOptions,\n (err, user, info, status) => {\n if (err) {\n reject(err);\n } else {\n resolve(user);\n }\n }\n )(ctx, err => (err ? reject(err) : resolve(0)));\n });\n if (user) {\n ctx.state[authOptions.userProperty] = user;\n if (authOptions.session) {\n // save to ctx.session.passport\n await ctx.login(user, options);\n }\n if (options.successRedirect) {\n ctx.redirect(options.successRedirect);\n return;\n }\n } else {\n if (options.failureRedirect) {\n ctx.redirect(options.failureRedirect);\n return;\n } else {\n throw new httpError.UnauthorizedError();\n }\n }\n await next();\n } catch (err) {\n ctx.throw(err);\n }\n }\n }.bind(this);\n }\n }\n\n static getName() {\n return 'passport';\n }\n }\n return InnerPassportMiddleware as any;\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;AAAA,yCAA6C;AAE7C,SAAgB,WAAW;IACzB,OAAO,aAAa,EAAE;QACpB,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC;QACrB,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,QAAQ,CAAC;AACxC,CAAC;AAJD,kCAIC;AAED,SAAgB,aAAa;;IAC3B,OAAO,CAAC,CAAC,CACP,MAAA,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,KAAK,SAAS,mCACjD,IAAA,kBAAW,EAAC,mBAAmB,CAAC,CACjC,CAAC;AACJ,CAAC;AALD,sCAKC","sourcesContent":["import { safeRequire } from '@midwayjs/core';\n\nexport function getPassport() {\n return isExpressMode()\n ? require('passport')\n : require('./proxy/index').passport;\n}\n\nexport function isExpressMode(): boolean {\n return !!(\n process.env['MIDWAY_PASSPORT_MODE'] === 'express' ??\n safeRequire('@midwayjs/express')\n );\n}\n"]}
package/index.d.ts CHANGED
@@ -7,3 +7,51 @@ declare module '@midwayjs/core/dist/interface' {
7
7
  passport?: passport.AuthenticateOptions;
8
8
  }
9
9
  }
10
+
11
+ declare module '@midwayjs/koa/dist/interface' {
12
+ interface Context {
13
+ state: {
14
+ user?: any;
15
+ };
16
+ isAuthenticated(): boolean;
17
+ isUnauthenticated(): boolean;
18
+ login(): Promise<void>;
19
+ logout(): void;
20
+ }
21
+ }
22
+
23
+ declare module '@midwayjs/web/dist/interface' {
24
+ interface Context {
25
+ state: {
26
+ user?: any;
27
+ };
28
+ isAuthenticated(): boolean;
29
+ isUnauthenticated(): boolean;
30
+ login(): Promise<void>;
31
+ logout(): void;
32
+ }
33
+ }
34
+
35
+ declare module '@midwayjs/faas/dist/interface' {
36
+ interface Context {
37
+ state: {
38
+ user?: any;
39
+ };
40
+ isAuthenticated(): boolean;
41
+ isUnauthenticated(): boolean;
42
+ login(): Promise<void>;
43
+ logout(): void;
44
+ }
45
+ }
46
+
47
+ declare module '@midwayjs/express/dist/interface' {
48
+ interface Context {
49
+ user?: any;
50
+ // These declarations are merged into express's Request type
51
+ login(user: any, done: (err: any) => void): void;
52
+ login(user: any, options: any, done: (err: any) => void): void;
53
+ logout(): void;
54
+ isAuthenticated(): boolean;
55
+ isUnauthenticated(): boolean;
56
+ }
57
+ }
package/package.json CHANGED
@@ -1,18 +1,19 @@
1
1
  {
2
2
  "name": "@midwayjs/passport",
3
3
  "description": "midway passport component",
4
- "version": "3.0.0-beta.8",
4
+ "version": "3.0.2",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
7
7
  "files": [
8
8
  "dist/**/*.js",
9
9
  "dist/**/*.d.ts",
10
- "index.d.ts"
10
+ "index.d.ts",
11
+ "dist/**/*.js.map"
11
12
  ],
12
13
  "scripts": {
13
14
  "build": "tsc",
14
15
  "test": "node --require=ts-node/register ../../node_modules/jest/bin/jest.js",
15
- "cov": "node --require=ts-node/register ../../node_modules/.bin/jest --coverage --forceExit"
16
+ "cov": "node --require=ts-node/register ../../node_modules/.bin/jest --runInBand --coverage --forceExit"
16
17
  },
17
18
  "keywords": [
18
19
  "midway",
@@ -22,22 +23,22 @@
22
23
  "author": "Nawbc",
23
24
  "license": "MIT",
24
25
  "devDependencies": {
25
- "@midwayjs/core": "^3.0.0-beta.8",
26
- "@midwayjs/decorator": "^3.0.0-beta.8",
27
- "@midwayjs/express": "^3.0.0-beta.8",
28
- "@midwayjs/jwt": "^3.0.0-beta.8",
29
- "@midwayjs/koa": "^3.0.0-beta.8",
30
- "@midwayjs/mock": "^3.0.0-beta.8",
31
- "@midwayjs/web": "^3.0.0-beta.8",
32
- "@types/passport": "^1.0.7",
33
- "@types/passport-local": "^1.0.34",
34
- "express-session": "^1.17.2",
35
- "passport": "^0.5.0",
36
- "passport-jwt": "^4.0.0",
37
- "passport-local": "^1.0.0"
26
+ "@midwayjs/core": "^3.0.2",
27
+ "@midwayjs/decorator": "^3.0.2",
28
+ "@midwayjs/express": "^3.0.2",
29
+ "@midwayjs/jwt": "^3.0.2",
30
+ "@midwayjs/koa": "^3.0.2",
31
+ "@midwayjs/mock": "^3.0.2",
32
+ "@midwayjs/web": "^3.0.2",
33
+ "@types/passport": "1.0.7",
34
+ "@types/passport-local": "1.0.34",
35
+ "express-session": "1.17.2",
36
+ "passport": "0.5.2",
37
+ "passport-jwt": "4.0.0",
38
+ "passport-local": "1.0.0"
38
39
  },
39
40
  "peerDependencies": {
40
41
  "passport": "^0.5.0"
41
42
  },
42
- "gitHead": "bfafbdf8798f48d4daac5dd88ad53c6b2f33c110"
43
+ "gitHead": "ca77247d229978a736e79bb208579c014ed226fc"
43
44
  }
package/CHANGELOG.md DELETED
@@ -1,18 +0,0 @@
1
- # Change Log
2
-
3
- All notable changes to this project will be documented in this file.
4
- See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
-
6
- # [3.0.0-beta.8](https://github.com/midwayjs/midway/compare/v3.0.0-beta.7...v3.0.0-beta.8) (2021-12-08)
7
-
8
-
9
- ### Bug Fixes
10
-
11
- * express routing middleware takes effect at the controller level ([#1364](https://github.com/midwayjs/midway/issues/1364)) ([b9272e0](https://github.com/midwayjs/midway/commit/b9272e0971003443304b0c53815be31a0061b4bd))
12
- * passport missing proxy file ([#1405](https://github.com/midwayjs/midway/issues/1405)) ([5c9bdae](https://github.com/midwayjs/midway/commit/5c9bdae8323b41ead72c3d3f867aa11150bb3e78))
13
-
14
-
15
- ### Features
16
-
17
- * passport add presetProperty ([#1358](https://github.com/midwayjs/midway/issues/1358)) ([4db8eda](https://github.com/midwayjs/midway/commit/4db8eda592c0486898edabcacbc9a69eb2d87004))
18
- * support passport and jwt ([#1343](https://github.com/midwayjs/midway/issues/1343)) ([f26af4f](https://github.com/midwayjs/midway/commit/f26af4f3e16507d6f3ffe0467f8f5be69e6306d7))