You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.6 KiB

  1. /* global WIKI */
  2. const Model = require('objection').Model
  3. const moment = require('moment')
  4. const ms = require('ms')
  5. const jwt = require('jsonwebtoken')
  6. /**
  7. * Users model
  8. */
  9. module.exports = class ApiKey extends Model {
  10. static get tableName() { return 'apiKeys' }
  11. static get jsonSchema () {
  12. return {
  13. type: 'object',
  14. required: ['name', 'key'],
  15. properties: {
  16. id: {type: 'integer'},
  17. name: {type: 'string'},
  18. key: {type: 'string'},
  19. expiration: {type: 'string'},
  20. isRevoked: {type: 'boolean'},
  21. createdAt: {type: 'string'},
  22. validUntil: {type: 'string'}
  23. }
  24. }
  25. }
  26. async $beforeUpdate(opt, context) {
  27. await super.$beforeUpdate(opt, context)
  28. this.updatedAt = moment.utc().toISOString()
  29. }
  30. async $beforeInsert(context) {
  31. await super.$beforeInsert(context)
  32. this.createdAt = moment.utc().toISOString()
  33. this.updatedAt = moment.utc().toISOString()
  34. }
  35. static async createNewKey ({ name, expiration, fullAccess, group }) {
  36. const entry = await WIKI.models.apiKeys.query().insert({
  37. name,
  38. key: 'pending',
  39. expiration: moment.utc().add(ms(expiration), 'ms').toISOString(),
  40. isRevoked: true
  41. })
  42. const key = jwt.sign({
  43. api: entry.id,
  44. grp: fullAccess ? 1 : group
  45. }, {
  46. key: WIKI.config.certs.private,
  47. passphrase: WIKI.config.sessionSecret
  48. }, {
  49. algorithm: 'RS256',
  50. expiresIn: expiration,
  51. audience: WIKI.config.auth.audience,
  52. issuer: 'urn:wiki.js'
  53. })
  54. await WIKI.models.apiKeys.query().findById(entry.id).patch({
  55. key,
  56. isRevoked: false
  57. })
  58. return key
  59. }
  60. }