All files / node-user-accounts-boilerplate-nahid/auth EmailAuth.js

91.67% Statements 99/108
82.28% Branches 65/79
90% Functions 9/10
91.67% Lines 99/108

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    2x 2x 2x   2x   2x   2x 2x                               7x                 7x             7x             7x             7x   7x 7x         7x             7x             7x     7x                             7x               7x         3x 3x   3x       3x                                   7x   7x   2x         2x   2x 2x 2x 2x 2x 2x 2x 2x       5x   3x   3x   3x     3x   2x       1x       3x       2x               3x                 3x   3x   3x       3x 3x   3x 3x 3x 3x   1x               3x         3x 3x                                 5x   5x       5x                   5x   3x                 6x   6x   4x     6x                       4x   4x   2x     4x                               7x   7x     2x 2x   2x 2x   3x 3x     7x   7x   7x   2x   5x   1x     4x   1x 1x 1x       3x 3x   7x 7x 7x 7x 7x   7x       2x  
"use strict";
 
const audit = require('../helper/audit');
const failureImpl = require('../restriction/failure');
const generatePassword = require('../fields/strongPassword')
  .generate;
const json = require('body-parser')
  .json();
const recaptchaImpl = require('../restriction/recaptcha');
 
const Auth = require('./Auth');
const LocalStrategy = require('passport-local');
 
/**
 * Email based login.
 *
 * Requies ```passport-local``` package.
 */
class EmailAuth extends Auth
{
 
  /**
   * @param {object} options see Auth class + additional options for email configuration.
   * @property {number} [options.tokenExpxiryMinutes=10] number of minutes to restrict token exchange to for passwordless login
   */
  constructor(options)
  {
    super('email', options);
 
    /**
     * Instance of email sender class for sending emails.
     *
     * If this is not specified, email login is disabled.
     *
     * @type {EmailSender}
     */
    this.emailSender = options.emailSender;
 
    /**
     * Instance of crypt class for encrypting and verifying passwords.
     *
     * @type {Crypt}
     */
    this.crypt = options.crypt;
 
    /**
     * Name of application.
     * Used for sending email.
     * @type {string}
     */
    this.applicationName = options.applicationName || 'Account';
 
    /**
     * Email from address
     * Used for sending email.
     * @type {string}
     */
    this.fromAddress = options.fromAddress || 'no-thanks@reply-factory.com';
 
    this.description.usesPassword = true;
    this.description.tokenExpiryMinutes = options.tokenExpiryMinutes || 10;
 
    /**
     * @private
     */
    this.tokenExpiryMilliseconds = this.description.tokenExpiryMinutes * 60 * 1000;
 
    /**
     * Settings for rate limiting failed requests.
     *
     * Note: use this or recaptcha.
     */
    this.block = options.block || undefined;
 
    /**
     * Settings for rate limiting through recaptcha.
     *
     * Note: use this or recaptcha.
     */
    this.recaptcha = options.recaptcha || undefined;
 
 
    Iif (this.recaptcha)
    {
      if (this.recaptcha.publicKey)
      {
        this.description.recaptcha = this.recaptcha.publicKey;
      }
      else
      {
        this.recaptcha = undefined;
      }
    }
 
    /**
     * If true, it remembers any passwords specified registration.
     */
    this.allowPasswordSettingDuringRegistration = options.allowPasswordSettingDuringRegistration || false;
  }
 
  /**
   * logs users in based on token or based on username(email)/password
   */
  async strategyImpl(req, username, password, done)
  {
    const defaultErrorMsg = this.defaultErrorMsg;
 
    // call if unsuccessful
    function error(msg, detailed = undefined)
    {
      req.audit(audit.LOGIN_FAILURE, msg, detailed);
      Eif (typeof msg === 'string')
      {
        msg = {
          error: defaultErrorMsg || msg
        };
      }
      done(null, msg);
    }
 
    // expire aged tokens
    // const now = Date.now();
 
    // // passwordless login
    // if (tokens[username])
    // {
    //   if (tokens[username].password === password)
    //   {
    //     const profile = await this.createProfileFromCredential(username, tokens[username].extra);
    //
    //     delete tokens[username];
    //
    //     this.handleUserLoginByProfile(username, profile, done, req);
    //   }
    // }
    const user = this.findUser(username);
 
    if (user && user.loginToken)
    {
      Iif (Date.now() > user.loginToken.expires)
      {
        delete user.loginToken;
        await this.users.updateRecord(user);
      }
      else Eif (user.loginToken.password === password)
      {
        const profile = await this.createProfileFromCredential(username, user.loginToken.extra);
        const update = this.createUserFromProfile(profile);
        delete user.loginToken;
        delete update.id;
        Object.assign(user, update);
        await this.users.updateRecord(user);
        done(null, user);
        return
      }
    }
 
    if (user && user.credentials) // if found, log in found account
    {
      for (let credential of user.credentials)
      {
        Eif (credential.type === this.method && credential.value === username && user.password)
        {
          this.crypt.verify(password, user.password)
            .then((verified) =>
            {
              if (verified)
              {
                done(null, user);
              }
              else
              {
                error('Email and password combination not found.', username);
              }
            }, done);
 
          return;
        }
      }
    }
    error('Email and password combination not found.', username);
  }
 
  /**
   * sends temporary login password to email address
   */
  async passwordlessImpl(req, res)
  {
    const defaultErrorMsg = this.defaultErrorMsg;
 
    // call if unsuccessful
    function error(msg, auditStr, detailed = undefined)
    {
      req.audit(auditStr, msg, detailed);
      return res.error(defaultErrorMsg || msg, audit.LOGIN_FAILURE);
    }
 
    try
    {
      const username = req.body.username;
 
      Iif (!req.body.username || typeof req.body.username !== 'string')
      {
        return error('Username not specified', audit.LOGIN_FAILURE, req.body);
      }
      const temporaryPassword = generatePassword();
      const theme = req.params.theme || 'login';
 
      await this.sendTemporaryPassword(theme, username, temporaryPassword, this.description.tokenExpiryMinutes, req.body.loginLinkPrefix);
      let user = this.findUser(username);
      let update = user ? this.users.updateRecord : this.users.createRecord;
      if (!user)
      {
        user = {
          id: this.generateId(),
          credentials: [{
            type: 'email',
            value: username
          }]
        };
      }
      user.loginToken = {
        password: temporaryPassword,
        expires: Date.now() + this.tokenExpiryMilliseconds,
        extra: req.body,
      };
      await update.call(this.users, user);
      res.success('A login email has been sent to email address.', audit.LOGIN, username);
    }
    catch (e)
    {
      error('Error sending email. Please verify that your address is correct and is valid.', audit.LOGIN_FAILURE, e);
    }
  }
 
  /**
   * @override
   */
  install(app, prefix, passport)
  {
    // Protect methods with restriction.
    // Verify does not need it as we are doing simple memory lookup in  small
    // sized table. May still be an issue unless we receive enough registrations
    // to fill up memory.
    const limit = this.block ? failureImpl(this.block) : recaptchaImpl(this.recaptcha);
 
    passport.use(new LocalStrategy({
      passReqToCallback: true,
    }, this.strategyImpl.bind(this)));
 
    app.all([`${prefix}/login.json`,
        `${prefix}/verify.json`
      ],
      json,
      limit,
      passport.authenticate('local', this.authenticateOptions),
      this.loggedIn());
 
    // PASSWORDLESS LOGIN
 
    if (this.emailSender)
    {
      app.all(`${prefix}/:theme.json`, json, limit, this.passwordlessImpl.bind(this));
    }
  }
 
  /**
   * helper method that creates a profile object from a credential address
   */
  async createProfileFromCredential(id, extra = {})
  {
    const profile = await super.createProfileFromCredential(id, extra);
 
    if (extra.password && this.crypt)
    {
      profile.password = await this.crypt.hash(extra.password);
    }
 
    return profile;
  }
 
  /**
   * Override of helper method that inserts password into produced user
   * if allowed by setting.
   *
   * @override
   */
  createUserFromProfile(profile)
  {
    // we allow password setting
    let user = super.createUserFromProfile(profile);
 
    if (profile.password && this.allowPasswordSettingDuringRegistration)
    {
      user.password = profile.password;
    }
 
    return user;
  }
 
  /**
   * Helper method that sends temporary password to an email address for rego/login.
   *
   * Should be able to override this to specify custom formats for email.
   *
   * @param {string} theme register | recover | passwordless etc. anything other than login or verify
   * @param {string} to target email address
   * @param {string} password temporary login token
   * @param {number} expireMinutes number of minutes after which this login token will expire
   * @param {string} [loginLinkPrefix] forward url for any links in email
   */
  sendTemporaryPassword(theme, to, password, expireMinutes, loginLinkPrefix)
  {
    let subject = `${this.applicationName}`;
 
    switch (theme)
    {
    case 'register':
      subject += ' Registration';
      break;
    case 'recover':
      subject += ' Account Recovery';
      break;
    default:
      subject += ' Login';
      break;
    }
 
    let message = '';
 
    message += `<p>You have received this email because someone requested access to the ${this.applicationName} using this email address.</p>\n`;
 
    if (theme === 'register' && loginLinkPrefix)
    {
      message += `<p>Use the following link to verify this email address and complete your registration: <a href="${loginLinkPrefix}${password}">verify</a>.</p>\n`;
    }
    else if (theme === 'recover' && loginLinkPrefix)
    {
      message += `<p>Use the following link to log into the system to change your password: <a href="${loginLinkPrefix}${password}">login</a>.</p>\n`;
    }
    else
    if (loginLinkPrefix)
    {
      message += `<p>Use the following link to log into the system: <a href="${loginLinkPrefix}${password}">login</a>.</p>\n`;
      message += `<p>Alternatively, you can use the following password: ${password}</p>\n`;
      message += `<p>Note: this link and password will expire within ${expireMinutes} minutes of request time.</p>\n`;
    }
    else
    {
      message += `<p>Use the following password to log into the system: ${password}</p>\n`;
      message += `<p>Note: this password will expire within ${expireMinutes} minutes of request time.</p>\n`;
    }
    message += `<p>If this is not you, please contact system administrators.</p>\n`;
    message += `<p>Kind Regards,</p>\n`;
    message += `<p>${this.applicationName} Team</p>\n`;
    message += `<p></p>\n`;
    message += `<p>WARNING: This is an automaticly generated email. Do not reploy to it.</p>\n`;
 
    return this.emailSender.send(to, this.fromAddress, subject, message);
  }
}
 
module.exports = EmailAuth;