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

const Model = require('objection').Model
4 5
const { DateTime } = require('luxon')
const { nanoid } = require('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

/**
 * 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)

44
    this.createdAt = DateTime.utc().toISO()
45 46 47
  }

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

58
  static async validateToken ({ kind, token, skipDelete }, context) {
59
    const res = await WIKI.models.userKeys.query().findOne({ kind, token }).withGraphJoined('user')
60
    if (res) {
61 62 63 64
      if (skipDelete !== true) {
        await WIKI.models.userKeys.query().deleteById(res.id)
      }
      if (DateTime.utc() > DateTime.fromISO(res.validUntil)) {
65 66 67 68 69 70 71
        throw new WIKI.Error.AuthValidationTokenInvalid()
      }
      return res.user
    } else {
      throw new WIKI.Error.AuthValidationTokenInvalid()
    }
  }
72 73 74 75

  static async destroyToken ({ token }) {
    return WIKI.models.userKeys.query().findOne({ token }).delete()
  }
76
}