session-management.e2e-spec.ts 5.1 KB

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