users.js 21.3 KB
Newer Older
1 2 3 4 5
/* global WIKI */

const bcrypt = require('bcryptjs-then')
const _ = require('lodash')
const tfa = require('node-2fa')
6
const jwt = require('jsonwebtoken')
7
const Model = require('objection').Model
8
const validate = require('validate.js')
9 10 11 12 13 14 15 16 17 18 19 20

const bcryptRegexp = /^\$2[ayb]\$[0-9]{2}\$[A-Za-z0-9./]{53}$/

/**
 * Users model
 */
module.exports = class User extends Model {
  static get tableName() { return 'users' }

  static get jsonSchema () {
    return {
      type: 'object',
21
      required: ['email'],
22 23 24 25 26

      properties: {
        id: {type: 'integer'},
        email: {type: 'string', format: 'email'},
        name: {type: 'string', minLength: 1, maxLength: 255},
27
        providerId: {type: 'string'},
28 29 30
        password: {type: 'string'},
        tfaIsActive: {type: 'boolean', default: false},
        tfaSecret: {type: 'string'},
31 32 33
        jobTitle: {type: 'string'},
        location: {type: 'string'},
        pictureUrl: {type: 'string'},
34
        isSystem: {type: 'boolean'},
35 36
        isActive: {type: 'boolean'},
        isVerified: {type: 'boolean'},
37 38 39 40 41 42 43 44 45 46
        createdAt: {type: 'string'},
        updatedAt: {type: 'string'}
      }
    }
  }

  static get relationMappings() {
    return {
      groups: {
        relation: Model.ManyToManyRelation,
47
        modelClass: require('./groups'),
48 49 50 51 52 53 54 55
        join: {
          from: 'users.id',
          through: {
            from: 'userGroups.userId',
            to: 'userGroups.groupId'
          },
          to: 'groups.id'
        }
NGPixel's avatar
NGPixel committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
      },
      provider: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./authentication'),
        join: {
          from: 'users.providerKey',
          to: 'authentication.key'
        }
      },
      defaultEditor: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./editors'),
        join: {
          from: 'users.editorKey',
          to: 'editors.key'
        }
      },
      locale: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./locales'),
        join: {
          from: 'users.localeCode',
          to: 'locales.code'
        }
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      }
    }
  }

  async $beforeUpdate(opt, context) {
    await super.$beforeUpdate(opt, context)

    this.updatedAt = new Date().toISOString()

    if (!(opt.patch && this.password === undefined)) {
      await this.generateHash()
    }
  }
  async $beforeInsert(context) {
    await super.$beforeInsert(context)

    this.createdAt = new Date().toISOString()
    this.updatedAt = new Date().toISOString()

    await this.generateHash()
  }

102 103 104 105
  // ------------------------------------------------
  // Instance Methods
  // ------------------------------------------------

106 107 108 109 110 111 112 113
  async generateHash() {
    if (this.password) {
      if (bcryptRegexp.test(this.password)) { return }
      this.password = await bcrypt.hash(this.password, 12)
    }
  }

  async verifyPassword(pwd) {
114
    if (await bcrypt.compare(pwd, this.password) === true) {
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
      return true
    } else {
      throw new WIKI.Error.AuthLoginFailed()
    }
  }

  async enableTFA() {
    let tfaInfo = tfa.generateSecret({
      name: WIKI.config.site.title
    })
    return this.$query.patch({
      tfaIsActive: true,
      tfaSecret: tfaInfo.secret
    })
  }

  async disableTFA() {
    return this.$query.patch({
      tfaIsActive: false,
      tfaSecret: ''
    })
  }

  async verifyTFA(code) {
    let result = tfa.verifyToken(this.tfaSecret, code)
    return (result && _.has(result, 'delta') && result.delta === 0)
  }

143 144 145 146 147 148
  getGlobalPermissions() {
    return _.uniq(_.flatten(_.map(this.groups, 'permissions')))
  }

  getGroups() {
    return _.uniq(_.map(this.groups, 'id'))
149 150
  }

151 152 153 154
  // ------------------------------------------------
  // Model Methods
  // ------------------------------------------------

155 156 157 158 159 160
  static async processProfile({ profile, providerKey }) {
    const provider = _.get(WIKI.auth.strategies, providerKey, {})
    provider.info = _.find(WIKI.data.authentication, ['key', providerKey])

    // Find existing user
    let user = await WIKI.models.users.query().findOne({
Nick's avatar
Nick committed
161
      providerId: _.toString(profile.id),
162 163 164 165
      providerKey
    })

    // Parse email
166 167
    let primaryEmail = ''
    if (_.isArray(profile.emails)) {
Nick's avatar
Nick committed
168
      const e = _.find(profile.emails, ['primary', true])
169 170 171 172 173 174 175 176
      primaryEmail = (e) ? e.value : _.first(profile.emails).value
    } else if (_.isString(profile.email) && profile.email.length > 5) {
      primaryEmail = profile.email
    } else if (_.isString(profile.mail) && profile.mail.length > 5) {
      primaryEmail = profile.mail
    } else if (profile.user && profile.user.email && profile.user.email.length > 5) {
      primaryEmail = profile.user.email
    } else {
177
      throw new Error('Missing or invalid email address from profile.')
178 179 180
    }
    primaryEmail = _.toLower(primaryEmail)

181 182 183 184 185 186 187 188 189 190 191 192 193 194
    // Find pending social user
    if (!user) {
      user = await WIKI.models.users.query().findOne({
        email: primaryEmail,
        providerId: null,
        providerKey
      })
      if (user) {
        user = await user.$query().patchAndFetch({
          providerId: _.toString(profile.id)
        })
      }
    }

195 196 197 198 199 200 201 202 203 204 205
    // Parse display name
    let displayName = ''
    if (_.isString(profile.displayName) && profile.displayName.length > 0) {
      displayName = profile.displayName
    } else if (_.isString(profile.name) && profile.name.length > 0) {
      displayName = profile.name
    } else {
      displayName = primaryEmail.split('@')[0]
    }

    // Parse picture URL
206 207 208 209
    let pictureUrl = _.truncate(_.get(profile, 'picture', _.get(user, 'pictureUrl', null)), {
      length: 255,
      omission: ''
    })
210 211

    // Update existing user
212
    if (user) {
213 214 215 216 217 218 219 220
      if (!user.isActive) {
        throw new WIKI.Error.AuthAccountBanned()
      }
      if (user.isSystem) {
        throw new Error('This is a system reserved account and cannot be used.')
      }

      user = await user.$query().patchAndFetch({
221
        email: primaryEmail,
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        name: displayName,
        pictureUrl: pictureUrl
      })

      return user
    }

    // Self-registration
    if (provider.selfRegistration) {
      // Check if email domain is whitelisted
      if (_.get(provider, 'domainWhitelist', []).length > 0) {
        const emailDomain = _.last(primaryEmail.split('@'))
        if (!_.includes(provider.domainWhitelist, emailDomain)) {
          throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
        }
      }

      // Create account
      user = await WIKI.models.users.query().insertAndFetch({
        providerKey: providerKey,
Nick's avatar
Nick committed
242
        providerId: _.toString(profile.id),
243 244 245 246 247 248 249 250 251
        email: primaryEmail,
        name: displayName,
        pictureUrl: pictureUrl,
        localeCode: WIKI.config.lang.code,
        defaultEditor: 'markdown',
        tfaIsActive: false,
        isSystem: false,
        isActive: true,
        isVerified: true
252
      })
253 254 255 256 257 258 259

      // Assign to group(s)
      if (provider.autoEnrollGroups.length > 0) {
        await user.$relatedQuery('groups').relate(provider.autoEnrollGroups)
      }

      return user
260 261
    }

262
    throw new Error('You are not authorized to login.')
263 264 265
  }

  static async login (opts, context) {
NGPixel's avatar
NGPixel committed
266
    if (_.has(WIKI.auth.strategies, opts.strategy)) {
Nick's avatar
Nick committed
267 268 269 270 271 272 273
      const strInfo = _.find(WIKI.data.authentication, ['key', opts.strategy])

      // Inject form user/pass
      if (strInfo.useForm) {
        _.set(context.req, 'body.email', opts.username)
        _.set(context.req, 'body.password', opts.password)
      }
274 275 276

      // Authenticate
      return new Promise((resolve, reject) => {
Nick's avatar
Nick committed
277 278
        WIKI.auth.passport.authenticate(opts.strategy, {
          session: !strInfo.useForm,
279
          scope: strInfo.scopes ? strInfo.scopes : null
Nick's avatar
Nick committed
280
        }, async (err, user, info) => {
281 282 283
          if (err) { return reject(err) }
          if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }

284 285 286 287 288 289 290 291 292 293 294 295
          // Must Change Password?
          if (user.mustChangePwd) {
            try {
              const pwdChangeToken = await WIKI.models.userKeys.generateToken({
                kind: 'changePwd',
                userId: user.id
              })

              return resolve({
                mustChangePwd: true,
                continuationToken: pwdChangeToken
              })
Nick's avatar
Nick committed
296 297
            } catch (errc) {
              WIKI.logger.warn(errc)
298 299 300 301
              return reject(new WIKI.Error.AuthGenericError())
            }
          }

302 303 304
          // Is 2FA required?
          if (user.tfaIsActive) {
            try {
305 306 307 308
              const tfaToken = await WIKI.models.userKeys.generateToken({
                kind: 'tfa',
                userId: user.id
              })
309 310
              return resolve({
                tfaRequired: true,
311
                continuationToken: tfaToken
312
              })
Nick's avatar
Nick committed
313 314
            } catch (errc) {
              WIKI.logger.warn(errc)
315 316 317
              return reject(new WIKI.Error.AuthGenericError())
            }
          }
318

Nick's avatar
Nick committed
319 320
          context.req.logIn(user, { session: !strInfo.useForm }, async errc => {
            if (errc) { return reject(errc) }
321 322 323
            const jwtToken = await WIKI.models.users.refreshToken(user)
            resolve({ jwt: jwtToken.token })
          })
324 325 326 327 328 329 330
        })(context.req, context.res, () => {})
      })
    } else {
      throw new WIKI.Error.AuthProviderInvalid()
    }
  }

331 332
  static async refreshToken(user) {
    if (_.isSafeInteger(user)) {
NGPixel's avatar
NGPixel committed
333
      user = await WIKI.models.users.query().findById(user).withGraphFetched('groups').modifyGraph('groups', builder => {
334 335
        builder.select('groups.id', 'permissions')
      })
336 337 338 339
      if (!user) {
        WIKI.logger.warn(`Failed to refresh token for user ${user}: Not found.`)
        throw new WIKI.Error.AuthGenericError()
      }
340
    } else if (_.isNil(user.groups)) {
NGPixel's avatar
NGPixel committed
341
      user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions')
342
    }
343

344 345 346
    // Update Last Login Date
    await WIKI.models.users.query().findById(user.id).patch({ lastLoginAt: new Date().toISOString() })

347 348 349 350 351 352 353 354 355
    return {
      token: jwt.sign({
        id: user.id,
        email: user.email,
        name: user.name,
        pictureUrl: user.pictureUrl,
        timezone: user.timezone,
        localeCode: user.localeCode,
        defaultEditor: user.defaultEditor,
356 357
        permissions: user.getGlobalPermissions(),
        groups: user.getGroups()
358 359 360 361 362
      }, {
        key: WIKI.config.certs.private,
        passphrase: WIKI.config.sessionSecret
      }, {
        algorithm: 'RS256',
363 364
        expiresIn: WIKI.config.auth.tokenExpiration,
        audience: WIKI.config.auth.audience,
365 366 367 368 369 370
        issuer: 'urn:wiki.js'
      }),
      user
    }
  }

371
  static async loginTFA (opts, context) {
372
    if (opts.securityCode.length === 6 && opts.loginToken.length === 64) {
373
      let result = await WIKI.redis.get(`tfa:${opts.loginToken}`)
374 375 376
      if (result) {
        let userId = _.toSafeInteger(result)
        if (userId && userId > 0) {
377
          let user = await WIKI.models.users.query().findById(userId)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
          if (user && user.verifyTFA(opts.securityCode)) {
            return Promise.fromCallback(clb => {
              context.req.logIn(user, clb)
            }).return({
              succeeded: true,
              message: 'Login Successful'
            }).catch(err => {
              WIKI.logger.warn(err)
              throw new WIKI.Error.AuthGenericError()
            })
          } else {
            throw new WIKI.Error.AuthTFAFailed()
          }
        }
      }
    }
    throw new WIKI.Error.AuthTFAInvalid()
  }
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
  /**
   * Change Password from a Mandatory Password Change after Login
   */
  static async loginChangePassword ({ continuationToken, newPassword }, context) {
    if (!newPassword || newPassword.length < 6) {
      throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
    }
    const usr = await WIKI.models.userKeys.validateToken({
      kind: 'changePwd',
      token: continuationToken
    })

    if (usr) {
      await WIKI.models.users.query().patch({
        password: newPassword,
        mustChangePwd: false
      }).findById(usr.id)

      return new Promise((resolve, reject) => {
        context.req.logIn(usr, { session: false }, async err => {
          if (err) { return reject(err) }
          const jwtToken = await WIKI.models.users.refreshToken(usr)
          resolve({ jwt: jwtToken.token })
        })
      })
    } else {
      throw new WIKI.Error.UserNotFound()
    }
  }

Nick's avatar
Nick committed
427 428 429 430 431
  /**
   * Create a new user
   *
   * @param {Object} param0 User Fields
   */
432 433 434 435 436
  static async createNewUser ({ providerKey, email, passwordRaw, name, groups, mustChangePassword, sendWelcomeEmail }) {
    // Input sanitization
    email = _.toLower(email)

    // Input validation
437 438 439 440 441 442 443 444 445 446 447 448
    let validation = null
    if (providerKey === 'local') {
      validation = validate({
        email,
        passwordRaw,
        name
      }, {
        email: {
          email: true,
          length: {
            maximum: 255
          }
449
        },
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        passwordRaw: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 6
          }
        },
        name: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 2,
            maximum: 255
          }
466
        }
467 468 469 470 471 472 473 474 475 476 477
      }, { format: 'flat' })
    } else {
      validation = validate({
        email,
        name
      }, {
        email: {
          email: true,
          length: {
            maximum: 255
          }
478
        },
479 480 481 482 483 484 485 486
        name: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 2,
            maximum: 255
          }
487
        }
488 489 490
      }, { format: 'flat' })
    }

491 492 493 494 495 496 497 498
    if (validation && validation.length > 0) {
      throw new WIKI.Error.InputInvalid(validation[0])
    }

    // Check if email already exists
    const usr = await WIKI.models.users.query().findOne({ email, providerKey })
    if (!usr) {
      // Create the account
499 500
      let newUsrData = {
        providerKey,
501 502 503 504 505 506 507 508
        email,
        name,
        locale: 'en',
        defaultEditor: 'markdown',
        tfaIsActive: false,
        isSystem: false,
        isActive: true,
        isVerified: true,
509 510 511 512 513 514 515 516 517
        mustChangePwd: false
      }

      if (providerKey === `local`) {
        newUsrData.password = passwordRaw
        newUsrData.mustChangePwd = (mustChangePassword === true)
      }

      const newUsr = await WIKI.models.users.query().insert(newUsrData)
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544

      // Assign to group(s)
      if (groups.length > 0) {
        await newUsr.$relatedQuery('groups').relate(groups)
      }

      if (sendWelcomeEmail) {
        // Send welcome email
        await WIKI.mail.send({
          template: 'accountWelcome',
          to: email,
          subject: `Welcome to the wiki ${WIKI.config.title}`,
          data: {
            preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
            title: `You've been invited to the wiki ${WIKI.config.title}`,
            content: `Click the button below to access the wiki.`,
            buttonLink: `${WIKI.config.host}/login`,
            buttonText: 'Login'
          },
          text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
        })
      }
    } else {
      throw new WIKI.Error.AuthAccountAlreadyExists()
    }
  }

Nick's avatar
Nick committed
545 546 547 548 549 550 551 552 553 554 555 556 557
  /**
   * Update an existing user
   *
   * @param {Object} param0 User ID and fields to update
   */
  static async updateUser ({ id, email, name, newPassword, groups, location, jobTitle, timezone }) {
    const usr = await WIKI.models.users.query().findById(id)
    if (usr) {
      let usrData = {}
      if (!_.isEmpty(email) && email !== usr.email) {
        const dupUsr = await WIKI.models.users.query().select('id').where({
          email,
          providerKey: usr.providerKey
558
        }).first()
Nick's avatar
Nick committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572
        if (dupUsr) {
          throw new WIKI.Error.AuthAccountAlreadyExists()
        }
        usrData.email = email
      }
      if (!_.isEmpty(name) && name !== usr.name) {
        usrData.name = _.trim(name)
      }
      if (!_.isEmpty(newPassword)) {
        if (newPassword.length < 6) {
          throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
        }
        usrData.password = newPassword
      }
573
      if (_.isArray(groups)) {
Nick's avatar
Nick committed
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        const usrGroupsRaw = await usr.$relatedQuery('groups')
        const usrGroups = _.map(usrGroupsRaw, 'id')
        // Relate added groups
        const addUsrGroups = _.difference(groups, usrGroups)
        for (const grp of addUsrGroups) {
          await usr.$relatedQuery('groups').relate(grp)
        }
        // Unrelate removed groups
        const remUsrGroups = _.difference(usrGroups, groups)
        for (const grp of remUsrGroups) {
          await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
        }
      }
      if (!_.isEmpty(location) && location !== usr.location) {
        usrData.location = _.trim(location)
      }
      if (!_.isEmpty(jobTitle) && jobTitle !== usr.jobTitle) {
        usrData.jobTitle = _.trim(jobTitle)
      }
      if (!_.isEmpty(timezone) && timezone !== usr.timezone) {
        usrData.timezone = timezone
      }
      await WIKI.models.users.query().patch(usrData).findById(id)
    } else {
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
      throw new WIKI.Error.UserNotFound()
    }
  }

  /**
   * Delete a User
   *
   * @param {*} id User ID
   */
  static async deleteUser (id) {
    const usr = await WIKI.models.users.query().findById(id)
    if (usr) {
      await WIKI.models.userKeys.query().delete().where('userId', id)
      await WIKI.models.users.query().deleteById(id)
    } else {
Nick's avatar
Nick committed
613 614 615 616 617 618 619 620 621 622
      throw new WIKI.Error.UserNotFound()
    }
  }

  /**
   * Register a new user (client-side registration)
   *
   * @param {Object} param0 User fields
   * @param {Object} context GraphQL Context
   */
623
  static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
624 625
    const localStrg = await WIKI.models.authentication.getStrategy('local')
    // Check if self-registration is enabled
626 627 628 629
    if (localStrg.selfRegistration || bypassChecks) {
      // Input sanitization
      email = _.toLower(email)

630 631
      // Input validation
      const validation = validate({
632 633
        email,
        password,
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        name
      }, {
        email: {
          email: true,
          length: {
            maximum: 255
          }
        },
        password: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 6
          }
        },
        name: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 2,
            maximum: 255
          }
658
        }
659 660 661 662 663 664
      }, { format: 'flat' })
      if (validation && validation.length > 0) {
        throw new WIKI.Error.InputInvalid(validation[0])
      }

      // Check if email domain is whitelisted
665
      if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
666 667 668 669 670 671 672 673 674
        const emailDomain = _.last(email.split('@'))
        if (!_.includes(localStrg.domainWhitelist.v, emailDomain)) {
          throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
        }
      }
      // Check if email already exists
      const usr = await WIKI.models.users.query().findOne({ email, providerKey: 'local' })
      if (!usr) {
        // Create the account
675
        const newUsr = await WIKI.models.users.query().insert({
676 677 678 679 680 681 682
          provider: 'local',
          email,
          name,
          password,
          locale: 'en',
          defaultEditor: 'markdown',
          tfaIsActive: false,
683 684 685 686 687
          isSystem: false,
          isActive: true,
          isVerified: false
        })

688 689 690 691 692
        // Assign to group(s)
        if (_.get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
          await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
        }

693 694 695 696 697 698
        if (verify) {
          // Create verification token
          const verificationToken = await WIKI.models.userKeys.generateToken({
            kind: 'verify',
            userId: newUsr.id
          })
699

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
          // Send verification email
          await WIKI.mail.send({
            template: 'accountVerify',
            to: email,
            subject: 'Verify your account',
            data: {
              preheadertext: 'Verify your account in order to gain access to the wiki.',
              title: 'Verify your account',
              content: 'Click the button below in order to verify your account and gain access to the wiki.',
              buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
              buttonText: 'Verify'
            },
            text: `You must open the following link in your browser to verify your account and gain access to the wiki: ${WIKI.config.host}/verify/${verificationToken}`
          })
        }
715 716 717 718
        return true
      } else {
        throw new WIKI.Error.AuthAccountAlreadyExists()
      }
719
    } else {
720
      throw new WIKI.Error.AuthRegistrationDisabled()
721 722
    }
  }
723 724

  static async getGuestUser () {
725
    const user = await WIKI.models.users.query().findById(2).withGraphJoined('groups').modifyGraph('groups', builder => {
726 727 728 729 730 731
      builder.select('groups.id', 'permissions')
    })
    if (!user) {
      WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
      process.exit(1)
    }
732
    user.permissions = user.getGlobalPermissions()
733 734
    return user
  }
735 736 737 738 739 740 741 742 743 744

  static async getRootUser () {
    let user = await WIKI.models.users.query().findById(1)
    if (!user) {
      WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
      process.exit(1)
    }
    user.permissions = ['manage:system']
    return user
  }
745
}