All files / src accounts-password.ts

92.06% Statements 197/214
87.38% Branches 90/103
100% Functions 28/28
92.31% Lines 156/169

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 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 4862x                   2x 2x 2x                 2x                                                           2x                 7x     3x     6x 6x 6x         2x 3x           3x 3x 3x     2x 30x 30x     2x 6x 6x 1x   5x 1x     4x     1x       1x               2x 1x               2x 1x                         2x 2x 1x   1x                   2x 1x               2x 5x 1x     4x 4x 1x     3x 3x 3x 1x     2x 2x 1x   1x                 2x 7x 1x   6x 1x     5x 5x 1x     4x 4x   4x                 1x     3x 3x 1x     2x   2x     1x 1x       2x                 2x 1x 1x                   2x         1x 1x 1x                   2x 4x 1x     3x 3x   1x     1x   2x 2x   2x                 2x                   2x 3x 1x     2x 2x   1x     1x   1x 1x   1x                 1x                     2x 3x 1x     2x 2x 1x   1x 1x   1x                 1x               2x 6x 1x     9x 1x     4x 1x       3x     3x       3x 2x 2x     3x   3x 2x 2x     3x             2x 2x     2x       3x           3x     3x         3x       3x 1x             2x 2x 1x     1x 1x 1x   1x 1x           2x 5x 5x 5x                 3x 3x 3x 3x 3x           3x   2x  
import { trim, isEmpty, pick, isString, isPlainObject, find, includes, defer } from 'lodash';
import {
  User,
  LoginUserIdentity,
  EmailRecord,
  TokenRecord,
  DatabaseInterface,
  AuthenticationService,
  HashAlgorithm,
} from '@accounts/types';
import { TwoFactor, AccountsTwoFactorOptions, getUserTwoFactorService } from '@accounts/two-factor';
import { AccountsServer, ServerHooks, generateRandomToken } from '@accounts/server';
import {
  getUserResetTokens,
  getUserVerificationTokens,
  hashPassword,
  bcryptPassword,
  verifyPassword,
  isEmail,
} from './utils';
import { PasswordCreateUserType, PasswordLoginType, PasswordType, ErrorMessages } from './types';
import { errors } from './errors';
 
export interface AccountsPasswordOptions {
  twoFactor?: AccountsTwoFactorOptions;
  passwordHashAlgorithm?: HashAlgorithm;
  /**
   * The number of milliseconds from when a link to verify the user email is sent until token expires and user can't verify his email with the link anymore. Defaults to 3 days.
   */
  verifyEmailTokenExpiration?: number;
  /**
   * The number of milliseconds from when a link to reset password is sent until token expires and user can't reset password with the link anymore. Defaults to 3 days.
   */
  passwordResetTokenExpiration?: number;
  /**
   * The number of milliseconds from when a link to set inital password is sent until token expires and user can't set password with the link anymore. Defaults to 30 days.
   */
  passwordEnrollTokenExpiration?: number;
  minimumPasswordLength?: number;
  /**
   * Accounts password module errors
   */
  errors?: ErrorMessages;
  validateNewUser?: (
    user: PasswordCreateUserType
  ) => Promise<PasswordCreateUserType> | PasswordCreateUserType;
  validateEmail?(email?: string): boolean;
  validatePassword?(password?: PasswordType): boolean;
  validateUsername?(username?: string): boolean;
}
 
const defaultOptions = {
  minimumPasswordLength: 7,
  // 3 days - 3 * 24 * 60 * 60 * 1000
  verifyEmailTokenExpiration: 259200000,
  // 3 days - 3 * 24 * 60 * 60 * 1000
  passwordResetTokenExpiration: 259200000,
  // 30 days - 30 * 24 * 60 * 60 * 1000
  passwordEnrollTokenExpiration: 2592000000,
  validateEmail(email?: string): boolean {
    return !isEmpty(trim(email)) && isEmail(email);
  },
  validatePassword(password?: PasswordType): boolean {
    return !isEmpty(password);
  },
  validateUsername(username?: string): boolean {
    const usernameRegex = /^[a-zA-Z][a-zA-Z0-9]*$/;
    const isValid = username && !isEmpty(trim(username)) && usernameRegex.test(username);
    return Boolean(isValid);
  },
  errors,
};
 
export default class AccountsPassword implements AuthenticationService {
  public serviceName = 'password';
  public server!: AccountsServer;
  public twoFactor: TwoFactor;
  private options: AccountsPasswordOptions & typeof defaultOptions;
  private db!: DatabaseInterface;
 
  constructor(Ioptions: AccountsPasswordOptions = {}) {
    this.options = { ...defaultOptions, ...options };
    this.twoFactor = new TwoFactor(options.twoFactor);
  }
 
  public setStore(store: DatabaseInterface) {
    this.db = store;
    this.twoFactor.setStore(store);
  }
 
  public async authenticate(params: PasswordLoginType): Promise<User> {
    const { user, password, code } = params;
    if (!user || !password) {
      throw new Error(this.options.errors.unrecognizedOptionsForLogin);
    }
    if ((!isString(user) && !isPlainObject(user)) || !isString(password)) {
      throw new Error(this.options.errors.matchFailed);
    }
 
    const foundUser = await this.passwordAuthenticator(user, password);
 
    // If user activated two factor authentication try with the code
    if (getUserTwoFactorService(foundUser)) {
      await this.twoFactor.authenticate(foundUser, code!);
    }
 
    return foundUser;
  }
 
  /**
   * @description Find a user by one of his emails.
   * @param {string} email - User email.
   * @returns {Promise<Object>} - Return a user or null if not found.
   */
  public findUserByEmail(email: string): Promise<User | null> {
    return this.db.findUserByEmail(email);
  }
 
  /**
   * @description Find a user by his username.
   * @param {string} username - User username.
   * @returns {Promise<Object>} - Return a user or null if not found.
   */
  public findUserByUsername(username: string): Promise<User | null> {
    return this.db.findUserByUsername(username);
  }
 
  /**
   * @description Add an email address for a user.
   * It will trigger the `validateEmail` option and throw if email is invalid.
   * Use this instead of directly updating the database.
   * @param {string} userId - User id.
   * @param {string} newEmail - A new email address for the user.
   * @param {boolean} [verified] - Whether the new email address should be marked as verified.
   * Defaults to false.
   * @returns {Promise<void>} - Return a Promise.
   */
  public addEmail(userId: string, newEmail: string, verified: boolean): Promise<void> {
    if (!this.options.validateEmail(newEmail)) {
      throw new Error(this.options.errors.invalidEmail);
    }
    return this.db.addEmail(userId, newEmail, verified);
  }
 
  /**
   * @description Remove an email address for a user.
   * Use this instead of directly updating the database.
   * @param {string} userId - User id.
   * @param {string} email - The email address to remove.
   * @returns {Promise<void>} - Return a Promise.
   */
  public removeEmail(userId: string, email: string): Promise<void> {
    return this.db.removeEmail(userId, email);
  }
 
  /**
   * @description Marks the user's email address as verified.
   * @param {string} token - The token retrieved from the verification URL.
   * @returns {Promise<void>} - Return a Promise.
   */
  public async verifyEmail(token: string): Promise<void> {
    if (!token || !isString(token)) {
      throw new Error(this.options.errors.invalidToken);
    }
 
    const user = await this.db.findUserByEmailVerificationToken(token);
    if (!user) {
      throw new Error(this.options.errors.verifyEmailLinkExpired);
    }
 
    const verificationTokens = getUserVerificationTokens(user);
    const tokenRecord = find(verificationTokens, (t: TokenRecord) => t.token === token);
    if (!tokenRecord || this.isTokenExpired(tokenRecord, this.options.verifyEmailTokenExpiration)) {
      throw new Error(this.options.errors.verifyEmailLinkExpired);
    }
 
    const emailRecord = find(user.emails, (e: EmailRecord) => e.address === tokenRecord.address);
    if (!emailRecord) {
      throw new Error(this.options.errors.verifyEmailLinkUnknownAddress);
    }
    await this.db.verifyEmail(user.id, emailRecord.address);
  }
 
  /**
   * @description Reset the password for a user using a token received in email.
   * @param {string} token - The token retrieved from the reset password URL.
   * @param {string} newPassword - A new password for the user.
   * @returns {Promise<void>} - Return a Promise.
   */
  public async resetPassword(token: string, newPassword: PasswordType): Promise<void> {
    if (!token || !isString(token)) {
      throw new Error(this.options.errors.invalidToken);
    }
    if (!newPassword || !isString(newPassword)) {
      throw new Error(this.options.errors.invalidNewPassword);
    }
 
    const user = await this.db.findUserByResetPasswordToken(token);
    if (!user) {
      throw new Error(this.options.errors.resetPasswordLinkExpired);
    }
 
    const resetTokens = getUserResetTokens(user);
    const resetTokenRecord = find(resetTokens, t => t.token === token);
 
    if (
      !resetTokenRecord ||
      this.isTokenExpired(
        resetTokenRecord,
        resetTokenRecord.reason === 'enroll'
          ? this.options.passwordEnrollTokenExpiration
          : this.options.passwordResetTokenExpiration
      )
    ) {
      throw new Error(this.options.errors.resetPasswordLinkExpired);
    }
 
    const emails = user.emails || [];
    if (!includes(emails.map((email: EmailRecord) => email.address), resetTokenRecord.address)) {
      throw new Error(this.options.errors.resetPasswordLinkUnknownAddress);
    }
 
    const password = await this.hashAndBcryptPassword(newPassword);
    // Change the user password and remove the old token
    await this.db.setResetPassword(user.id, resetTokenRecord.address, password, token);
 
    // If user clicked on an enrollment link we can verify his email
    if (resetTokenRecord.reason === 'enroll') {
      await this.db.verifyEmail(user.id, resetTokenRecord.address);
    }
 
    // Changing the password should invalidate existing sessions
    this.db.invalidateAllSessions(user.id);
  }
 
  /**
   * @description Change the password for a user.
   * @param {string} userId - User id.
   * @param {string} newPassword - A new password for the user.
   * @returns {Promise<void>} - Return a Promise.
   */
  public async setPassword(userId: string, newPassword: string): Promise<void> {
    const password = await bcryptPassword(newPassword);
    return this.db.setPassword(userId, password);
  }
 
  /**
   * @description Change the current user's password.
   * @param {string} userId - User id.
   * @param {string} oldPassword - The user's current password.
   * @param {string} newPassword - A new password for the user.
   * @returns {Promise<void>} - Return a Promise.
   */
  public async changePassword(
    userId: string,
    oldPassword: string,
    newPassword: string
  ): Promise<void> {
    await this.passwordAuthenticator({ id: userId }, oldPassword);
    const password = await bcryptPassword(newPassword);
    return this.db.setPassword(userId, password);
  }
 
  /**
   * @description Send an email with a link the user can use verify their email address.
   * @param {string} [address] - Which address of the user's to send the email to.
   * This address must be in the user's emails list.
   * Defaults to the first unverified email in the list.
   * @returns {Promise<void>} - Return a Promise.
   */
  public async sendVerificationEmail(address: string): Promise<void> {
    if (!address || !isString(address)) {
      throw new Error(this.options.errors.invalidEmail);
    }
 
    const user = await this.db.findUserByEmail(address);
    if (!user) {
      // To prevent user enumeration we fail silently
      Iif (this.server.options.ambiguousErrorMessages) {
        return;
      }
      throw new Error(this.options.errors.userNotFound);
    }
    const token = generateRandomToken();
    await this.db.addEmailVerificationToken(user.id, address, token);
 
    const resetPasswordMail = this.server.prepareMail(
      address,
      token,
      this.server.sanitizeUser(user),
      'verify-email',
      this.server.options.emailTemplates.verifyEmail,
      this.server.options.emailTemplates.from
    );
 
    await this.server.options.sendMail(resetPasswordMail);
  }
 
  /**
   * @description Send an email with a link the user can use to reset their password.
   * @param {string} [address] - Which address of the user's to send the email to.
   * This address must be in the user's emails list.
   * Defaults to the first email in the list.
   * @returns {Promise<void>} - Return a Promise.
   */
  public async sendResetPasswordEmail(address: string): Promise<void> {
    if (!address || !isString(address)) {
      throw new Error(this.options.errors.invalidEmail);
    }
 
    const user = await this.db.findUserByEmail(address);
    if (!user) {
      // To prevent user enumeration we fail silently
      Iif (this.server.options.ambiguousErrorMessages) {
        return;
      }
      throw new Error(this.options.errors.userNotFound);
    }
    const token = generateRandomToken();
    await this.db.addResetPasswordToken(user.id, address, token, 'reset');
 
    const resetPasswordMail = this.server.prepareMail(
      address,
      token,
      this.server.sanitizeUser(user),
      'reset-password',
      this.server.options.emailTemplates.resetPassword,
      this.server.options.emailTemplates.from
    );
 
    await this.server.options.sendMail(resetPasswordMail);
  }
 
  /**
   * @description Send an email with a link the user can use to set their initial password.
   * The user's email will be verified after clicking on the link.
   * @param {string} [address] - Which address of the user's to send the email to.
   * This address must be in the user's emails list.
   * Defaults to the first email in the list.
   * @returns {Promise<void>} - Return a Promise.
   */
  public async sendEnrollmentEmail(address: string): Promise<void> {
    if (!address || !isString(address)) {
      throw new Error(this.options.errors.invalidEmail);
    }
 
    const user = await this.db.findUserByEmail(address);
    if (!user) {
      throw new Error(this.options.errors.userNotFound);
    }
    const token = generateRandomToken();
    await this.db.addResetPasswordToken(user.id, address, token, 'enroll');
 
    const enrollmentMail = this.server.prepareMail(
      address,
      token,
      this.server.sanitizeUser(user),
      'enroll-account',
      this.server.options.emailTemplates.enrollAccount,
      this.server.options.emailTemplates.from
    );
 
    await this.server.options.sendMail(enrollmentMail);
  }
 
  /**
   * @description Create a new user.
   * @param user - The user object.
   * @returns Return the id of user created.
   */
  public async createUser(user: PasswordCreateUserType): Promise<string> {
    if (!this.options.validateUsername(user.username) && !this.options.validateEmail(user.email)) {
      throw new Error(this.options.errors.usernameOrEmailRequired);
    }
 
    if (user.username && (await this.db.findUserByUsername(user.username))) {
      throw new Error(this.options.errors.usernameAlreadyExists);
    }
 
    if (user.email && (await this.db.findUserByEmail(user.email))) {
      throw new Error(this.options.errors.emailAlreadyExists);
    }
 
    if (user.password) {
      Iif (!this.options.validatePassword(user.password)) {
        throw new Error(this.options.errors.invalidPassword);
      }
      user.password = await this.hashAndBcryptPassword(user.password);
    }
 
    // If user does not provide the validate function only allow some fields
    user = this.options.validateNewUser
      ? await this.options.validateNewUser(user)
      : pick(user, ['username', 'email', 'password']);
 
    try {
      const userId = await this.db.createUser(user);
 
      defer(async () => {
        const userRecord = (await this.db.findUserById(userId)) as User;
        this.server.getHooks().emit(ServerHooks.CreateUserSuccess, userRecord);
      });
 
      return userId;
    } catch (e) {
      await this.server.getHooks().emit(ServerHooks.CreateUserError, user);
      throw e;
    }
  }
 
  public isTokenExpired(tokenRecord: TokenRecord, expiryDate: number): boolean {
    return Number(tokenRecord.when) + expiryDate < Date.now();
  }
 
  private async passwordAuthenticator(
    user: string | LoginUserIdentity,
    password: PasswordType
  ): Promise<User> {
    const { username, email, id } = isString(user)
      ? this.toUsernameAndEmail({ user })
      : this.toUsernameAndEmail({ ...user });
 
    let foundUser: User | null;
 
    if (id) {
      // this._validateLoginWithField('id', user);
      foundUser = await this.db.findUserById(id);
    } else if (username) {
      // this._validateLoginWithField('username', user);
      foundUser = await this.db.findUserByUsername(username);
    } else if (email) {
      // this._validateLoginWithField('email', user);
      foundUser = await this.db.findUserByEmail(email);
    }
 
    // @ts-ignore
    if (!foundUser) {
      throw new Error(
        this.server.options.ambiguousErrorMessages
          ? this.options.errors.invalidCredentials
          : this.options.errors.userNotFound
      );
    }
 
    const hash = await this.db.findPasswordHash(foundUser.id);
    if (!hash) {
      throw new Error(this.options.errors.noPasswordSet);
    }
 
    const hashAlgorithm = this.options.passwordHashAlgorithm;
    const pass: any = hashAlgorithm ? hashPassword(password, hashAlgorithm) : password;
    const isPasswordValid = await verifyPassword(pass, hash);
 
    Eif (!isPasswordValid) {
      throw new Error(this.options.errors.incorrectPassword);
    }
 
    return foundUser;
  }
 
  private async hashAndBcryptPassword(password: PasswordType): Promise<string> {
    const hashAlgorithm = this.options.passwordHashAlgorithm;
    const hashedPassword: any = hashAlgorithm ? hashPassword(password, hashAlgorithm) : password;
    return bcryptPassword(hashedPassword);
  }
 
  /**
   * Given a username, user and/or email figure out the username and/or email.
   *
   * @param user An object containing at least `username`, `user` and/or `email`.
   * @returns An object containing `id`, `username` and `email`.
   */
  private toUsernameAndEmail({ user, username, email, id }: any): any {
    Eif (user && !username && !email) {
      Eif (isEmail(user)) {
        email = user;
        username = null;
      } else {
        username = user;
        email = null;
      }
    }
    return { username, email, id };
  }
}