users.js 12.6 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 securityHelper = require('../helpers/security')
7
const jwt = require('jsonwebtoken')
8
const Model = require('objection').Model
9
const validate = require('validate.js')
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

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',
      required: ['email', 'name', 'provider'],

      properties: {
        id: {type: 'integer'},
        email: {type: 'string', format: 'email'},
        name: {type: 'string', minLength: 1, maxLength: 255},
        providerId: {type: 'number'},
        password: {type: 'string'},
        role: {type: 'string', enum: ['admin', 'guest', 'user']},
        tfaIsActive: {type: 'boolean', default: false},
        tfaSecret: {type: 'string'},
33 34 35
        jobTitle: {type: 'string'},
        location: {type: 'string'},
        pictureUrl: {type: 'string'},
36
        isSystem: {type: 'boolean'},
37 38
        isActive: {type: 'boolean'},
        isVerified: {type: 'boolean'},
39 40 41 42 43 44 45 46 47 48
        createdAt: {type: 'string'},
        updatedAt: {type: 'string'}
      }
    }
  }

  static get relationMappings() {
    return {
      groups: {
        relation: Model.ManyToManyRelation,
49
        modelClass: require('./groups'),
50 51 52 53 54 55 56 57
        join: {
          from: 'users.id',
          through: {
            from: 'userGroups.userId',
            to: 'userGroups.groupId'
          },
          to: 'groups.id'
        }
NGPixel's avatar
NGPixel committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
      },
      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'
        }
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
      }
    }
  }

  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()
  }

104 105 106 107
  // ------------------------------------------------
  // Instance Methods
  // ------------------------------------------------

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

  async verifyPassword(pwd) {
116
    if (await bcrypt.compare(pwd, this.password) === true) {
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
      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)
  }

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

  getGroups() {
    return _.uniq(_.map(this.groups, 'id'))
151 152
  }

153 154 155 156
  // ------------------------------------------------
  // Model Methods
  // ------------------------------------------------

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  static async processProfile(profile) {
    let primaryEmail = ''
    if (_.isArray(profile.emails)) {
      let e = _.find(profile.emails, ['primary', true])
      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 {
      return Promise.reject(new Error(WIKI.lang.t('auth:errors.invaliduseremail')))
    }

    profile.provider = _.lowerCase(profile.provider)
    primaryEmail = _.toLower(primaryEmail)

175
    let user = await WIKI.models.users.query().findOne({
176 177 178 179 180 181 182 183 184 185 186
      email: primaryEmail,
      provider: profile.provider
    })
    if (user) {
      user.$query().patchAdnFetch({
        email: primaryEmail,
        provider: profile.provider,
        providerId: profile.id,
        name: profile.displayName || _.split(primaryEmail, '@')[0]
      })
    } else {
187
      user = await WIKI.models.users.query().insertAndFetch({
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        email: primaryEmail,
        provider: profile.provider,
        providerId: profile.id,
        name: profile.displayName || _.split(primaryEmail, '@')[0]
      })
    }

    // Handle unregistered accounts
    // if (!user && profile.provider !== 'local' && (WIKI.config.auth.defaultReadAccess || profile.provider === 'ldap' || profile.provider === 'azure')) {
    //   let nUsr = {
    //     email: primaryEmail,
    //     provider: profile.provider,
    //     providerId: profile.id,
    //     password: '',
    //     name: profile.displayName || profile.name || profile.cn,
    //     rights: [{
    //       role: 'read',
    //       path: '/',
    //       exact: false,
    //       deny: false
    //     }]
    //   }
210
    //   return WIKI.models.users.query().insert(nUsr)
211 212 213 214 215 216
    // }

    return user
  }

  static async login (opts, context) {
NGPixel's avatar
NGPixel committed
217
    if (_.has(WIKI.auth.strategies, opts.strategy)) {
218 219 220 221 222
      _.set(context.req, 'body.email', opts.username)
      _.set(context.req, 'body.password', opts.password)

      // Authenticate
      return new Promise((resolve, reject) => {
223
        WIKI.auth.passport.authenticate(opts.strategy, { session: false }, async (err, user, info) => {
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
          if (err) { return reject(err) }
          if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }

          // Is 2FA required?
          if (user.tfaIsActive) {
            try {
              let loginToken = await securityHelper.generateToken(32)
              await WIKI.redis.set(`tfa:${loginToken}`, user.id, 'EX', 600)
              return resolve({
                tfaRequired: true,
                tfaLoginToken: loginToken
              })
            } catch (err) {
              WIKI.logger.warn(err)
              return reject(new WIKI.Error.AuthGenericError())
            }
          } else {
            // No 2FA, log in user
242
            return context.req.logIn(user, { session: false }, async err => {
243
              if (err) { return reject(err) }
244
              const jwtToken = await WIKI.models.users.refreshToken(user)
245
              resolve({
246
                jwt: jwtToken.token,
247 248 249 250 251 252 253 254 255 256 257
                tfaRequired: false
              })
            })
          }
        })(context.req, context.res, () => {})
      })
    } else {
      throw new WIKI.Error.AuthProviderInvalid()
    }
  }

258 259
  static async refreshToken(user) {
    if (_.isSafeInteger(user)) {
260 261 262
      user = await WIKI.models.users.query().findById(user).eager('groups').modifyEager('groups', builder => {
        builder.select('groups.id', 'permissions')
      })
263 264 265 266
      if (!user) {
        WIKI.logger.warn(`Failed to refresh token for user ${user}: Not found.`)
        throw new WIKI.Error.AuthGenericError()
      }
267 268
    } else if(_.isNil(user.groups)) {
      await user.$relatedQuery('groups').select('groups.id', 'permissions')
269
    }
270

271 272 273 274 275 276 277 278 279
    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,
280 281
        permissions: user.getGlobalPermissions(),
        groups: user.getGroups()
282 283 284 285 286
      }, {
        key: WIKI.config.certs.private,
        passphrase: WIKI.config.sessionSecret
      }, {
        algorithm: 'RS256',
287 288
        expiresIn: WIKI.config.auth.tokenExpiration,
        audience: WIKI.config.auth.audience,
289 290 291 292 293 294
        issuer: 'urn:wiki.js'
      }),
      user
    }
  }

295 296
  static async loginTFA(opts, context) {
    if (opts.securityCode.length === 6 && opts.loginToken.length === 64) {
297
      let result = null // await WIKI.redis.get(`tfa:${opts.loginToken}`)
298 299 300
      if (result) {
        let userId = _.toSafeInteger(result)
        if (userId && userId > 0) {
301
          let user = await WIKI.models.users.query().findById(userId)
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
          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()
  }
320

321
  static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
322 323
    const localStrg = await WIKI.models.authentication.getStrategy('local')
    // Check if self-registration is enabled
324 325 326 327
    if (localStrg.selfRegistration || bypassChecks) {
      // Input sanitization
      email = _.toLower(email)

328 329
      // Input validation
      const validation = validate({
330 331
        email,
        password,
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
        name
      }, {
        email: {
          email: true,
          length: {
            maximum: 255
          }
        },
        password: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 6
          }
        },
        name: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 2,
            maximum: 255
          }
        },
      }, { format: 'flat' })
      if (validation && validation.length > 0) {
        throw new WIKI.Error.InputInvalid(validation[0])
      }

      // Check if email domain is whitelisted
363
      if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
364 365 366 367 368 369 370 371 372
        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
373
        const newUsr = await WIKI.models.users.query().insert({
374 375 376 377 378 379 380
          provider: 'local',
          email,
          name,
          password,
          locale: 'en',
          defaultEditor: 'markdown',
          tfaIsActive: false,
381 382 383 384 385
          isSystem: false,
          isActive: true,
          isVerified: false
        })

386 387 388 389 390 391
        if (verify) {
          // Create verification token
          const verificationToken = await WIKI.models.userKeys.generateToken({
            kind: 'verify',
            userId: newUsr.id
          })
392

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
          // 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}`
          })
        }
408 409 410 411
        return true
      } else {
        throw new WIKI.Error.AuthAccountAlreadyExists()
      }
412
    } else {
413
      throw new WIKI.Error.AuthRegistrationDisabled()
414 415
    }
  }
416 417

  static async getGuestUser () {
418 419 420 421 422 423 424
    const user = await WIKI.models.users.query().findById(2).eager('groups').modifyEager('groups', builder => {
      builder.select('groups.id', 'permissions')
    })
    if (!user) {
      WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
      process.exit(1)
    }
425 426
    return user
  }
427
}