2018-12-24 06:03:10 +00:00
|
|
|
/* global WIKI */
|
|
|
|
|
|
|
|
const Model = require('objection').Model
|
2020-08-22 23:37:49 +00:00
|
|
|
const { DateTime } = require('luxon')
|
|
|
|
const { nanoid } = require('nanoid')
|
2018-12-24 06:03:10 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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)
|
|
|
|
|
2020-08-22 23:37:49 +00:00
|
|
|
this.createdAt = DateTime.utc().toISO()
|
2018-12-24 06:03:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static async generateToken ({ userId, kind }, context) {
|
2020-08-22 23:37:49 +00:00
|
|
|
const token = await nanoid()
|
2018-12-24 06:03:10 +00:00
|
|
|
await WIKI.models.userKeys.query().insert({
|
|
|
|
kind,
|
|
|
|
token,
|
2020-08-22 23:37:49 +00:00
|
|
|
validUntil: DateTime.utc().plus({ days: 1 }).toISO(),
|
2018-12-24 06:03:10 +00:00
|
|
|
userId
|
|
|
|
})
|
|
|
|
return token
|
|
|
|
}
|
|
|
|
|
2020-08-22 23:37:49 +00:00
|
|
|
static async validateToken ({ kind, token, skipDelete }, context) {
|
2020-01-26 04:29:46 +00:00
|
|
|
const res = await WIKI.models.userKeys.query().findOne({ kind, token }).withGraphJoined('user')
|
2018-12-24 06:03:10 +00:00
|
|
|
if (res) {
|
2020-08-22 23:37:49 +00:00
|
|
|
if (skipDelete !== true) {
|
|
|
|
await WIKI.models.userKeys.query().deleteById(res.id)
|
|
|
|
}
|
|
|
|
if (DateTime.utc() > DateTime.fromISO(res.validUntil)) {
|
2018-12-24 06:03:10 +00:00
|
|
|
throw new WIKI.Error.AuthValidationTokenInvalid()
|
|
|
|
}
|
|
|
|
return res.user
|
|
|
|
} else {
|
|
|
|
throw new WIKI.Error.AuthValidationTokenInvalid()
|
|
|
|
}
|
|
|
|
}
|
2020-08-22 23:37:49 +00:00
|
|
|
|
|
|
|
static async destroyToken ({ token }) {
|
|
|
|
return WIKI.models.userKeys.query().findOne({ token }).delete()
|
|
|
|
}
|
2018-12-24 06:03:10 +00:00
|
|
|
}
|