Files
wiki/server/models/apiKeys.mjs
T

76 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-02-22 17:38:06 -05:00
/* global WIKI */
2023-04-08 07:42:35 +00:00
import { Model } from 'objection'
import { DateTime } from 'luxon'
import ms from 'ms'
import jwt from 'jsonwebtoken'
2020-02-22 17:38:06 -05:00
/**
* Users model
*/
2023-04-08 07:42:35 +00:00
export class ApiKey extends Model {
2020-02-22 17:38:06 -05:00
static get tableName() { return 'apiKeys' }
static get jsonSchema () {
return {
type: 'object',
required: ['name', 'key'],
properties: {
2022-07-31 07:15:40 +00:00
id: {type: 'string'},
2020-02-22 17:38:06 -05:00
name: {type: 'string'},
key: {type: 'string'},
expiration: {type: 'string'},
isRevoked: {type: 'boolean'},
createdAt: {type: 'string'},
validUntil: {type: 'string'}
}
}
}
async $beforeUpdate(opt, context) {
await super.$beforeUpdate(opt, context)
2022-07-31 07:15:40 +00:00
this.updatedAt = new Date().toISOString()
2020-02-22 17:38:06 -05:00
}
async $beforeInsert(context) {
await super.$beforeInsert(context)
2022-07-31 07:15:40 +00:00
this.createdAt = new Date().toISOString()
this.updatedAt = new Date().toISOString()
2020-02-22 17:38:06 -05:00
}
2022-07-31 07:15:40 +00:00
static async createNewKey ({ name, expiration, groups }) {
console.info(DateTime.utc().plus(ms(expiration)).toISO())
const entry = await WIKI.db.apiKeys.query().insert({
2020-02-22 17:38:06 -05:00
name,
key: 'pending',
2022-07-31 07:15:40 +00:00
expiration: DateTime.utc().plus(ms(expiration)).toISO(),
2020-02-22 17:38:06 -05:00
isRevoked: true
})
2022-07-31 07:15:40 +00:00
console.info(entry)
2020-02-22 17:38:06 -05:00
const key = jwt.sign({
api: entry.id,
2022-07-31 07:15:40 +00:00
grp: groups
2020-02-22 17:38:06 -05:00
}, {
2022-07-31 07:15:40 +00:00
key: WIKI.config.auth.certs.private,
passphrase: WIKI.config.auth.secret
2020-02-22 17:38:06 -05:00
}, {
algorithm: 'RS256',
expiresIn: expiration,
audience: WIKI.config.auth.audience,
issuer: 'urn:wiki.js'
})
await WIKI.db.apiKeys.query().findById(entry.id).patch({
2020-02-22 17:38:06 -05:00
key,
isRevoked: false
})
return key
}
}