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

77.78% Statements 49/63
67.92% Branches 36/53
81.82% Functions 9/11
77.78% Lines 49/63

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    8x 8x 8x                                           63x                   63x                     63x                       63x             63x             63x                                           63x                         1x                             12x   12x   19x 19x 13x   19x   8x       4x                                                                                             5x         5x                                     5x   3x   2x   2x   1x         5x       5x             5x         6x 6x 6x   6x   6x               6x         6x 6x       6x 6x       6x                       5x         5x       7x   3x 3x         4x             4x             4x               8x  
"use strict";
 
const audit = require('../helper/audit');
const generateId = require('../helper/generateId');
const escape = require('../helper/escape');
 
/**
 * Authenticator/passport strategy wrapper abstraction.
 *
 * I.e. it is the parent class of all auth classes.
 */
class Auth
{
 
  /**
   * @param {string} method
   * @param {object} options common options for all auth classes; see properties
   */
  constructor(method, options)
  {
 
    /**
     * Authentication method name. E.g. 'email' for Email based authentication.
     * This is used as an unique id for various things.
     * @type string
     */
    this.method = method;
 
    /**
     * This is a standard descriptor of this authentication mechanism that is publicly shared.
     * Clients should use this to figure out how to use a login auth from outside.
     *
     * Not directly configurable.
     *
     * @type object
     */
    this.description = {
      method: this.method
    };
 
    /**
     * Additional settings given to passport.authenticate.
     *
     * Not directly configurable.
     *
     * @type object
     */
    this.authenticateOptions = {
      failureMessage: 'login failed',
      badRequestMessage: 'XXX'
    };
 
    /**
     * Users collection.
     *
     * Note: various things all assume that a CachedCollection is being used.
     *
     * @type {CachedCollection}
     */
    this.users = options.users || options.collection;
 
    /**
     * Default roles new registered users should assume.
     *
     * @type {object}
     */
    this.defaultRoles = options.defaultRoles || {};
 
    /**
     * Custom fields
     *
     * @type {object}
     */
    this.custom = options.custom || {};
 
    //~ /**
    //~ * Instance of email sender class for sending emails.
    //~ *
    //~ * @type {EmailSender}
    //~ */
    //~ this.emailSender = options.emailSender;
 
 
    //~ this.defaultNotificationInterval = options.defaultNotificationInterval || -1;
 
    //~ if (options.recaptcha)
    //~ {
    //~ this.description.recaptcha = true;
    //~ }
 
    /**
     * Default error message to return instead of actual errors (security).
     *
     * @type {string}
     */
    this.defaultErrorMsg = options.defaultErrorMsg || undefined;
 
  }
 
  /**
   * Must be overridden to provide implementation of said authentication method.
   * @param {ExpressApplication} app express application
   * @param {string} prefix all route prefix
   * @param {Passport} passport passport class
   * @abstract
   */
  install(app, prefix, passport)
  {
    throw new Error('TODO: ABSTRACT');
  }
 
  /**
   * Helper method that finds an user based on a credential.
   *
   * A credential is something like an email address or a facebook user id.
   *
   * This is something that uniquely identifies an account.
   *
   * @param {string} value
   * @return {User|false}
   */
  findUser(value)
  {
    const users = this.users.lookup;
 
    for (let userId in users)
    {
      let user = users[userId];
      let credentials = (user.credentials || [])
        .filter((credential) => credential.type === this.method && credential.value === value);
 
      if (credentials.length > 0)
      {
        return user;
      }
    }
 
    return false;
  }
 
  /**
   * Helper method for SSO type logins.
   *
   * This method finds existing or creates new accounts basen on profile
   * information returned from oauth partner.
   *
   * @param {string} username unique id
   * @param {Profile} profile unique id
   * @param {Function} done callback to call when our work is done
   * @param {Request} [req] request object
   */
  handleUserLoginByProfile(username, profile, done, req = undefined)
  {
    username = username || profile.id;
    // find an account
    let user = this.findUser(username);
 
    if (user) // if found, log in found account
    {
      done(null, user);
    }
    else // if not found, make a new user and log new user in
    {
      user = this.createUserFromProfile(profile);
      this.users.createRecord(user)
        .then((user) =>
        {
          req && req.audit(audit.ACCOUNT_CREATE, JSON.stringify({
            user,
            profile
          }));
          done(null, user);
        }, done);
    }
  }
 
  /**
   * Helper method that creates an User object from a Profile
   *
   * @param {Profile} profile
   * @return {User}
   */
  createUserFromProfile(profile)
  {
    const credential = {
      type: this.method,
      value: profile.id
    };
 
    let user = {
      // unique id
      // can't use id from profile as these might conflict across login providers
      id: this.generateId(),
      // login credentials
      credentials: [credential],
      // new user roles
      roles: this.defaultRoles,
      // profile bs
      displayName: escape(profile.displayName),
      //~ name: profile.name,
      photos: profile.photos,
      //~ // notification settings
      //~ notifications: [],
      //~ notificationInterval: -1,
      //~ notificationLastSent: 0,
      //~ notificationSubscriptions: {},
    };
 
    for (let field in this.custom)
    {
      if (this.custom[field].derive)
      {
        let value = this.custom[field].derive(profile);
 
        if (value)
        {
          user[field] = value;
        }
      }
    }
 
    Iif (profile._json && profile._json.publicProfileUrl)
    {
      credential.publicUrl = profile._json.publicProfileUrl;
    }
    else Iif (profile._json && profile._json.url)
    {
      credential.publicUrl = profile._json.url;
    }
 
    // console.log(JSON.stringify(profile, null, 2))
 
    return user;
  }
 
  generateId()
  {
    console.log(this)
    let id = undefined;
    while (!id || this.users.lookup[id])
    {
      id = generateId();
    }
    return id;
  }
 
  /**
   * helper method that creates a profile object from a credential address
   */
  async createProfileFromCredential(id, extra = {})
  {
    Iif (!id)
    {
      throw new Error(`id not specified: ${id}`);
    }
    // we don't accept spaces in id
    id = id.replace(/\s+/g, '');
    Iif (!id)
    {
      throw new Error(`id not specified: ${id}`);
    }
    let displayName = extra.displayName || (id.indexOf('@') !== -1 && id.substr(0, id.indexOf('@'))) || id;
    let user = {
      id,
      displayName
    };
    return user;
  }
 
  /**
   * Helper method that produces a middleware to handle successful logged in
   * case.
   *
   * @param {boolean} [redirect=false] redirect based login is used
   * @return {ExpressMiddleware}
   */
  loggedIn(redirect = false)
  {
    Iif (redirect && typeof redirect !== 'string')
    {
      redirect = '/';
    }
 
    return function (req, res)
    {
      // if not req.user.id then it is not a real use
      // i.e. we are forwarding error or custom payload
      if (!req.user.id)
      {
        res.error(req.user.error, audit.LOGIN_FAILURE);
        req.logout();
      }
      else
      {
        // otherwise, we make a fuss about logging in
        res.audit(audit.LOGIN, `Logged in via ${this.method}`, JSON.stringify({
          id: req.user.id,
          displayName: req.user.displayName,
          roles: req.user.roles
        }));
 
        // for redirect based login methods, we redirect back to some url
        Iif (redirect)
        {
          res.redirect(redirect);
        }
        else
        {
          // otherwise we return a login success message
          res.success(`Logged in via ${this.method}`, audit.LOGIN);
        }
      }
    }.bind(this);
  }
 
}
 
module.exports = Auth;