apiKeys.mjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* global WIKI */
  2. import { Model } from 'objection'
  3. import { DateTime } from 'luxon'
  4. import ms from 'ms'
  5. import jwt from 'jsonwebtoken'
  6. /**
  7. * Users model
  8. */
  9. export 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: 'string'},
  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 = new Date().toISOString()
  29. }
  30. async $beforeInsert(context) {
  31. await super.$beforeInsert(context)
  32. this.createdAt = new Date().toISOString()
  33. this.updatedAt = new Date().toISOString()
  34. }
  35. static async createNewKey ({ name, expiration, groups }) {
  36. console.info(DateTime.utc().plus(ms(expiration)).toISO())
  37. const entry = await WIKI.db.apiKeys.query().insert({
  38. name,
  39. key: 'pending',
  40. expiration: DateTime.utc().plus(ms(expiration)).toISO(),
  41. isRevoked: true
  42. })
  43. console.info(entry)
  44. const key = jwt.sign({
  45. api: entry.id,
  46. grp: groups
  47. }, {
  48. key: WIKI.config.auth.certs.private,
  49. passphrase: WIKI.config.auth.secret
  50. }, {
  51. algorithm: 'RS256',
  52. expiresIn: expiration,
  53. audience: WIKI.config.auth.audience,
  54. issuer: 'urn:wiki.js'
  55. })
  56. await WIKI.db.apiKeys.query().findById(entry.id).patch({
  57. key,
  58. isRevoked: false
  59. })
  60. return key
  61. }
  62. }