All files / profile profile.service.ts

96.07% Statements 49/51
100% Branches 8/8
100% Functions 4/4
95.91% Lines 47/49

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 1291x             1x   1x   1x 1x 1x 1x     1x 1x   1x 1x 1x 1x                 3x   3x 2x 2x       1x       8x 8x 1x     7x 1x         1x     6x 6x   1x   1x 1x                     5x 5x   1x             7x   7x 1x     6x 6x   6x   5x                   5x 5x 3x   2x           2x   2x 2x 2x                
import {
  HttpException,
  Injectable,
  InternalServerErrorException,
  Logger,
  UnauthorizedException,
} from '@nestjs/common'
import { compare } from 'bcrypt'
import { ObjectId } from 'mongoose'
import { AuthService } from '../auth/auth.service'
import { MailData } from '../db/entities/mail-event.entity'
import { LastWillDBService } from '../db/services/lastwill.service'
import { UserDBService } from '../db/services/user.service'
import { MailTemplates } from '../mail/interfaces/mail.interface'
import { MailScheduleService } from '../mail/services/scheduler.service'
 
@Injectable()
export class ProfileService {
  private readonly logger = new Logger(ProfileService.name)
  constructor(
    private readonly userService: UserDBService,
    private readonly authService: AuthService,
    private readonly mailService: MailScheduleService,
    private readonly lastwillDbService: LastWillDBService,
  ) {}
 
  async updatePassword(
    id: ObjectId,
    oldPassword: string,
    newPassword: string,
  ): Promise<void> {
    // Verify that old password is right
    const user = await this.userService.findOneById(id)
 
    if (!user || !(await compare(oldPassword, user.password))) {
      this.logger.warn(`Invalid credentials for password change.`)
      throw new UnauthorizedException(
        'This is not allowed...either you do not exist or the provided password was invalid',
      )
    }
    await this.userService.updateUserPassword(id, newPassword)
  }
 
  async updateUserEmail(id: ObjectId, newEmail: string): Promise<void> {
    const user = await this.userService.findOneById(id)
    if (!user) {
      throw new UnauthorizedException()
    }
 
    if (user.email === newEmail) {
      this.logger.log(
        `Skipping email update for user as new email equaled the old one`,
      )
      // Do not throw error here
      // Throwing an error would allow for an attacker to brute force their way to the accounts email address
      return
    }
 
    try {
      await this.userService.updateUserEmail(id, newEmail)
    } catch (error) {
      this.logger.error(`Could not update user email ${error}`)
      // If error is already httpexception => Continue throwing
      if (error instanceof HttpException) {
        throw error
      }
 
      // This should only happen on DB failure...which we do not test
      /* istanbul ignore next */
      this.logger.warn(`Could not update user email due to an error ${error}`)
      throw new InternalServerErrorException(
        'Something went wrong, please try again later',
      )
    }
 
    try {
      await this.authService.requestUserVerifyMail(id)
    } catch (error) {
      this.logger.warn(
        `Updated email for user did not receive verify email due to an error. The user update continues anyways. ${error}`,
      )
    }
  }
 
  async deleteProfile(id: ObjectId): Promise<void> {
    const user = await this.userService.findOneById(id)
 
    if (!user) {
      throw new UnauthorizedException()
    }
 
    await this.userService.deleteUserById(id)
    await this.lastwillDbService.deleteAllByUser(id)
 
    if (!user.hasVerifiedEmail) return
 
    const mailData: MailData = {
      content: {
        subject: 'Account gelöscht',
        contentTemplate: MailTemplates.ACCOUNT_DELETED,
      },
      recipient: {
        recipient: user.email,
      },
    }
 
    try {
      await this.mailService.scheduleMailNow(mailData)
      return
    } catch (error) {
      this.logger.error(
        `Could not send email regarding account deletion. Deletion will continue anyway.`,
      )
    }
 
    // If we get here the mail could not be send as of now => Fallback to just scheduling it
    const newSendDate = new Date()
    // Reschedule 5 hours later by default
    newSendDate.setHours(newSendDate.getHours() + 5)
    try {
      await this.mailService.scheduleMailAtDate(newSendDate, mailData)
    } catch (error) {
      this.logger.warn(
        `Mail could not be scheduled due to an error. Account deletion continues anyways ${error}`,
      )
    }
  }
}