session-management.e2e-spec.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /* tslint:disable:no-non-null-assertion */
  2. import { CachedSession, mergeConfig, SessionCacheStrategy } from '@vendure/core';
  3. import { createTestEnvironment } from '@vendure/testing';
  4. import gql from 'graphql-tag';
  5. import path from 'path';
  6. import { initialData } from '../../../e2e-common/e2e-initial-data';
  7. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  8. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '../../common/src/shared-constants';
  9. import {
  10. AttemptLoginMutation,
  11. AttemptLoginMutationVariables,
  12. MeQuery,
  13. } from './graphql/generated-e2e-admin-types';
  14. import { ATTEMPT_LOGIN, ME } from './graphql/shared-definitions';
  15. const testSessionCache = new Map<string, CachedSession>();
  16. const getSpy = jest.fn();
  17. const setSpy = jest.fn();
  18. const clearSpy = jest.fn();
  19. const deleteSpy = jest.fn();
  20. class TestingSessionCacheStrategy implements SessionCacheStrategy {
  21. clear() {
  22. clearSpy();
  23. testSessionCache.clear();
  24. }
  25. delete(sessionToken: string) {
  26. deleteSpy(sessionToken);
  27. testSessionCache.delete(sessionToken);
  28. }
  29. get(sessionToken: string) {
  30. getSpy(sessionToken);
  31. return testSessionCache.get(sessionToken);
  32. }
  33. set(session: CachedSession) {
  34. setSpy(session);
  35. testSessionCache.set(session.token, session);
  36. }
  37. }
  38. describe('Session caching', () => {
  39. const { server, adminClient } = createTestEnvironment(
  40. mergeConfig(testConfig(), {
  41. authOptions: {
  42. sessionCacheStrategy: new TestingSessionCacheStrategy(),
  43. sessionCacheTTL: 2,
  44. },
  45. }),
  46. );
  47. beforeAll(async () => {
  48. await server.init({
  49. initialData,
  50. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  51. customerCount: 1,
  52. });
  53. testSessionCache.clear();
  54. }, TEST_SETUP_TIMEOUT_MS);
  55. afterAll(async () => {
  56. await server.destroy();
  57. });
  58. it('populates the cache on login', async () => {
  59. setSpy.mockClear();
  60. expect(setSpy.mock.calls.length).toBe(0);
  61. expect(testSessionCache.size).toBe(0);
  62. await adminClient.query<AttemptLoginMutation, AttemptLoginMutationVariables>(ATTEMPT_LOGIN, {
  63. username: SUPER_ADMIN_USER_IDENTIFIER,
  64. password: SUPER_ADMIN_USER_PASSWORD,
  65. });
  66. expect(testSessionCache.size).toBe(1);
  67. expect(setSpy.mock.calls.length).toBe(1);
  68. });
  69. it('takes user data from cache on next request', async () => {
  70. getSpy.mockClear();
  71. const { me } = await adminClient.query<MeQuery>(ME);
  72. expect(getSpy.mock.calls.length).toBe(1);
  73. });
  74. it('sets fresh data after TTL expires', async () => {
  75. setSpy.mockClear();
  76. await adminClient.query<MeQuery>(ME);
  77. expect(setSpy.mock.calls.length).toBe(0);
  78. await adminClient.query<MeQuery>(ME);
  79. expect(setSpy.mock.calls.length).toBe(0);
  80. await pause(2000);
  81. await adminClient.query<MeQuery>(ME);
  82. expect(setSpy.mock.calls.length).toBe(1);
  83. });
  84. it('clears cache for that user on logout', async () => {
  85. deleteSpy.mockClear();
  86. expect(deleteSpy.mock.calls.length).toBe(0);
  87. await adminClient.query(
  88. gql`
  89. mutation Logout {
  90. logout {
  91. success
  92. }
  93. }
  94. `,
  95. );
  96. expect(testSessionCache.size).toBe(0);
  97. expect(deleteSpy.mock.calls.length).toBeGreaterThan(0);
  98. });
  99. });
  100. describe('Session expiry', () => {
  101. const { server, adminClient } = createTestEnvironment(
  102. mergeConfig(testConfig(), {
  103. authOptions: {
  104. sessionDuration: '3s',
  105. sessionCacheTTL: 1,
  106. },
  107. }),
  108. );
  109. beforeAll(async () => {
  110. await server.init({
  111. initialData,
  112. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  113. customerCount: 1,
  114. });
  115. await adminClient.asSuperAdmin();
  116. }, TEST_SETUP_TIMEOUT_MS);
  117. afterAll(async () => {
  118. await server.destroy();
  119. });
  120. it('session does not expire with continued use', async () => {
  121. await adminClient.asSuperAdmin();
  122. await pause(1000);
  123. await adminClient.query(ME);
  124. await pause(1000);
  125. await adminClient.query(ME);
  126. await pause(1000);
  127. await adminClient.query(ME);
  128. await pause(1000);
  129. await adminClient.query(ME);
  130. }, 10000);
  131. it('session expires when not used for longer than sessionDuration', async () => {
  132. await adminClient.asSuperAdmin();
  133. await pause(3500);
  134. try {
  135. await adminClient.query(ME);
  136. fail('Should have thrown');
  137. } catch (e: any) {
  138. expect(e.message).toContain('You are not currently authorized to perform this action');
  139. }
  140. }, 10000);
  141. });
  142. function pause(ms: number): Promise<void> {
  143. return new Promise(resolve => setTimeout(resolve, ms));
  144. }