userKeys.js 1.64 KB
Newer Older
1 2 3 4
/* global WIKI */

const Model = require('objection').Model
const moment = require('moment')
5
const nanoid = require('nanoid').nanoid
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

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

  static get jsonSchema () {
    return {
      type: 'object',
      required: ['kind', 'token', 'validUntil'],

      properties: {
        id: {type: 'integer'},
        kind: {type: 'string'},
        token: {type: 'string'},
        createdAt: {type: 'string'},
        validUntil: {type: 'string'}
      }
    }
  }

  static get relationMappings() {
    return {
      user: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./users'),
        join: {
          from: 'userKeys.userId',
          to: 'users.id'
        }
      }
    }
  }

  async $beforeInsert(context) {
    await super.$beforeInsert(context)

    this.createdAt = moment.utc().toISOString()
  }

  static async generateToken ({ userId, kind }, context) {
48
    const token = nanoid()
49 50 51 52 53 54 55 56 57 58
    await WIKI.models.userKeys.query().insert({
      kind,
      token,
      validUntil: moment.utc().add(1, 'days').toISOString(),
      userId
    })
    return token
  }

  static async validateToken ({ kind, token }, context) {
59
    const res = await WIKI.models.userKeys.query().findOne({ kind, token }).withGraphJoined('user')
60 61 62 63 64 65 66 67 68 69 70
    if (res) {
      await WIKI.models.userKeys.query().deleteById(res.id)
      if (moment.utc().isAfter(moment.utc(res.validUntil))) {
        throw new WIKI.Error.AuthValidationTokenInvalid()
      }
      return res.user
    } else {
      throw new WIKI.Error.AuthValidationTokenInvalid()
    }
  }
}