All files / session session.service.ts

100% Statements 46/46
100% Branches 10/10
100% Functions 12/12
100% Lines 44/44

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          18x 18x 18x 18x     18x         18x           18x   34x 34x 34x 34x 34x 34x                   5x   5x 4x     4x 4x   1x                     2x       2x                   2x         2x 1x   1x                     2x       2x 2x   2x 1x   1x                     3x   3x 2x           1x                   1x                 1x                 5x   5x 4x       4x                   4x 4x   1x        
/**
 * Session 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 { NBSession } from './session.interface';
import { NBUser } from '../user/user.interface';
import { ServiceException } from '../service.exception';
 
/**
 * Session table name.
 */
export const sessionTableName = 'NB_SESSION';
 
/**
 * Session table service.
 */
@Injectable()
export class SessionService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
  ) {}
 
  /**
   * Create a user session.
   *
   * @param userID The ID of the user creating the session.
   * @returns The new session record.
   */
  public async createSession(userID: string): Promise<NBSession> {
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      const session = await this.dbService.create<NBSession>(sessionTableName, {
        userID,
      });
      await this.deleteOldUserSessions(userID);
      return session;
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Determine whether or not a session exists.
   *
   * @param sessionID The session's ID.
   * @returns Whether or not the session exists.
   */
  public async sessionExists(sessionID: string): Promise<boolean> {
    const session = await this.dbService.getByID<NBSession>(
      sessionTableName,
      sessionID,
    );
    return !!session;
  }
 
  /**
   * Get a user session record.
   *
   * @param sessionID The session's ID.
   * @returns The user session record.
   */
  public async getSession(sessionID: string): Promise<NBSession> {
    const res = await this.dbService.getByID<NBSession>(
      sessionTableName,
      sessionID,
    );
 
    if (res) {
      return res;
    } else {
      throw new ServiceException('Session does not exist');
    }
  }
 
  /**
   * Get the user associated with a session.
   *
   * @param sessionID The session's ID.
   * @returns The user associated with the session.
   */
  public async getUserBySessionID(sessionID: string): Promise<NBUser> {
    const sql = `
      SELECT * FROM "${userTableName}" WHERE id = (
        SELECT "userID" FROM "${sessionTableName}" WHERE id = ?
      );`;
    const params = [sessionID];
    const res = await this.dbService.execute<NBUser>(sql, params);
 
    if (res.length === 1) {
      return res[0];
    } else {
      throw new ServiceException('Session does not exist');
    }
  }
 
  /**
   * Get all sessions associated with a user.
   *
   * @param userID The user's ID.
   * @returns All sessions associated with the user.
   */
  public async getUserSessions(userID: string): Promise<NBSession[]> {
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      return this.dbService.listByFields<NBSession>(
        sessionTableName,
        { userID },
        { fieldName: 'createTime', sortOrder: 'ASC' },
      );
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Delete a user session.
   *
   * @param sessionID The session's ID.
   */
  public async deleteSession(sessionID: string): Promise<void> {
    await this.dbService.deleteByID(sessionTableName, sessionID);
  }
 
  /**
   * Delete all sessions associated with a user.
   *
   * @param userID The user's ID.
   */
  public async deleteUserSessions(userID: string): Promise<void> {
    await this.dbService.deleteByFields(sessionTableName, { userID });
  }
 
  /**
   * Delete all old user sessions.
   *
   * @param userID The user's ID.
   */
  public async deleteOldUserSessions(userID: string): Promise<void> {
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      const userMaxSessions = await this.resourceService.getResource<number>(
        'USER_MAX_SESSIONS',
      );
 
      const sql = `
        DELETE FROM "${sessionTableName}"
          WHERE "userID" = ?
          AND "id" NOT IN (
            SELECT "id" FROM "${sessionTableName}"
              WHERE "userID" = ?
              ORDER BY "createTime" DESC
              LIMIT ?
        );
      `;
      const params = [userID, userID, userMaxSessions];
      await this.dbService.execute(sql, params);
    } else {
      throw new ServiceException('User does not exist');
    }
  }
}