Skip to content

Commit

Permalink
feature(serializer) Adding request and refactor
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
boenrobot committed Nov 28, 2019
1 parent cc1ae91 commit b869b01
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions lib/passport/passport.serializer.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
);
}
}

0 comments on commit b869b01

Please sign in to comment.