All files / auth auth.service.ts

93.82% Statements 76/81
90.9% Branches 10/11
100% Functions 11/11
94.87% Lines 74/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 2932x                   2x 2x 2x       2x 2x           2x 2x                   2x 2x   2x 2x 2x 2x 2x               8x   7x                 7x 7x   1x         7x               15x                   15x         15x                     15x               5x 5x               5x 2x 2x   3x             12x 12x                   12x                               12x                       4x   4x 1x 1x     3x 1x 1x     2x 2x 2x           2x 2x             10x   10x 1x       9x 1x 1x     8x 8x   2x 2x                   5x     5x     4x 4x   4x 2x                 2x       2x 2x     4x                     4x             2x   2x 1x     1x       1x 1x                          
import {
  ConflictException,
  HttpException,
  Injectable,
  InternalServerErrorException,
  Logger,
  NotFoundException,
  ServiceUnavailableException,
  UnauthorizedException,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { compare } from 'bcrypt'
import { ObjectId } from 'mongoose'
import { MailData } from '../db/entities/mail-event.entity'
import { User } from '../db/entities/users.entity'
import { UserDBService } from '../db/services/user.service'
import {
  MailTemplateContent,
  MailTemplates,
  PasswordResetMailData,
  VerifyMailData,
} from '../mail/interfaces/mail.interface'
import { MailScheduleService } from '../mail/services/scheduler.service'
import { StripeService } from '../payments/services/stripe.service'
import { JWTPayload } from '../shared/interfaces/jwt-payload.interface'
import { LoginDTO } from './dtos/login.dto'
import { RegisterDTO } from './dtos/register.dto'
import { PasswordResetJWTPayload } from './interfaces/pw-reset-jwt-payload.interface'
import { RefreshJWTPayload } from './interfaces/refresh-jwt-payload.interface'
import { VerifyJWTPayload } from './interfaces/verify-jwt-payload.interface'
import { TokenResponse } from './responses/token.response'
 
@Injectable()
export class AuthService {
  private readonly logger = new Logger(AuthService.name)
  constructor(
    private readonly userService: UserDBService,
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
    private readonly mailService: MailScheduleService,
    private readonly stripeService: StripeService,
  ) {}
 
  /**
   * @description Initiate user registration
   */
  async register(body: RegisterDTO): Promise<TokenResponse> {
    // hash password
    const newUser = await this.userService.insertUser(body)
    /* istanbul ignore if */
    if (!newUser) {
      this.logger.error(
        'An unexpected error occured. Creation of user did not fail but also did not return user',
      )
      // All conflict related exceptions are thrown within the userService
      // This is only a safeguard that should never be reached (in theory)
      throw new InternalServerErrorException()
    }
 
    try {
      await this.sendEmailVerify(newUser)
    } catch (error) {
      this.logger.warn(
        `Sending verify mail failed due to an error. User registration continued anyway ${error}`,
      )
    }
 
    return await this.getAuthPayload(newUser)
  }
 
  /**
   *
   * @description Send verification email for user
   */
  private async sendEmailVerify(user: User) {
    const verifyToken = this.jwtService.sign(
      {
        email: user.email,
      } as VerifyJWTPayload,
      {
        secret: this.configService.get('JWT_VERIFY_SECRET'),
        expiresIn: this.configService.get('JWT_VERIFY_EXPIRE_TIME'),
      },
    )
 
    const mailContent: VerifyMailData = {
      verifyUrl: `${this.configService.get(
        'FRONTEND_DOMAIN',
      )}/account/verify-email?token=${verifyToken}`,
    }
    const mail: MailData = {
      recipient: {
        recipient: user.email,
      },
      content: {
        subject: 'Email verifizieren',
        templateContent: mailContent,
        contentTemplate: MailTemplates.VERIFY,
      },
    }
 
    await this.mailService.scheduleMailNow(mail)
  }
 
  /**
   * @description Initiate user login
   */
  async login(body: LoginDTO): Promise<TokenResponse> {
    let user: User
    try {
      user = await this.userService.findOneByEmail(body.email)
    } catch (error) /* istanbul ignore next */ {
      this.logger.error(error)
      if (error instanceof HttpException) {
        throw error
      }
      throw new InternalServerErrorException()
    }
    if (!user || !(await compare(body.password, user.password))) {
      this.logger.warn(`Attempted but invalid login for user ${body.email}`)
      throw new UnauthorizedException()
    }
    return await this.getAuthPayload(user)
  }
 
  /**
   * @description Generate tokens
   */
  async getAuthPayload(user: User): Promise<TokenResponse> {
    await this.userService.setLoginTimestamp(user._id)
    return {
      access_token: await this.generateJWTToken(user),
      refresh_token: await this.generateRefreshToken(user),
    }
  }
 
  /**
   * @description Generate refresh token for passed user
   */
  private async generateRefreshToken(user: User): Promise<string> {
    return await this.jwtService.sign(
      {
        id: user._id,
        email: user.email,
      } as RefreshJWTPayload,
      {
        expiresIn: this.configService.get('JWT_REFRESH_EXPIRE_TIME'),
        secret: this.configService.get('JWT_REFRESH_SECRET'),
      },
    )
  }
 
  /**
   * @description Generate access token for passed user
   */
  private async generateJWTToken(user: User): Promise<string> {
    return this.jwtService.sign({
      id: user._id,
      email: user.email,
      hasVerifiedEmail: user.hasVerifiedEmail,
      paymentPlan: user.paymentPlan,
    } as JWTPayload)
  }
 
  /**
   * @description Verify users email
   */
  async verifyUserMail(mail: string): Promise<void> {
    const user = await this.userService.findOneByEmail(mail)
 
    if (!user) {
      this.logger.warn('Verify for user that does not exist was attempted')
      throw new NotFoundException('No user with that email address exists')
    }
 
    if (user.hasVerifiedEmail) {
      this.logger.debug('Skipped verify as users email is already verified')
      throw new ConflictException('This user already verified their email')
    }
 
    try {
      this.logger.debug(`Verifying user mail`)
      await this.userService.updateUserEmailVerify(mail)
    } catch (error) {
      this.logger.error(`User update failed due to an error ${error}`)
      throw new InternalServerErrorException('Update could not be made')
    }
 
    Iif (!user.stripeCustomerId) return
    await this.stripeService.customer_update(user.stripeCustomerId, mail)
  }
 
  /**
   * @description Request that verification email is send to users email address
   */
  async requestUserVerifyMail(id: ObjectId): Promise<void> {
    const user = await this.userService.findOneById(id)
    // This should never happen, however it is a valid failsave
    if (!user) {
      throw new NotFoundException('No user')
    }
 
    // Dont do anything here, throwing an error is more confusing than helpful
    if (user.hasVerifiedEmail) {
      this.logger.debug('Verify mail was not send as user is already verified')
      return
    }
 
    try {
      await this.sendEmailVerify(user)
    } catch (error) {
      this.logger.error(`An error ocured while sending the email ${error}`)
      throw new ServiceUnavailableException(
        'Mail could not be send as of now. Please try again later',
      )
    }
  }
 
  /**
   * @description Send password reset email
   */
  async startForgottenPasswordFlow(email: string): Promise<void> {
    const user = await this.userService.findOneByEmail(email)
 
    // No error to prevent mail checking
    if (!user) return
 
    // Default to case that user does not have a verified email i.e. they have to contact support
    let mailContent: MailTemplateContent = {}
    let mailTemplate = MailTemplates.PASSWORD_RESET_SUPPORT
 
    if (user.hasVerifiedEmail) {
      const resetToken = this.jwtService.sign(
        {
          id: user._id,
        } as PasswordResetJWTPayload,
        {
          secret: this.configService.get('JWT_PASSWORD_RESET_SECRET'),
          expiresIn: this.configService.get('JWT_PASSWORD_RESET_EXPIRE_TIME'),
        },
      )
      const resetUrl = `${this.configService.get(
        'FRONTEND_DOMAIN',
      )}/account/change-password?token=${resetToken}`
 
      mailContent = { resetUrl } as PasswordResetMailData
      mailTemplate = MailTemplates.PASSWORD_RESET
    }
 
    const mailData: MailData = {
      content: {
        subject: 'Email reset',
        templateContent: mailContent,
        contentTemplate: mailTemplate,
      },
      recipient: {
        recipient: email,
      },
    }
 
    await this.mailService.scheduleMailNow(mailData)
  }
 
  /**
   * @description Reset user password
   */
  async setNewUserPassword(id: ObjectId, newPassword: string): Promise<void> {
    const user = await this.userService.findOneById(id)
    // This SHOULD never happen => Therefore internal server error
    if (!user) {
      this.logger.warn(
        `Password update was attempted for user that does not exist`,
      )
      throw new InternalServerErrorException(
        'This user does not seem to exist anymore',
      )
    }
    try {
      await this.userService.updateUserPassword(id, newPassword)
      // No tests for db failure
      /* istanbul ignore next */
    } catch (error) {
      this.logger.error(
        `Could not update a user password due to an error ${error}`,
      )
      throw new ServiceUnavailableException(
        'Password could not be set, please try again later',
      )
    }
  }
}