memory_adapter.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const LRU = require('lru-cache');
  2. const epochTime = require('../helpers/epoch_time');
  3. let storage = new LRU({});
  4. function grantKeyFor(id) {
  5. return `grant:${id}`;
  6. }
  7. function sessionUidKeyFor(id) {
  8. return `sessionUid:${id}`;
  9. }
  10. function userCodeKeyFor(userCode) {
  11. return `userCode:${userCode}`;
  12. }
  13. class MemoryAdapter {
  14. constructor(model) {
  15. this.model = model;
  16. }
  17. key(id) {
  18. return `${this.model}:${id}`;
  19. }
  20. async destroy(id) {
  21. const key = this.key(id);
  22. storage.del(key);
  23. }
  24. async consume(id) {
  25. storage.get(this.key(id)).consumed = epochTime();
  26. }
  27. async find(id) {
  28. return storage.get(this.key(id));
  29. }
  30. async findByUid(uid) {
  31. const id = storage.get(sessionUidKeyFor(uid));
  32. return this.find(id);
  33. }
  34. async findByUserCode(userCode) {
  35. const id = storage.get(userCodeKeyFor(userCode));
  36. return this.find(id);
  37. }
  38. async upsert(id, payload, expiresIn) {
  39. const key = this.key(id);
  40. if (this.model === 'Session') {
  41. storage.set(sessionUidKeyFor(payload.uid), id, expiresIn * 1000);
  42. }
  43. const { grantId, userCode } = payload;
  44. if (grantId) {
  45. const grantKey = grantKeyFor(grantId);
  46. const grant = storage.get(grantKey);
  47. if (!grant) {
  48. storage.set(grantKey, [key]);
  49. } else {
  50. grant.push(key);
  51. }
  52. }
  53. if (userCode) {
  54. storage.set(userCodeKeyFor(userCode), id, expiresIn * 1000);
  55. }
  56. storage.set(key, payload, expiresIn * 1000);
  57. }
  58. async revokeByGrantId(grantId) { // eslint-disable-line class-methods-use-this
  59. const grantKey = grantKeyFor(grantId);
  60. const grant = storage.get(grantKey);
  61. if (grant) {
  62. grant.forEach((token) => storage.del(token));
  63. storage.del(grantKey);
  64. }
  65. }
  66. }
  67. module.exports = MemoryAdapter;
  68. module.exports.setStorage = (store) => { storage = store; };