All files / src user-store.js

96.34% Statements 79/82
90.62% Branches 29/32
100% Functions 33/33
98.71% Lines 77/78

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    1x 1x   1x                                     31x 31x                                                   31x   31x 31x   31x                           32x                           10x   9x                       22x   21x               6x                               10x   10x 8x   7x   7x   7x     7x                         1x   1x 1x   1x   1x   1x         11x 2x 2x 2x         9x 1x 1x 1x                       8x   8x   8x 1x     8x                     3x   3x 2x 2x   1x   3x 3x                         1x       1x   1x                       7x 4x 4x 4x   3x                       6x   6x   6x   1x     5x                       1x   1x   1x         1x                                 9x 9x 9x 9x                                     2x 2x 2x 2x 1x   1x           1x 1x  
'use strict'
 
const KVPFileStore = require('kvplus-files')
const bcrypt = require('bcryptjs')
 
const DEFAULT_SALT_ROUNDS = 10
 
class UserStore {
  /**
   * @constructor
   *
   * @param [options={}] {Object} Options hashmap
   * @param [options.path] {string} Directory path where the various collections
   *   (users etc) will be stored.
   *
   * @param [options.saltRounds] {number} Number of `bcrypt` password hash
   *   salt rounds.
   * @see https://www.npmjs.com/package/bcrypt
   *
   * @param [options.backend] {KVPFileStore} Optional Key/Value file store
   *   (will be initialized if not passed in).
   * @see https://github.com/solid/kvplus-files
   */
  constructor (options) {
    this.backend = options.backend
    this.saltRounds = options.saltRounds
  }
 
  /**
   * Factory method, constructs a UserStore instance from passed in options.
   * Usage:
   *
   *   ```
   *   let options = {
   *     path: './db/users',
   *     saltRounds: 10
   *   }
   *   let store = UserStore.from(options)
   *   ```
   *
   * @param options {Object} Options hashmap
   *
   * @param options.path {string} Directory path where the various collections
   *   (users etc) will be stored. Used to initialize a backend.
   *
   * @param [options.saltRounds] {number} Number of `bcrypt` password hash
   *   salt rounds.
   *
   * @return {UserStore}
   */
  static from (options) {
    options.saltRounds = options.saltRounds || DEFAULT_SALT_ROUNDS
 
    const storeOptions = UserStore.backendOptionsFor(options.path)
    options.backend = new KVPFileStore(storeOptions)
 
    return new UserStore(options)
  }
 
  /**
   * Constructs and returns options for initializing a default KVPFileStore
   * instance.
   *
   * @param path {string} Directory path where the various collections
   *   (users etc) will be stored. Used to initialize a backend if it's not
   *   explicitly passed in.
   *
   * @return {Object}
   */
  static backendOptionsFor (path) {
    return {
      path,
      collections: ['users', 'users-by-email']
    }
  }
 
  /**
   * Creates and returns an fs-safe filename key from an email.
   *
   * @param email {string|null}
   *
   * @return {string|null}
   */
  static normalizeEmailKey (email) {
    if (!email) { return null }
 
    return encodeURIComponent(email)
  }
 
  /**
   * Creates and returns an fs-safe filename key from an id string (which can
   * be an http URI).
   *
   * @param id {string|null}
   *
   * @return {string|null}
   */
  static normalizeIdKey (id) {
    if (!id) { return null }
 
    return encodeURIComponent(id)
  }
 
  /**
   * Initializes the backend store's collections (if using a file-system based
   * backend, this creates directories for each collection).
   */
  initCollections () {
    this.backend.initCollections()
  }
 
  /**
   * Generates a salted password hash, saves user credentials to the 'users'
   * collection, and makes an index entry into the 'users-by-email' collection
   * if applicable.
   *
   * @param user {UserAccount} User account currently being created
   * @param password {string} User's login password
   *
   * @throws {TypeError} HTTP 400 errors if required parameters are missing.
   *
   * @return {Promise<Object>} Resolves to stored user object hashmap
   */
  createUser (user, password) {
    return Promise.resolve()
      .then(() => {
        this.validateUser(user)
        this.validatePassword(password)
      })
      .then(() => this.hashPassword(password))
      .then(hashedPassword => {
        user.hashedPassword = hashedPassword
 
        return this.saveUser(user)
      })
      .then(() => {
        return this.saveUserByEmail(user)
      })
  }
 
  /**
   * Updates (overwrites) a user record with the new password.
   *
   * @param user {UserAccount}
   * @param password {string}
   *
   * @return {Promise}
   */
  updatePassword (user, password) {
    return Promise.resolve()
      .then(() => {
        this.validateUser(user)
        this.validatePassword(password)
      })
      .then(() => this.hashPassword(password))
      .then(hashedPassword => {
        user.hashedPassword = hashedPassword
 
        return this.saveUser(user)
      })
  }
 
  validateUser (user) {
    if (!user || !user.id) {
      const error = new TypeError('No user id provided to user store')
      error.status = 400
      throw error
    }
  }
 
  validatePassword (password) {
    if (!password) {
      const error = new TypeError('No password provided')
      error.status = 400
      throw error
    }
  }
 
  /**
   * Saves a serialized user object to the 'users' collection.
   *
   * @param user {UserAccount}
   *
   * @return {Promise}
   */
  saveUser (user) {
    const userKey = UserStore.normalizeIdKey(user.id)
 
    return Promise.resolve()
      .then(() => {
        if (user.localAccountId) {
          return this.saveAliasUserRecord(user.localAccountId, user.id)
        }
      })
      .then(() => this.backend.put('users', userKey, user))
  }
  /**
   * Permanently deletes the files of a user
   *
   * @param user {UserAccount}
   *
   * @return {Promise}
   */
 
  deleteUser (user) {
    const userKey = UserStore.normalizeIdKey(user.id)
    let deletedEmail
    if (user.email) {
      const emailKey = UserStore.normalizeEmailKey(user.email)
      deletedEmail = this.backend.del('users-by-email', emailKey)
    } else {
      deletedEmail = Promise.reject(new Error('No email given'))
    }
    const deletedUser = this.backend.del('users', userKey)
    return Promise.all([deletedEmail, deletedUser])
  }
 
  /**
   * Saves an "alias" user object, used for linking local account IDs to
   * external Web IDs.
   *
   * @param fromId {string}
   * @param toId {string}
   *
   * @returns {Promise}
   */
  saveAliasUserRecord (fromId, toId) {
    const aliasRecord = {
      link: toId
    }
 
    const aliasKey = UserStore.normalizeIdKey(fromId)
 
    return this.backend.put('users', aliasKey, aliasRecord)
  }
 
  /**
   * Creates an entry for the user id in the 'users-by-email' index, if
   * applicable.
   *
   * @param user {UserAccount}
   *
   * @return {Promise}
   */
  saveUserByEmail (user) {
    if (user.email) {
      const userByEmail = { id: user.id }
      const key = UserStore.normalizeEmailKey(user.email)
      return this.backend.put('users-by-email', key, userByEmail)
    } else {
      return Promise.resolve()
    }
  }
 
  /**
   * Loads and returns a user object for a given id.
   *
   * @param userId {string}
   *
   * @return {Promise<Object>} User info, parsed from a JSON string
   */
  findUser (userId) {
    const userKey = UserStore.normalizeIdKey(userId)
 
    return this.backend.get('users', userKey)
      .then(user => {
        if (user && user.link) {
          // this is an alias record, fetch the user it points to
          return this.findUser(user.link)
        }
 
        return user
      })
  }
 
  /**
   * Loads and returns a user object for a given email.
   *
   * @param email {string}
   *
   * @return {Promise<Object>} User info, parsed from a JSON string
   */
  findUserByEmail (email) {
    const emailKey = UserStore.normalizeEmailKey(email)
 
    return this.backend.get('users-by-email', emailKey)
      .then(user => {
        Iif (user && user.link) {
          // this is an alias record, fetch the user it points to
          return this.findUser(user.link)
        }
 
        return user
      })
  }
 
  /**
   * Creates and returns a salted password hash, for storage with the user
   * record.
   *
   * @see https://www.npmjs.com/package/bcrypt
   *
   * @param plaintextPassword {string}
   *
   * @throws {Error}
   *
   * @return {Promise<string>} Combined salt and password hash, bcrypt style
   */
  hashPassword (plaintextPassword) {
    return new Promise((resolve, reject) => {
      bcrypt.hash(plaintextPassword, this.saltRounds, (err, hashedPassword) => {
        Iif (err) { return reject(err) }
        resolve(hashedPassword)
      })
    })
  }
 
  /**
   * Returns the user object if the plaintext password matches the stored hash,
   * and returns a `null` if there is no match.
   *
   * @param user {UserAccount}
   * @param user.hashedPassword {string} Created by a previous call to
   *   `hashPassword()` and stored in the user object.
   *
   * @param plaintextPassword {string} For example, submitted by a user from a
   *   login form.
   *
   * @return {Promise<UserAccount|null>}
   */
  matchPassword (user, plaintextPassword) {
    return new Promise((resolve, reject) => {
      bcrypt.compare(plaintextPassword, user.hashedPassword, (err, res) => {
        Iif (err) { return reject(err) }
        if (res) { // password matches
          return resolve(user)
        }
        return resolve(null)
      })
    })
  }
}
 
module.exports = UserStore
module.exports.DEFAULT_SALT_ROUNDS = DEFAULT_SALT_ROUNDS