Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
2
Indexable
Never
/**
   * Creates a JwtPayload for the given User
   *
   * @param {UserDto} user
   * @returns {{ data: JwtPayload; token: string }} The data contains the email, username, and expiration of the
   * token depending on the environment variable. Expiration could be undefined if there is none set. token is the
   * token created by signing the data.
   * @memberof AuthService
   */
  async createJwt(user: UserDto, isRefresh?: boolean): Promise<string> {
    try {
      const data: any = {
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        role: user.role,
      };

      const options = !isRefresh
        ? { secret: process.env.JWT_SECRET }
        : {
            expiresIn: `${process.env.REFRESH_TOKEN_EXPIRATION_DAYS}d`,
            secret: process.env.JWT_REFRESH_SECRET,
          };

      const jwt = await this.jwtService.signAsync(data, options);

      if (isRefresh) {
        const refreshToken = await this.cryptoService.encrypt(jwt);
        await this.userService.updateUser(user.email, {
          refreshToken,
        });

        return refreshToken;
      }

      return jwt;
    } catch (e) {
      this.logger.log(`Error from ${this.createJwt.name}: ${e.message}`);
      throw new Error(e);
    }
  }