@teamhive/nestjs-common
Version:
Our common decorators, services, etc for NestJS projects
51 lines (50 loc) • 2.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PassportAuthGuard = void 0;
const passport_1 = require("@nestjs/passport");
const exceptions_1 = require("../exceptions");
const enums_1 = require("../enums");
function PassportAuthGuard(strategyToken) {
return class Guard extends (0, passport_1.AuthGuard)(strategyToken) {
constructor() {
super();
this.whitelistedErrors = new Set(Object.values(enums_1.PassportWhitelistedErrors));
}
handleRequest(error, user, passportError) {
if (error || !user) {
if (!(error instanceof exceptions_1.UnauthorizedException)) {
const actualError = error ||
(passportError instanceof Error) ? passportError : false ||
new Error('Passport Error');
if (!this.isWhitelisted(actualError)) {
this.handleErrors(actualError);
}
}
this.throwException();
}
return user;
}
isWhitelisted(error = {}) {
return Array.from(this.whitelistedErrors).some(whitelistedError => {
if (typeof error.message === 'string') {
return error.message.includes(whitelistedError);
}
return false;
});
}
handleErrors(error) {
console.warn('Override the handleErrors method in the child class of PassportAuthGuard to report errors!');
console.error(error);
}
throwException() {
throw new exceptions_1.UnauthorizedException();
}
addToWhitelist(messages) {
messages.forEach(message => this.whitelistedErrors.add(message));
}
removeFromWhitelist(messages) {
messages.forEach(message => this.whitelistedErrors.delete(String(message)));
}
};
}
exports.PassportAuthGuard = PassportAuthGuard;