All files / password-reset password-reset.service.ts

98.18% Statements 54/55
93.75% Branches 15/16
100% Functions 14/14
98.11% Lines 52/53

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          18x 18x 18x 18x     18x         18x           18x   34x 34x 34x 34x 34x 34x                   5x   4x 4x       4x 3x       1x                         5x       5x                   5x       5x                       3x         3x 2x   1x                         4x         4x 3x   1x                       1x                             3x       3x 3x   3x 2x   1x                       4x                           3x       3x       3x       2x       2x 1x 1x 1x   1x     1x                   1x       1x 1x      
/**
 * Password reset service.
 * @packageDocumentation
 */
 
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { DBService } from '../db/db.service';
import { ResourceService } from '../resource/resource.service';
import { UserService, userTableName } from '../user/user.service';
import { NBPasswordReset } from './password-reset.interface';
import { NBUser } from '../user/user.interface';
import { ServiceException } from '../service.exception';
 
/**
 * Password reset table name.
 */
export const passwordResetTableName = 'NB_PASSWORD_RESET';
 
/**
 * Password reset table service.
 */
@Injectable()
export class PasswordResetService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
  ) {}
 
  /**
   * Create a password reset record.
   *
   * @param userID The ID of the user requesting the password reset.
   * @returns The new password reset record.
   */
  public async createPasswordReset(userID: string): Promise<NBPasswordReset> {
    const user = await this.userService.getUser(userID);
 
    Eif (user.verified) {
      const passwordResetExists = await this.passwordResetExistsByUserID(
        userID,
      );
 
      if (!passwordResetExists) {
        return this.dbService.create<NBPasswordReset>(passwordResetTableName, {
          userID,
        });
      } else {
        return this.getPasswordResetByUserID(userID);
      }
    } else {
      throw new ServiceException('User is not verified');
    }
  }
 
  /**
   * Determine whether or not a password reset record exists.
   * @param passwordResetID The password reset ID.
   * @returns Whether or not the password reset record exists.
   */
  public async passwordResetExists(passwordResetID: string): Promise<boolean> {
    const passwordReset = await this.dbService.getByID<NBPasswordReset>(
      passwordResetTableName,
      passwordResetID,
    );
    return !!passwordReset;
  }
 
  /**
   * Determine whether or not a password reset record exists for a given user ID.
   *
   * @param userID The ID of the user associated with the password reset record.
   * @returns Whether or not the password reset record exists for the given user ID.
   */
  public async passwordResetExistsByUserID(userID: string): Promise<boolean> {
    const passwordReset = await this.dbService.getByFields<NBPasswordReset>(
      passwordResetTableName,
      { userID },
    );
    return !!passwordReset;
  }
 
  /**
   * Get a password reset record.
   *
   * @param passwordResetID The password reset record's ID.
   * @returns The password reset record.
   */
  public async getPasswordReset(
    passwordResetID: string,
  ): Promise<NBPasswordReset> {
    const passwordReset = await this.dbService.getByID<NBPasswordReset>(
      passwordResetTableName,
      passwordResetID,
    );
 
    if (passwordReset) {
      return passwordReset;
    } else {
      throw new ServiceException('Password reset record does not exist');
    }
  }
 
  /**
   * Get the password reset record associated with a user.
   *
   * @param userID The ID of the user associated with the password reset record.
   * @returns The password reset record associated with the user.
   */
  public async getPasswordResetByUserID(
    userID: string,
  ): Promise<NBPasswordReset> {
    const passwordReset = await this.dbService.getByFields<NBPasswordReset>(
      passwordResetTableName,
      { userID },
    );
 
    if (passwordReset) {
      return passwordReset;
    } else {
      throw new ServiceException(
        'Password reset record does not exist for given user ID',
      );
    }
  }
 
  /**
   * Get all password reset records.
   *
   * @returns All password reset records.
   */
  public async getPasswordResets(): Promise<NBPasswordReset[]> {
    return this.dbService.list<NBPasswordReset>(passwordResetTableName, {
      fieldName: 'createTime',
      sortOrder: 'ASC',
    });
  }
 
  /**
   * Get the user associated with a password reset record.
   *
   * @param passwordResetID The password reset record's ID.
   * @returns The user associated with the password reset record.
   */
  public async getUserByPasswordReset(
    passwordResetID: string,
  ): Promise<NBUser> {
    const sql = `
      SELECT * FROM "${userTableName}" WHERE "id" = (
        SELECT "userID" FROM "${passwordResetTableName}" WHERE id = ?
      );`;
    const params = [passwordResetID];
    const res = await this.dbService.execute<NBUser>(sql, params);
 
    if (res.length === 1) {
      return res[0];
    } else {
      throw new ServiceException(
        'User does not exist for given password reset ID',
      );
    }
  }
 
  /**
   * Delete a password reset record.
   *
   * @param passwordResetID The password reset record's ID.
   */
  public async deletePasswordReset(passwordResetID: string): Promise<void> {
    await this.dbService.deleteByID(passwordResetTableName, passwordResetID);
  }
 
  /**
   * Reset a user's password and delete the password reset record.
   *
   * @param passwordResetID The password reset record's ID.
   * @param newPassword The user's new password.
   */
  public async resetPassword(
    passwordResetID: string,
    newPassword: string,
  ): Promise<void> {
    const userPasswordMinLength =
      await this.resourceService.getResource<number>(
        'USER_PASSWORD_MIN_LENGTH',
      );
    const userPasswordMaxLength =
      await this.resourceService.getResource<number>(
        'USER_PASSWORD_MAX_LENGTH',
      );
 
    if (
      newPassword.length >= userPasswordMinLength &&
      newPassword.length <= userPasswordMaxLength
    ) {
      const passwordResetExists = await this.passwordResetExists(
        passwordResetID,
      );
 
      if (passwordResetExists) {
        const user = await this.getUserByPasswordReset(passwordResetID);
        await this.deletePasswordReset(passwordResetID);
        await this.userService.setPassword(user.id, newPassword);
      } else {
        throw new ServiceException('Invalid password reset ID');
      }
    } else {
      throw new ServiceException(
        `Password must be between ${userPasswordMinLength} and ${userPasswordMaxLength} characters`,
      );
    }
  }
 
  /**
   * Prune all old password reset records.
   */
  public async prunePasswordResets(): Promise<void> {
    const passwordResetAge = await this.resourceService.getResource<number>(
      'PASSWORD_RESET_AGE',
    );
 
    const sql = `DELETE FROM "${passwordResetTableName}" WHERE EXTRACT(EPOCH FROM NOW() - "createTime") >= ${passwordResetAge};`;
    await this.dbService.execute(sql);
  }
}