nestjs-auth-kit
Version:
A modular and flexible authentication kit for NestJS with JWT, social login, OTP, and password reset.
142 lines • 6.23 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthService = void 0;
const common_1 = require("@nestjs/common");
const jwt_1 = require("@nestjs/jwt");
const otp_service_1 = require("./services/otp.service");
const forgot_password_service_1 = require("./services/forgot-password.service");
const auth_constants_1 = require("./constants/auth.constants");
const typeorm_1 = require("@nestjs/typeorm");
const user_entity_1 = require("./entities/user.entity");
const typeorm_2 = require("typeorm");
const bcrypt = __importStar(require("bcrypt"));
let AuthService = class AuthService {
constructor(jwtService, otpService, forgotPasswordService, authOptions, userRepository) {
this.jwtService = jwtService;
this.otpService = otpService;
this.forgotPasswordService = forgotPasswordService;
this.authOptions = authOptions;
this.userRepository = userRepository;
}
async register(registerDto) {
const { email, password, firstName, lastName } = registerDto;
if (!password) {
throw new common_1.BadRequestException('Password is required');
}
// Encrypt the password
const hashedPassword = await bcrypt.hash(password, 10);
// Create a new user
const user = this.userRepository.create({
email,
password: hashedPassword,
firstName,
lastName,
});
try {
const newUser = await this.userRepository.save(user);
// Destructure the newUser object to exclude the password
const { password, ...userWithoutPassword } = newUser;
return {
message: 'User created successfully',
user: userWithoutPassword,
};
}
catch (error) {
throw new common_1.InternalServerErrorException('Failed to create user');
}
}
async login(loginDto) {
const { email, password } = loginDto;
const user = await this.userRepository.findOne({ where: { email } });
if (!user) {
throw new common_1.UnauthorizedException('Account not found');
}
if (!password) {
throw new common_1.BadRequestException('Password is required');
}
// Validate the password
const isPasswordValid = await bcrypt.compare(password, user.password || '');
if (!isPasswordValid) {
throw new common_1.UnauthorizedException('Invalid credentials');
}
const payload = { email: user.email, sub: user.id };
return {
access_token: this.jwtService.sign(payload, {
secret: this.authOptions.jwtSecret,
expiresIn: this.authOptions.jwtExpiration,
}),
};
}
async validateGoogleUser(profile) {
// Validate or create user from Google profile
return { email: profile.emails[0].value, userId: profile.id };
}
async validateFacebookUser(profile) {
// Validate or create user from Facebook profile
return { email: profile.emails[0].value, userId: profile.id };
}
async sendOtp(email) {
return this.otpService.generateOtp(email);
}
async verifyOtp(email, otp) {
return this.otpService.verifyOtp(email, otp);
}
async resetPassword(email, otp, newPassword) {
return this.forgotPasswordService.resetPassword(email, otp, newPassword);
}
};
exports.AuthService = AuthService;
exports.AuthService = AuthService = __decorate([
(0, common_1.Injectable)(),
__param(3, (0, common_1.Inject)(auth_constants_1.AUTH_OPTIONS)),
__param(4, (0, typeorm_1.InjectRepository)(user_entity_1.User)),
__metadata("design:paramtypes", [jwt_1.JwtService,
otp_service_1.OtpService,
forgot_password_service_1.ForgotPasswordService, Object, typeorm_2.Repository])
], AuthService);
//# sourceMappingURL=auth.service.js.map