All files / user user.service.ts

100% Statements 113/113
100% Branches 49/49
100% Functions 24/24
100% Lines 111/111

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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470          18x 18x 18x 18x 18x 18x 18x       18x 18x         18x           18x   34x 34x 34x 34x 34x 34x 34x 34x                                   51x     51x     51x       51x       51x       51x 51x   51x 50x 49x       48x 47x       46x   46x 44x   44x             2x     1x         1x     1x         1x         1x                         234x 234x                 53x     53x                   86x   86x 81x   5x                     7x       7x 6x   1x                     24x   24x 23x           1x                               4x       4x       4x       3x   3x 2x   2x       1x     1x                           7x   7x 6x       1x                             2x   2x 1x   1x   1x   1x                         45x   45x 1x   1x       44x                       13x   13x                         3x   3x                         3x   3x                       8x                                     8x 8x                     6x   6x   6x 5x 5x         5x 2x 2x 2x   2x 2x   3x     1x                   44x 44x             1x       1x 1x                     46x       46x                           5x      
/**
 * User service.
 * @packageDocumentation
 */
 
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { DBService } from '../db/db.service';
import { ResourceService } from '../resource/resource.service';
import { ImageService } from '../image/image.service';
import { SessionService } from '../session/session.service';
import { bookTableName } from '../book/book.service';
import { userInterestTableName } from '../user-interest/user-interest.service';
import { NBUser } from './user.interface';
import { NBSession } from '../session/session.interface';
import { NBBook } from '../book/book.interface';
import { ServiceException } from '../service.exception';
import * as bcrypt from 'bcrypt';
 
/**
 * User table name.
 */
export const userTableName = 'NB_USER';
 
/**
 * User table service.
 */
@Injectable()
export class UserService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => ImageService))
    private readonly imageService: ImageService,
    @Inject(forwardRef(() => SessionService))
    private readonly sessionService: SessionService,
  ) {}
 
  /**
   * Create a new user.
   *
   * @param firstname The user's first name.
   * @param lastname The user's last name.
   * @param email The user's email address.
   * @param password The user's password.
   * @returns The new user record.
   */
  public async createUser(
    firstname: string,
    lastname: string,
    email: string,
    password: string,
  ): Promise<NBUser> {
    const userNameMaxLength = await this.resourceService.getResource<number>(
      'USER_NAME_MAX_LENGTH',
    );
    const userEmailMinLength = await this.resourceService.getResource<number>(
      'USER_EMAIL_MIN_LENGTH',
    );
    const userEmailMaxLength = await this.resourceService.getResource<number>(
      'USER_EMAIL_MAX_LENGTH',
    );
    const userPasswordMinLength =
      await this.resourceService.getResource<number>(
        'USER_PASSWORD_MIN_LENGTH',
      );
    const userPasswordMaxLength =
      await this.resourceService.getResource<number>(
        'USER_PASSWORD_MAX_LENGTH',
      );
 
    const emailAddressWithoutDomain = email.replace('@luther.edu', '');
    const emailAddress = `${emailAddressWithoutDomain}@luther.edu`;
 
    if (firstname.length > 0 && firstname.length <= userNameMaxLength) {
      if (lastname.length > 0 && lastname.length <= userNameMaxLength) {
        if (
          emailAddress.length >= userEmailMinLength &&
          emailAddress.length <= userEmailMaxLength
        ) {
          if (!emailAddressWithoutDomain.includes('@')) {
            if (
              password.length >= userPasswordMinLength &&
              password.length <= userPasswordMaxLength
            ) {
              const emailExists = await this.userExistsByEmail(emailAddress);
 
              if (!emailExists) {
                const passwordHash = await this.hashPassword(password);
 
                return this.dbService.create<NBUser>(userTableName, {
                  firstname,
                  lastname,
                  email: emailAddress,
                  passwordHash,
                });
              } else {
                throw new ServiceException('Email is already in use');
              }
            } else {
              throw new ServiceException(
                `Password must be between ${userPasswordMinLength} and ${userPasswordMaxLength} characters`,
              );
            }
          } else {
            throw new ServiceException('Please use Norse email address');
          }
        } else {
          throw new ServiceException(
            `Email must be between ${userEmailMinLength} and ${userEmailMaxLength} characters`,
          );
        }
      } else {
        throw new ServiceException(
          `First name must be between 1 and ${userNameMaxLength} characters`,
        );
      }
    } else {
      throw new ServiceException(
        `Last name must be between 1 and ${userNameMaxLength} characters`,
      );
    }
  }
 
  /**
   * Determine whether or not a user exists.
   *
   * @param userID The ID of the user.
   * @returns Whether or not the user exists.
   */
  public async userExists(userID: string): Promise<boolean> {
    const user = await this.dbService.getByID<NBUser>(userTableName, userID);
    return !!user;
  }
 
  /**
   * Determine whether or not a user with a given email address exists.
   * @param email The user's email.
   * @returns Whether or not a user with the given email address exists.
   */
  public async userExistsByEmail(email: string): Promise<boolean> {
    const user = await this.dbService.getByFields<NBUser>(userTableName, {
      email,
    });
    return !!user;
  }
 
  /**
   * Get a user.
   *
   * @param userID The user's ID.
   * @returns The user record.
   */
  public async getUser(userID: string): Promise<NBUser> {
    const user = await this.dbService.getByID<NBUser>(userTableName, userID);
 
    if (user) {
      return user;
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Get a user given an email address.
   *
   * @param email The user's email address.
   * @returns The user record.
   */
  public async getUserByEmail(email: string): Promise<NBUser> {
    const user = await this.dbService.getByFields<NBUser>(userTableName, {
      email,
    });
 
    if (user) {
      return user;
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Get the books currently listed by a user.
   *
   * @param userID The user's ID.
   * @returns All books currently listed by the user.
   */
  public async getCurrentBooks(userID: string): Promise<NBBook[]> {
    const userExists = await this.userExists(userID);
 
    if (userExists) {
      return this.dbService.listByFields<NBBook>(
        bookTableName,
        { userID },
        { fieldName: 'listTime', sortOrder: 'ASC' },
      );
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Set a user's password.
   *
   * @param userID The user's ID.
   * @param newPassword The new password.
   * @returns The updated user record.
   */
  public async setPassword(
    userID: string,
    newPassword: string,
  ): Promise<NBUser> {
    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 userExists = await this.userExists(userID);
 
      if (userExists) {
        const passwordHash = await this.hashPassword(newPassword);
 
        return this.dbService.updateByID<NBUser>(userTableName, userID, {
          passwordHash,
        });
      } else {
        throw new ServiceException('User does not exist');
      }
    } else {
      throw new ServiceException(
        `Password must be between ${userPasswordMinLength} and ${userPasswordMaxLength} characters`,
      );
    }
  }
 
  /**
   * Set a user's verified status.
   *
   * @param userID The user's ID.
   * @param verified The new verified status.
   * @returns The updated user record.
   */
  public async setVerified(userID: string, verified = true): Promise<NBUser> {
    const userExists = await this.userExists(userID);
 
    if (userExists) {
      return this.dbService.updateByID<NBUser>(userTableName, userID, {
        verified,
      });
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Set a user's image.
   *
   * @param userID The user's ID.
   * @param imageData The image data.
   * @returns The updated user record.
   */
  public async setUserImage(
    userID: string,
    imageData: string,
  ): Promise<NBUser> {
    const user = await this.getUser(userID);
 
    if (user.imageID) {
      await this.imageService.setImageData(user.imageID, imageData);
 
      return user;
    } else {
      const image = await this.imageService.createImage(imageData);
 
      return this.dbService.updateByID<NBUser>(userTableName, userID, {
        imageID: image.id,
      });
    }
  }
 
  /**
   * Delete a user's image.
   *
   * @param userID The user's ID.
   * @returns The updated user record.
   */
  public async deleteUserImage(userID: string): Promise<NBUser> {
    const user = await this.getUser(userID);
 
    if (user.imageID) {
      await this.imageService.deleteImage(user.imageID);
 
      return this.dbService.updateByID<NBUser>(userTableName, userID, {
        imageID: null,
      });
    } else {
      return user;
    }
  }
 
  /**
   * Increment the number of books a user has listed.
   *
   * @param userID The user's ID.
   * @param num The number to increment by.
   * @returns The updated user record.
   */
  public async incrementBooksListed(userID: string, num = 1): Promise<NBUser> {
    const user = await this.getUser(userID);
 
    return this.dbService.updateByID<NBUser>(userTableName, userID, {
      numBooksListed: user.numBooksListed + num,
    });
  }
 
  /**
   * Increment the number of books a user has sold.
   *
   * @param userID The user's ID.
   * @param num The number to increment by.
   * @returns The updated user record.
   */
  public async incrementBooksSold(userID: string, num = 1): Promise<NBUser> {
    const user = await this.getUser(userID);
 
    return this.dbService.updateByID<NBUser>(userTableName, userID, {
      numBooksSold: user.numBooksSold + num,
    });
  }
 
  /**
   * Increment the amount of money a user has made.
   *
   * @param userID The user's ID.
   * @param amount The amount of money to add.
   * @returns The updated user record.
   */
  public async addMoneyMade(userID: string, amount: number): Promise<NBUser> {
    const user = await this.getUser(userID);
 
    return this.dbService.updateByID<NBUser>(userTableName, userID, {
      moneyMade: user.moneyMade + amount,
    });
  }
 
  /**
   * Get a list of books recommended to the user.
   *
   * @param userID The user's ID.
   * @returns The list of recommended books.
   */
  public async recommendations(userID: string): Promise<NBBook[]> {
    const sql = `
      (
        SELECT "${bookTableName}".*
          FROM "${bookTableName}"
          JOIN "${userInterestTableName}"
            ON "${bookTableName}"."departmentID" = "${userInterestTableName}"."departmentID"
        WHERE "${userInterestTableName}"."userID" = ?
          AND "${bookTableName}"."userID" != ?
      ) UNION (
        SELECT "${bookTableName}".*
          FROM "${bookTableName}"
          JOIN (
            SELECT *
              FROM "${bookTableName}"
              WHERE "userID" = ?
          ) AS "USER_BOOKS"
            ON "${bookTableName}"."departmentID" = "USER_BOOKS"."departmentID"
        WHERE "${bookTableName}"."userID" != ?
      ) ORDER BY "listTime" ASC;`;
    const params = [userID, userID, userID, userID];
    return this.dbService.execute<NBBook>(sql, params);
  }
 
  /**
   * Log a user in and return the new session.
   *
   * @param email The user's email address.
   * @param password The user's password.
   * @returns The new user session.
   */
  public async login(email: string, password: string): Promise<NBSession> {
    const emailAddress = email.includes('@') ? email : `${email}@luther.edu`;
 
    const userExists = await this.userExistsByEmail(emailAddress);
 
    if (userExists) {
      const user = await this.getUserByEmail(emailAddress);
      const passwordMatch = await this.passwordMatch(
        password,
        user.passwordHash,
      );
 
      if (passwordMatch && user.verified) {
        const sql = `UPDATE "${userTableName}" SET "lastLoginTime" = NOW() WHERE id = ?;`;
        const params = [user.id];
        await this.dbService.execute(sql, params);
 
        const session = await this.sessionService.createSession(user.id);
        return session;
      } else {
        throw new ServiceException('Invalid login');
      }
    } else {
      throw new ServiceException('Invalid login');
    }
  }
 
  /**
   * Delete a user.
   *
   * @param userID The user's ID.
   */
  public async deleteUser(userID: string): Promise<void> {
    await this.deleteUserImage(userID);
    await this.dbService.deleteByID(userTableName, userID);
  }
 
  /**
   * Prune all old unverified accounts.
   */
  public async pruneUnverifiedUsers(): Promise<void> {
    const unverifiedUserAge = await this.resourceService.getResource<number>(
      'UNVERIFIED_USER_AGE',
    );
 
    const sql = `DELETE FROM "${userTableName}" WHERE "verified" = FALSE AND EXTRACT(EPOCH FROM NOW() - "joinTime") >= ${unverifiedUserAge};`;
    await this.dbService.execute(sql);
  }
 
  /**
   * Hash a password.
   *
   * @param password The password.
   * @param rounds The number of salt rounds for bcrypt to use.
   * @returns The hashed password.
   */
  private async hashPassword(password: string): Promise<string> {
    const saltRounds = await this.resourceService.getResource<number>(
      'SALT_ROUNDS',
    );
 
    return bcrypt.hash(password, saltRounds);
  }
 
  /**
   * Check if passwords match.
   *
   * @param password The password.
   * @param hash The hashed password.
   * @returns Whether or not the password and hash match.
   */
  private async passwordMatch(
    password: string,
    hash: string,
  ): Promise<boolean> {
    return bcrypt.compare(password, hash);
  }
}