refactor: deps update + 2FA setup + verify
This commit is contained in:
		@@ -44,6 +44,7 @@ type AuthenticationMutation {
 | 
			
		||||
  loginTFA(
 | 
			
		||||
    continuationToken: String!
 | 
			
		||||
    securityCode: String!
 | 
			
		||||
    setup: Boolean
 | 
			
		||||
  ): AuthenticationLoginResponse @rateLimit(limit: 5, duration: 60)
 | 
			
		||||
 | 
			
		||||
  loginChangePassword(
 | 
			
		||||
@@ -108,8 +109,10 @@ type AuthenticationLoginResponse {
 | 
			
		||||
  jwt: String
 | 
			
		||||
  mustChangePwd: Boolean
 | 
			
		||||
  mustProvideTFA: Boolean
 | 
			
		||||
  mustSetupTFA: Boolean
 | 
			
		||||
  continuationToken: String
 | 
			
		||||
  redirect: String
 | 
			
		||||
  tfaQRImage: String
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type AuthenticationRegisterResponse {
 | 
			
		||||
 
 | 
			
		||||
@@ -140,6 +140,7 @@ type User {
 | 
			
		||||
  createdAt: Date!
 | 
			
		||||
  updatedAt: Date!
 | 
			
		||||
  lastLoginAt: Date
 | 
			
		||||
  tfaIsActive: Boolean!
 | 
			
		||||
  groups: [Group]!
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
@@ -185,7 +185,7 @@ module.exports = class Asset extends Model {
 | 
			
		||||
  static async getAssetFromStorage(assetPath, res) {
 | 
			
		||||
    const localLocations = await WIKI.models.storage.getLocalLocations({
 | 
			
		||||
      asset: {
 | 
			
		||||
        path: assetPath,
 | 
			
		||||
        path: assetPath
 | 
			
		||||
      }
 | 
			
		||||
    })
 | 
			
		||||
    for (let location of _.filter(localLocations, location => Boolean(location.path))) {
 | 
			
		||||
 
 | 
			
		||||
@@ -1,8 +1,8 @@
 | 
			
		||||
/* global WIKI */
 | 
			
		||||
 | 
			
		||||
const Model = require('objection').Model
 | 
			
		||||
const moment = require('moment')
 | 
			
		||||
const nanoid = require('nanoid').nanoid
 | 
			
		||||
const { DateTime } = require('luxon')
 | 
			
		||||
const { nanoid } = require('nanoid')
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Users model
 | 
			
		||||
@@ -41,25 +41,27 @@ module.exports = class UserKey extends Model {
 | 
			
		||||
  async $beforeInsert(context) {
 | 
			
		||||
    await super.$beforeInsert(context)
 | 
			
		||||
 | 
			
		||||
    this.createdAt = moment.utc().toISOString()
 | 
			
		||||
    this.createdAt = DateTime.utc().toISO()
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  static async generateToken ({ userId, kind }, context) {
 | 
			
		||||
    const token = nanoid()
 | 
			
		||||
    const token = await nanoid()
 | 
			
		||||
    await WIKI.models.userKeys.query().insert({
 | 
			
		||||
      kind,
 | 
			
		||||
      token,
 | 
			
		||||
      validUntil: moment.utc().add(1, 'days').toISOString(),
 | 
			
		||||
      validUntil: DateTime.utc().plus({ days: 1 }).toISO(),
 | 
			
		||||
      userId
 | 
			
		||||
    })
 | 
			
		||||
    return token
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  static async validateToken ({ kind, token }, context) {
 | 
			
		||||
  static async validateToken ({ kind, token, skipDelete }, context) {
 | 
			
		||||
    const res = await WIKI.models.userKeys.query().findOne({ kind, token }).withGraphJoined('user')
 | 
			
		||||
    if (res) {
 | 
			
		||||
      await WIKI.models.userKeys.query().deleteById(res.id)
 | 
			
		||||
      if (moment.utc().isAfter(moment.utc(res.validUntil))) {
 | 
			
		||||
      if (skipDelete !== true) {
 | 
			
		||||
        await WIKI.models.userKeys.query().deleteById(res.id)
 | 
			
		||||
      }
 | 
			
		||||
      if (DateTime.utc() > DateTime.fromISO(res.validUntil)) {
 | 
			
		||||
        throw new WIKI.Error.AuthValidationTokenInvalid()
 | 
			
		||||
      }
 | 
			
		||||
      return res.user
 | 
			
		||||
@@ -67,4 +69,8 @@ module.exports = class UserKey extends Model {
 | 
			
		||||
      throw new WIKI.Error.AuthValidationTokenInvalid()
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  static async destroyToken ({ token }) {
 | 
			
		||||
    return WIKI.models.userKeys.query().findOne({ token }).delete()
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -6,6 +6,7 @@ const tfa = require('node-2fa')
 | 
			
		||||
const jwt = require('jsonwebtoken')
 | 
			
		||||
const Model = require('objection').Model
 | 
			
		||||
const validate = require('validate.js')
 | 
			
		||||
const qr = require('qr-image')
 | 
			
		||||
 | 
			
		||||
const bcryptRegexp = /^\$2[ayb]\$[0-9]{2}\$[A-Za-z0-9./]{53}$/
 | 
			
		||||
 | 
			
		||||
@@ -118,14 +119,22 @@ module.exports = class User extends Model {
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  async enableTFA() {
 | 
			
		||||
  async generateTFA() {
 | 
			
		||||
    let tfaInfo = tfa.generateSecret({
 | 
			
		||||
      name: WIKI.config.site.title
 | 
			
		||||
      name: WIKI.config.title,
 | 
			
		||||
      account: this.email
 | 
			
		||||
    })
 | 
			
		||||
    return this.$query.patch({
 | 
			
		||||
      tfaIsActive: true,
 | 
			
		||||
    await WIKI.models.users.query().findById(this.id).patch({
 | 
			
		||||
      tfaIsActive: false,
 | 
			
		||||
      tfaSecret: tfaInfo.secret
 | 
			
		||||
    })
 | 
			
		||||
    return qr.imageSync(`otpauth://totp/${WIKI.config.title}:${this.email}?secret=${tfaInfo.secret}`, { type: 'svg' })
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  async enableTFA() {
 | 
			
		||||
    return WIKI.models.users.query().findById(this.id).patch({
 | 
			
		||||
      tfaIsActive: true
 | 
			
		||||
    })
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  async disableTFA() {
 | 
			
		||||
@@ -135,7 +144,7 @@ module.exports = class User extends Model {
 | 
			
		||||
    })
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  async verifyTFA(code) {
 | 
			
		||||
  verifyTFA(code) {
 | 
			
		||||
    let result = tfa.verifyToken(this.tfaSecret, code)
 | 
			
		||||
    return (result && _.has(result, 'delta') && result.delta === 0)
 | 
			
		||||
  }
 | 
			
		||||
@@ -281,55 +290,12 @@ module.exports = class User extends Model {
 | 
			
		||||
          if (err) { return reject(err) }
 | 
			
		||||
          if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }
 | 
			
		||||
 | 
			
		||||
          // Get redirect target
 | 
			
		||||
          user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions', 'redirectOnLogin')
 | 
			
		||||
          let redirect = '/'
 | 
			
		||||
          if (user.groups && user.groups.length > 0) {
 | 
			
		||||
            redirect = user.groups[0].redirectOnLogin
 | 
			
		||||
          try {
 | 
			
		||||
            const resp = await WIKI.models.users.afterLoginChecks(user, context)
 | 
			
		||||
            resolve(resp)
 | 
			
		||||
          } catch (err) {
 | 
			
		||||
            reject(err)
 | 
			
		||||
          }
 | 
			
		||||
 | 
			
		||||
          // 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,
 | 
			
		||||
                redirect
 | 
			
		||||
              })
 | 
			
		||||
            } catch (errc) {
 | 
			
		||||
              WIKI.logger.warn(errc)
 | 
			
		||||
              return reject(new WIKI.Error.AuthGenericError())
 | 
			
		||||
            }
 | 
			
		||||
          }
 | 
			
		||||
 | 
			
		||||
          // Is 2FA required?
 | 
			
		||||
          if (user.tfaIsActive) {
 | 
			
		||||
            try {
 | 
			
		||||
              const tfaToken = await WIKI.models.userKeys.generateToken({
 | 
			
		||||
                kind: 'tfa',
 | 
			
		||||
                userId: user.id
 | 
			
		||||
              })
 | 
			
		||||
              return resolve({
 | 
			
		||||
                tfaRequired: true,
 | 
			
		||||
                continuationToken: tfaToken,
 | 
			
		||||
                redirect
 | 
			
		||||
              })
 | 
			
		||||
            } catch (errc) {
 | 
			
		||||
              WIKI.logger.warn(errc)
 | 
			
		||||
              return reject(new WIKI.Error.AuthGenericError())
 | 
			
		||||
            }
 | 
			
		||||
          }
 | 
			
		||||
 | 
			
		||||
          context.req.logIn(user, { session: !strInfo.useForm }, async errc => {
 | 
			
		||||
            if (errc) { return reject(errc) }
 | 
			
		||||
            const jwtToken = await WIKI.models.users.refreshToken(user)
 | 
			
		||||
            resolve({ jwt: jwtToken.token, redirect })
 | 
			
		||||
          })
 | 
			
		||||
        })(context.req, context.res, () => {})
 | 
			
		||||
      })
 | 
			
		||||
    } else {
 | 
			
		||||
@@ -337,6 +303,79 @@ module.exports = class User extends Model {
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  static async afterLoginChecks (user, context, { skipTFA, skipChangePwd } = { skipTFA: false, skipChangePwd: false }) {
 | 
			
		||||
    // Get redirect target
 | 
			
		||||
    user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions', 'redirectOnLogin')
 | 
			
		||||
    let redirect = '/'
 | 
			
		||||
    if (user.groups && user.groups.length > 0) {
 | 
			
		||||
      redirect = user.groups[0].redirectOnLogin
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Is 2FA required?
 | 
			
		||||
    if (!skipTFA) {
 | 
			
		||||
      if (user.tfaIsActive && user.tfaSecret) {
 | 
			
		||||
        try {
 | 
			
		||||
          const tfaToken = await WIKI.models.userKeys.generateToken({
 | 
			
		||||
            kind: 'tfa',
 | 
			
		||||
            userId: user.id
 | 
			
		||||
          })
 | 
			
		||||
          return {
 | 
			
		||||
            mustProvideTFA: true,
 | 
			
		||||
            continuationToken: tfaToken,
 | 
			
		||||
            redirect
 | 
			
		||||
          }
 | 
			
		||||
        } catch (errc) {
 | 
			
		||||
          WIKI.logger.warn(errc)
 | 
			
		||||
          throw new WIKI.Error.AuthGenericError()
 | 
			
		||||
        }
 | 
			
		||||
      } else if (WIKI.config.auth.enforce2FA || (user.tfaIsActive && !user.tfaSecret)) {
 | 
			
		||||
        try {
 | 
			
		||||
          const tfaQRImage = await user.generateTFA()
 | 
			
		||||
          const tfaToken = await WIKI.models.userKeys.generateToken({
 | 
			
		||||
            kind: 'tfaSetup',
 | 
			
		||||
            userId: user.id
 | 
			
		||||
          })
 | 
			
		||||
          return {
 | 
			
		||||
            mustSetupTFA: true,
 | 
			
		||||
            continuationToken: tfaToken,
 | 
			
		||||
            tfaQRImage,
 | 
			
		||||
            redirect
 | 
			
		||||
          }
 | 
			
		||||
        } catch (errc) {
 | 
			
		||||
          WIKI.logger.warn(errc)
 | 
			
		||||
          throw new WIKI.Error.AuthGenericError()
 | 
			
		||||
        }
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Must Change Password?
 | 
			
		||||
    if (!skipChangePwd && user.mustChangePwd) {
 | 
			
		||||
      try {
 | 
			
		||||
        const pwdChangeToken = await WIKI.models.userKeys.generateToken({
 | 
			
		||||
          kind: 'changePwd',
 | 
			
		||||
          userId: user.id
 | 
			
		||||
        })
 | 
			
		||||
 | 
			
		||||
        return {
 | 
			
		||||
          mustChangePwd: true,
 | 
			
		||||
          continuationToken: pwdChangeToken,
 | 
			
		||||
          redirect
 | 
			
		||||
        }
 | 
			
		||||
      } catch (errc) {
 | 
			
		||||
        WIKI.logger.warn(errc)
 | 
			
		||||
        throw new WIKI.Error.AuthGenericError()
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    return new Promise((resolve, reject) => {
 | 
			
		||||
      context.req.login(user, { session: false }, async errc => {
 | 
			
		||||
        if (errc) { return reject(errc) }
 | 
			
		||||
        const jwtToken = await WIKI.models.users.refreshToken(user)
 | 
			
		||||
        resolve({ jwt: jwtToken.token, redirect })
 | 
			
		||||
      })
 | 
			
		||||
    })
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  static async refreshToken(user) {
 | 
			
		||||
    if (_.isSafeInteger(user)) {
 | 
			
		||||
      user = await WIKI.models.users.query().findById(user).withGraphFetched('groups').modifyGraph('groups', builder => {
 | 
			
		||||
@@ -384,26 +423,21 @@ module.exports = class User extends Model {
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  static async loginTFA (opts, context) {
 | 
			
		||||
    if (opts.securityCode.length === 6 && opts.loginToken.length === 64) {
 | 
			
		||||
      let result = await WIKI.redis.get(`tfa:${opts.loginToken}`)
 | 
			
		||||
      if (result) {
 | 
			
		||||
        let userId = _.toSafeInteger(result)
 | 
			
		||||
        if (userId && userId > 0) {
 | 
			
		||||
          let user = await WIKI.models.users.query().findById(userId)
 | 
			
		||||
          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()
 | 
			
		||||
  static async loginTFA ({ securityCode, continuationToken, setup }, context) {
 | 
			
		||||
    if (securityCode.length === 6 && continuationToken.length > 1) {
 | 
			
		||||
      const user = await WIKI.models.userKeys.validateToken({
 | 
			
		||||
        kind: setup ? 'tfaSetup' : 'tfa',
 | 
			
		||||
        token: continuationToken,
 | 
			
		||||
        skipDelete: setup
 | 
			
		||||
      })
 | 
			
		||||
      if (user) {
 | 
			
		||||
        if (user.verifyTFA(securityCode)) {
 | 
			
		||||
          if (setup) {
 | 
			
		||||
            await user.enableTFA()
 | 
			
		||||
          }
 | 
			
		||||
          return WIKI.models.users.afterLoginChecks(user, context, { skipTFA: true })
 | 
			
		||||
        } else {
 | 
			
		||||
          throw new WIKI.Error.AuthTFAFailed()
 | 
			
		||||
        }
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
 
 | 
			
		||||
@@ -442,7 +442,7 @@ module.exports = () => {
 | 
			
		||||
    WIKI.logger.info('HTTP Server: [ RUNNING ]')
 | 
			
		||||
    WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
 | 
			
		||||
    WIKI.logger.info('')
 | 
			
		||||
    WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/ to complete setup!`)
 | 
			
		||||
    WIKI.logger.info(`Browse to http://YOUR-SERVER-IP:${WIKI.config.port}/ to complete setup!`)
 | 
			
		||||
    WIKI.logger.info('')
 | 
			
		||||
    WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
 | 
			
		||||
  })
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user