|
| 1 | +import * as jwt from 'jsonwebtoken'; |
| 2 | +import * as bcrypt from 'bcrypt'; |
| 3 | +import * as nodemailer from 'nodemailer'; |
| 4 | +import {default as config} from '../config'; |
| 5 | +import { Component, HttpException, HttpStatus } from '@nestjs/common'; |
| 6 | +import { JWTService } from './jwt.service'; |
| 7 | +import { Model } from 'mongoose'; |
| 8 | +import { InjectModel } from '@nestjs/mongoose'; |
| 9 | +import { User } from '../users/interfaces/user.interface'; |
| 10 | +import { UserDto } from '../users/dto/user.dto'; |
| 11 | +import { UserSchema } from '../users/schemas/user.schema'; |
| 12 | +import { EmailVerification } from './interfaces/emailverification.interface'; |
| 13 | +import { EmailVerificationSchema } from './schemas/emailverification.schema'; |
| 14 | +import { ForgottenPassword } from './interfaces/forgottenpassword.interface'; |
| 15 | +import { ForgottenPasswordSchema } from './schemas/forgottenpassword.schema'; |
| 16 | + |
| 17 | + |
| 18 | +const saltRounds = 10; |
| 19 | + |
| 20 | +@Component() |
| 21 | +export class AuthService { |
| 22 | + constructor(@InjectModel(UserSchema) private readonly userModel: Model<User>, |
| 23 | + @InjectModel(EmailVerificationSchema) private readonly emailVerificationModel: Model<EmailVerification>, |
| 24 | + @InjectModel(ForgottenPasswordSchema) private readonly forgottenPasswordModel: Model<ForgottenPassword>, |
| 25 | + private readonly jwtService: JWTService) {} |
| 26 | + |
| 27 | + |
| 28 | + async validateLogin(email, password) { |
| 29 | + var userFromDb = await this.userModel.findOne({ email: email}); |
| 30 | + if(!userFromDb) throw new HttpException('LOGIN.USER_NOT_FOUND', HttpStatus.NOT_FOUND); |
| 31 | + if(!userFromDb.auth.email.valid) throw new HttpException('LOGIN.EMAIL_NOT_VERIFIED', HttpStatus.FORBIDDEN); |
| 32 | + |
| 33 | + var isValidPass = await bcrypt.compare(password, userFromDb.password); |
| 34 | + |
| 35 | + if(isValidPass){ |
| 36 | + var accessToken = await this.jwtService.createToken(email); |
| 37 | + return { token: accessToken, user: new UserDto(userFromDb)} |
| 38 | + } else { |
| 39 | + throw new HttpException('LOGIN.PASSWORD_INCORRECT', HttpStatus.UNAUTHORIZED); |
| 40 | + } |
| 41 | + |
| 42 | + } |
| 43 | + |
| 44 | + async createEmailToken(email: string): Promise<boolean> { |
| 45 | + var emailVerificationModel = await this.emailVerificationModel.findOneAndUpdate( |
| 46 | + {email: email}, |
| 47 | + { |
| 48 | + email: email, |
| 49 | + emailToken: Math.floor(Math.random() * (900000000)) + 100000000, //Generate 9 digits number |
| 50 | + timestamp: new Date() |
| 51 | + }, |
| 52 | + {upsert: true} |
| 53 | + ); |
| 54 | + if(emailVerificationModel){ |
| 55 | + return true; |
| 56 | + } else { |
| 57 | + throw new HttpException('LOGIN.ERROR.GENERIC_ERROR', HttpStatus.INTERNAL_SERVER_ERROR); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + async createForgottenPasswordToken(email: string): Promise<ForgottenPassword> { |
| 62 | + var forgottenPasswordModel = await this.forgottenPasswordModel.findOneAndUpdate( |
| 63 | + {email: email}, |
| 64 | + { |
| 65 | + email: email, |
| 66 | + newPasswordToken: Math.floor(Math.random() * (900000000)) + 100000000, //Generate 9 digits number, |
| 67 | + timestamp: new Date() |
| 68 | + }, |
| 69 | + {upsert: true} |
| 70 | + ); |
| 71 | + if(forgottenPasswordModel){ |
| 72 | + return forgottenPasswordModel; |
| 73 | + } else { |
| 74 | + throw new HttpException('LOGIN.ERROR.GENERIC_ERROR', HttpStatus.INTERNAL_SERVER_ERROR); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + async verifyEmail(token: string): Promise<boolean> { |
| 79 | + var emailVerif = await this.emailVerificationModel.findOne({ emailToken: token}); |
| 80 | + if(emailVerif && emailVerif.email){ |
| 81 | + var userFromDb = await this.userModel.findOne({ email: emailVerif.email}); |
| 82 | + if (userFromDb) { |
| 83 | + userFromDb.auth.email.valid = true; |
| 84 | + var savedUser = await userFromDb.save(); |
| 85 | + await emailVerif.remove(); |
| 86 | + return !!savedUser; |
| 87 | + } |
| 88 | + } else { |
| 89 | + throw new HttpException('LOGIN.EMAIL_CODE_NOT_VALID', HttpStatus.FORBIDDEN); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + async getForgottenPasswordModel(newPasswordToken: string, newPassword: string): Promise<ForgottenPassword> { |
| 94 | + return await this.forgottenPasswordModel.findOne({newPasswordToken: newPasswordToken}); |
| 95 | + } |
| 96 | + |
| 97 | + async sendEmailVerification(email: string): Promise<boolean> { |
| 98 | + var model = await this.emailVerificationModel.findOne({ email: email}); |
| 99 | + |
| 100 | + if(model && model.emailToken){ |
| 101 | + let transporter = nodemailer.createTransport({ |
| 102 | + host: config.mail.host, |
| 103 | + port: config.mail.port, |
| 104 | + secure: config.mail.secure, |
| 105 | + auth: { |
| 106 | + user: config.mail.user, |
| 107 | + pass: config.mail.pass |
| 108 | + } |
| 109 | + }); |
| 110 | + |
| 111 | + let mailOptions = { |
| 112 | + from: '"NestJs Auth"', |
| 113 | + to: email, |
| 114 | + subject: 'Verify Email', |
| 115 | + text: 'Verify Email', |
| 116 | + html: 'Hi! <br><br> Thanks for your registration<br><br>'+ |
| 117 | + '<a href='+ config.host.url + ':' + config.host.port +'/auth/email/verify/'+ model.emailToken + '>Click here to activate your account</a>' // html body |
| 118 | + }; |
| 119 | + |
| 120 | + var sended = await new Promise<boolean>(async function(resolve, reject) { |
| 121 | + return await transporter.sendMail(mailOptions, async (error, info) => { |
| 122 | + if (error) { |
| 123 | + console.log('Message sent: %s', error); |
| 124 | + return reject(false); |
| 125 | + } |
| 126 | + console.log('Message sent: %s', info.messageId); |
| 127 | + resolve(true); |
| 128 | + }); |
| 129 | + }) |
| 130 | + |
| 131 | + return sended; |
| 132 | + } else { |
| 133 | + throw new HttpException('REGISTER.USER_NOT_REGISTERED', HttpStatus.FORBIDDEN); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + async sendEmailForgotPassword(email: string): Promise<boolean> { |
| 138 | + var userFromDb = await this.userModel.findOne({ email: email}); |
| 139 | + if(!userFromDb) throw new HttpException('LOGIN.USER_NOT_FOUND', HttpStatus.NOT_FOUND); |
| 140 | + |
| 141 | + var tokenModel = await this.createForgottenPasswordToken(email); |
| 142 | + |
| 143 | + if(tokenModel && tokenModel.newPasswordToken){ |
| 144 | + let transporter = nodemailer.createTransport({ |
| 145 | + host: config.mail.host, |
| 146 | + port: config.mail.port, |
| 147 | + secure: config.mail.secure, |
| 148 | + auth: { |
| 149 | + user: config.mail.user, |
| 150 | + pass: config.mail.pass |
| 151 | + } |
| 152 | + }); |
| 153 | + |
| 154 | + let mailOptions = { |
| 155 | + from: '"NestJs Auth"', |
| 156 | + to: email, |
| 157 | + subject: 'Forgot Password', |
| 158 | + text: 'Forgot Password', |
| 159 | + html: 'Hi! <br><br> If you requested to reset your password<br><br>'+ |
| 160 | + '<a href='+ config.host.url + ':' + config.host.port +'/auth/email/reset-password/'+ tokenModel.newPasswordToken + '>Click here</a>' // html body |
| 161 | + }; |
| 162 | + |
| 163 | + var sended = await new Promise<boolean>(async function(resolve, reject) { |
| 164 | + return await transporter.sendMail(mailOptions, async (error, info) => { |
| 165 | + if (error) { |
| 166 | + console.log('Message sent: %s', error); |
| 167 | + return reject(false); |
| 168 | + } |
| 169 | + console.log('Message sent: %s', info.messageId); |
| 170 | + resolve(true); |
| 171 | + }); |
| 172 | + }) |
| 173 | + |
| 174 | + return sended; |
| 175 | + } else { |
| 176 | + throw new HttpException('REGISTER.USER_NOT_REGISTERED', HttpStatus.FORBIDDEN); |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + |
| 181 | + |
| 182 | +} |
0 commit comments