From 869b03614818d87bd550b5c86270317463d8b954 Mon Sep 17 00:00:00 2001 From: Vasil Rangelov Date: Wed, 6 Nov 2019 15:31:40 +0200 Subject: [PATCH] feature(serializer) Adding request and refactor Passport has an undocumented feature, where the request can be passed to the serializeUser/deserializeUser callback as the first argument, and whether it is or not is determined by the arguments in the function (if it accepts 3, the first is the request). This feature is used to get and pass the request to the callback. The done callback is removed in favor of a promise being expected. A rejected promise (or an exception thrown within the handler) will be passed to passport as an error. Also added types for everything as generics, defaulting to the type safe "unknown" instead of "any", allowing extenders to enforce type safety on this lower level, instead of just theirs. --- lib/passport/passport.serializer.ts | 45 +++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/lib/passport/passport.serializer.ts b/lib/passport/passport.serializer.ts index 634e2d11..7d1ab997 100644 --- a/lib/passport/passport.serializer.ts +++ b/lib/passport/passport.serializer.ts @@ -1,13 +1,46 @@ +import { IncomingMessage } from 'http'; import * as passport from 'passport'; -export abstract class PassportSerializer { - abstract serializeUser(user: any, done: Function); - abstract deserializeUser(payload: any, done: Function); +export abstract class PassportSerializer< + UserType extends unknown = unknown, + PayloadType extends unknown = unknown, + RequestType extends IncomingMessage = IncomingMessage +> { + abstract serializeUser( + user: UserType, + req?: RequestType + ): Promise | PayloadType; + abstract deserializeUser( + payload: PayloadType, + req?: RequestType + ): Promise | UserType; constructor() { - passport.serializeUser((user, done) => this.serializeUser(user, done)); - passport.deserializeUser((payload, done) => - this.deserializeUser(payload, done) + passport.serializeUser( + async ( + req: RequestType, + user: UserType, + done: (err: unknown, payload?: PayloadType) => unknown + ) => { + try { + done(null, await this.serializeUser(user, req)); + } catch (err) { + done(err); + } + } + ); + passport.deserializeUser( + async ( + req: RequestType, + payload: PayloadType, + done: (err: unknown, user?: UserType) => unknown + ) => { + try { + done(null, await this.deserializeUser(payload, req)); + } catch (err) { + done(err); + } + } ); } }