All files / verify verify.service.ts

100% Statements 60/60
88.89% Branches 16/18
100% Functions 15/15
100% Lines 58/58

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          18x 18x 18x 18x     18x         18x           18x   34x 34x 34x 34x 34x 34x                   5x   5x 4x   4x 3x   1x     1x                     7x       7x                   5x       5x                   4x         4x 3x   1x                     4x         4x 3x   1x                       1x                         4x       4x 4x   4x 3x   1x                   4x                 2x   2x 1x 1x   1x 1x   1x 1x       1x                   2x   2x 1x 1x 1x   1x               1x       1x 1x      
/**
 * Verify 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 { NBVerify } from './verify.interface';
import { NBUser } from '../user/user.interface';
import { ServiceException } from '../service.exception';
 
/**
 * Verify table name.
 */
export const verifyTableName = 'NB_VERIFY';
 
/**
 * Verify table service.
 */
@Injectable()
export class VerifyService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
  ) {}
 
  /**
   * Create a verification record.
   *
   * @param userID The ID of the user being verified.
   * @returns The new verification record.
   */
  public async createVerification(userID: string): Promise<NBVerify> {
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      const verificationExists = await this.verificationExistsByUserID(userID);
 
      if (!verificationExists) {
        return this.dbService.create<NBVerify>(verifyTableName, { userID });
      } else {
        return this.getVerificationByUserID(userID);
      }
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Determine whether or not a verification record exists.
   *
   * @param verifyID The verification ID.
   * @returns Whether or not the verification record exists.
   */
  public async verificationExists(verifyID: string): Promise<boolean> {
    const verification = await this.dbService.getByID<NBVerify>(
      verifyTableName,
      verifyID,
    );
    return !!verification;
  }
 
  /**
   * Determine whether or not a verification record exists for a given user ID.
   *
   * @param userID The ID of the user associated with the verification record.
   * @returns Whether or not the verification record exists for the given user ID.
   */
  public async verificationExistsByUserID(userID: string): Promise<boolean> {
    const verification = await this.dbService.getByFields<NBVerify>(
      verifyTableName,
      { userID },
    );
    return !!verification;
  }
 
  /**
   * Get a verification record.
   *
   * @param verifyID The verification record's ID.
   * @returns The verification record.
   */
  public async getVerification(verifyID: string): Promise<NBVerify> {
    const verification = await this.dbService.getByID<NBVerify>(
      verifyTableName,
      verifyID,
    );
 
    if (verification) {
      return verification;
    } else {
      throw new ServiceException('Verification record does not exist');
    }
  }
 
  /**
   * Get the verification record associated with a user.
   *
   * @param userID The ID of the user associated with the verification record.
   * @returns The verification record associated with the user.
   */
  public async getVerificationByUserID(userID: string): Promise<NBVerify> {
    const verification = await this.dbService.getByFields<NBVerify>(
      verifyTableName,
      { userID },
    );
 
    if (verification) {
      return verification;
    } else {
      throw new ServiceException(
        'Verification record does not exist for given user ID',
      );
    }
  }
 
  /**
   * Get all verification records.
   *
   * @returns All verification records.
   */
  public async getVerifications(): Promise<NBVerify[]> {
    return this.dbService.list<NBVerify>(verifyTableName, {
      fieldName: 'createTime',
      sortOrder: 'ASC',
    });
  }
 
  /**
   * Get the user associated with a verification record.
   *
   * @param verifyID The verification record's ID.
   * @returns The user associated with the verification record.
   */
  public async getUserByVerification(verifyID: string): Promise<NBUser> {
    const sql = `
      SELECT * FROM "${userTableName}" WHERE "id" = (
        SELECT "userID" FROM "${verifyTableName}" WHERE "id" = ?
      );`;
    const params = [verifyID];
    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 verify ID');
    }
  }
 
  /**
   * Delete a verification record.
   *
   * @param verifyID The verification record's ID.
   */
  public async deleteVerification(verifyID: string): Promise<void> {
    await this.dbService.deleteByID(verifyTableName, verifyID);
  }
 
  /**
   * Delete a verification record and the corresponding user.
   *
   * @param verifyID The verification record's ID.
   */
  public async deleteUnverifiedUser(verifyID: string): Promise<void> {
    const verificationExists = await this.verificationExists(verifyID);
 
    if (verificationExists) {
      const verification = await this.getVerification(verifyID);
      const userExists = await this.userService.userExists(verification.userID);
 
      Eif (userExists) {
        const user = await this.getUserByVerification(verifyID);
 
        Eif (!user.verified) {
          await this.userService.deleteUser(user.id);
        }
      }
 
      await this.deleteVerification(verifyID);
    }
  }
 
  /**
   * Verify a user's account and delete the verification record.
   *
   * @param verifyID The verification record's ID.
   */
  public async verifyUser(verifyID: string): Promise<void> {
    const verificationExists = await this.verificationExists(verifyID);
 
    if (verificationExists) {
      const user = await this.getUserByVerification(verifyID);
      await this.deleteVerification(verifyID);
      await this.userService.setVerified(user.id);
    } else {
      throw new ServiceException('Invalid verify ID');
    }
  }
 
  /**
   * Prune all old verification records.
   */
  public async pruneVerifications(): Promise<void> {
    const verificationAge = await this.resourceService.getResource<number>(
      'VERIFICATION_AGE',
    );
 
    const sql = `DELETE FROM "${verifyTableName}" WHERE EXTRACT(EPOCH FROM NOW() - "createTime") >= ${verificationAge};`;
    await this.dbService.execute(sql);
  }
}