shop-auth.e2e-spec.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. /* tslint:disable:no-non-null-assertion */
  2. import { OnModuleInit } from '@nestjs/common';
  3. import { ErrorCode, RegisterCustomerInput } from '@vendure/common/lib/generated-shop-types';
  4. import { pick } from '@vendure/common/lib/pick';
  5. import {
  6. AccountRegistrationEvent,
  7. EventBus,
  8. EventBusModule,
  9. IdentifierChangeEvent,
  10. IdentifierChangeRequestEvent,
  11. mergeConfig,
  12. PasswordResetEvent,
  13. PasswordValidationStrategy,
  14. RequestContext,
  15. VendurePlugin,
  16. } from '@vendure/core';
  17. import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing';
  18. import { DocumentNode } from 'graphql';
  19. import gql from 'graphql-tag';
  20. import path from 'path';
  21. import { initialData } from '../../../e2e-common/e2e-initial-data';
  22. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  23. import { PasswordValidationError } from '../src/common/error/generated-graphql-shop-errors';
  24. import {
  25. CreateAdministrator,
  26. CreateRole,
  27. GetCustomer,
  28. GetCustomerHistory,
  29. GetCustomerList,
  30. HistoryEntryType,
  31. Permission,
  32. } from './graphql/generated-e2e-admin-types';
  33. import {
  34. CurrentUserShopFragment,
  35. GetActiveCustomer,
  36. RefreshToken,
  37. Register,
  38. RequestPasswordReset,
  39. RequestUpdateEmailAddress,
  40. ResetPassword,
  41. UpdateEmailAddress,
  42. Verify,
  43. } from './graphql/generated-e2e-shop-types';
  44. import {
  45. CREATE_ADMINISTRATOR,
  46. CREATE_ROLE,
  47. GET_CUSTOMER,
  48. GET_CUSTOMER_HISTORY,
  49. GET_CUSTOMER_LIST,
  50. } from './graphql/shared-definitions';
  51. import {
  52. GET_ACTIVE_CUSTOMER,
  53. REFRESH_TOKEN,
  54. REGISTER_ACCOUNT,
  55. REQUEST_PASSWORD_RESET,
  56. REQUEST_UPDATE_EMAIL_ADDRESS,
  57. RESET_PASSWORD,
  58. UPDATE_EMAIL_ADDRESS,
  59. VERIFY_EMAIL,
  60. } from './graphql/shop-definitions';
  61. import { assertThrowsWithMessage } from './utils/assert-throws-with-message';
  62. let sendEmailFn: jest.Mock;
  63. /**
  64. * This mock plugin simulates an EmailPlugin which would send emails
  65. * on the registration & password reset events.
  66. */
  67. @VendurePlugin({
  68. imports: [EventBusModule],
  69. })
  70. class TestEmailPlugin implements OnModuleInit {
  71. constructor(private eventBus: EventBus) {}
  72. onModuleInit() {
  73. this.eventBus.ofType(AccountRegistrationEvent).subscribe(event => {
  74. sendEmailFn(event);
  75. });
  76. this.eventBus.ofType(PasswordResetEvent).subscribe(event => {
  77. sendEmailFn(event);
  78. });
  79. this.eventBus.ofType(IdentifierChangeRequestEvent).subscribe(event => {
  80. sendEmailFn(event);
  81. });
  82. this.eventBus.ofType(IdentifierChangeEvent).subscribe(event => {
  83. sendEmailFn(event);
  84. });
  85. }
  86. }
  87. const successErrorGuard: ErrorResultGuard<{ success: boolean }> = createErrorResultGuard(
  88. input => input.success != null,
  89. );
  90. const currentUserErrorGuard: ErrorResultGuard<CurrentUserShopFragment> = createErrorResultGuard(
  91. input => input.identifier != null,
  92. );
  93. class TestPasswordValidationStrategy implements PasswordValidationStrategy {
  94. validate(ctx: RequestContext, password: string): boolean | string {
  95. if (password === 'test') {
  96. // allow the default seed data password
  97. return true;
  98. }
  99. if (password.length < 8) {
  100. return 'Password must be more than 8 characters';
  101. }
  102. if (password === '12345678') {
  103. return `Don't use 12345678!`;
  104. }
  105. return true;
  106. }
  107. }
  108. describe('Shop auth & accounts', () => {
  109. const { server, adminClient, shopClient } = createTestEnvironment(
  110. mergeConfig(testConfig(), {
  111. plugins: [TestEmailPlugin as any],
  112. authOptions: {
  113. passwordValidationStrategy: new TestPasswordValidationStrategy(),
  114. },
  115. }),
  116. );
  117. beforeAll(async () => {
  118. await server.init({
  119. initialData,
  120. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  121. customerCount: 2,
  122. });
  123. await adminClient.asSuperAdmin();
  124. }, TEST_SETUP_TIMEOUT_MS);
  125. afterAll(async () => {
  126. await server.destroy();
  127. });
  128. describe('customer account creation with deferred password', () => {
  129. const password = 'password';
  130. const emailAddress = 'test1@test.com';
  131. let verificationToken: string;
  132. let newCustomerId: string;
  133. beforeEach(() => {
  134. sendEmailFn = jest.fn();
  135. });
  136. it('does not return error result on email address conflict', async () => {
  137. // To prevent account enumeration attacks
  138. const { customers } = await adminClient.query<GetCustomerList.Query>(GET_CUSTOMER_LIST);
  139. const input: RegisterCustomerInput = {
  140. firstName: 'Duplicate',
  141. lastName: 'Person',
  142. phoneNumber: '123456',
  143. emailAddress: customers.items[0].emailAddress,
  144. };
  145. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  146. REGISTER_ACCOUNT,
  147. {
  148. input,
  149. },
  150. );
  151. successErrorGuard.assertSuccess(registerCustomerAccount);
  152. });
  153. it('register a new account without password', async () => {
  154. const verificationTokenPromise = getVerificationTokenPromise();
  155. const input: RegisterCustomerInput = {
  156. firstName: 'Sean',
  157. lastName: 'Tester',
  158. phoneNumber: '123456',
  159. emailAddress,
  160. };
  161. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  162. REGISTER_ACCOUNT,
  163. {
  164. input,
  165. },
  166. );
  167. successErrorGuard.assertSuccess(registerCustomerAccount);
  168. verificationToken = await verificationTokenPromise;
  169. expect(registerCustomerAccount.success).toBe(true);
  170. expect(sendEmailFn).toHaveBeenCalled();
  171. expect(verificationToken).toBeDefined();
  172. const { customers } = await adminClient.query<GetCustomerList.Query, GetCustomerList.Variables>(
  173. GET_CUSTOMER_LIST,
  174. {
  175. options: {
  176. filter: {
  177. emailAddress: {
  178. eq: emailAddress,
  179. },
  180. },
  181. },
  182. },
  183. );
  184. expect(
  185. pick(customers.items[0], ['firstName', 'lastName', 'emailAddress', 'phoneNumber']),
  186. ).toEqual(input);
  187. });
  188. it('issues a new token if attempting to register a second time', async () => {
  189. const sendEmail = new Promise<string>(resolve => {
  190. sendEmailFn.mockImplementation((event: AccountRegistrationEvent) => {
  191. resolve(event.user.getNativeAuthenticationMethod().verificationToken!);
  192. });
  193. });
  194. const input: RegisterCustomerInput = {
  195. firstName: 'Sean',
  196. lastName: 'Tester',
  197. emailAddress,
  198. };
  199. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  200. REGISTER_ACCOUNT,
  201. {
  202. input,
  203. },
  204. );
  205. successErrorGuard.assertSuccess(registerCustomerAccount);
  206. const newVerificationToken = await sendEmail;
  207. expect(registerCustomerAccount.success).toBe(true);
  208. expect(sendEmailFn).toHaveBeenCalled();
  209. expect(newVerificationToken).not.toBe(verificationToken);
  210. verificationToken = newVerificationToken;
  211. });
  212. it('refreshCustomerVerification issues a new token', async () => {
  213. const sendEmail = new Promise<string>(resolve => {
  214. sendEmailFn.mockImplementation((event: AccountRegistrationEvent) => {
  215. resolve(event.user.getNativeAuthenticationMethod().verificationToken!);
  216. });
  217. });
  218. const { refreshCustomerVerification } = await shopClient.query<
  219. RefreshToken.Mutation,
  220. RefreshToken.Variables
  221. >(REFRESH_TOKEN, { emailAddress });
  222. successErrorGuard.assertSuccess(refreshCustomerVerification);
  223. const newVerificationToken = await sendEmail;
  224. expect(refreshCustomerVerification.success).toBe(true);
  225. expect(sendEmailFn).toHaveBeenCalled();
  226. expect(newVerificationToken).not.toBe(verificationToken);
  227. verificationToken = newVerificationToken;
  228. });
  229. it('refreshCustomerVerification does nothing with an unrecognized emailAddress', async () => {
  230. const { refreshCustomerVerification } = await shopClient.query<
  231. RefreshToken.Mutation,
  232. RefreshToken.Variables
  233. >(REFRESH_TOKEN, {
  234. emailAddress: 'never-been-registered@test.com',
  235. });
  236. successErrorGuard.assertSuccess(refreshCustomerVerification);
  237. await waitForSendEmailFn();
  238. expect(refreshCustomerVerification.success).toBe(true);
  239. expect(sendEmailFn).not.toHaveBeenCalled();
  240. });
  241. it('login fails before verification', async () => {
  242. const result = await shopClient.asUserWithCredentials(emailAddress, '');
  243. expect(result.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR);
  244. });
  245. it('verification fails with wrong token', async () => {
  246. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  247. VERIFY_EMAIL,
  248. {
  249. password,
  250. token: 'bad-token',
  251. },
  252. );
  253. currentUserErrorGuard.assertErrorResult(verifyCustomerAccount);
  254. expect(verifyCustomerAccount.message).toBe(`Verification token not recognized`);
  255. expect(verifyCustomerAccount.errorCode).toBe(ErrorCode.VERIFICATION_TOKEN_INVALID_ERROR);
  256. });
  257. it('verification fails with no password', async () => {
  258. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  259. VERIFY_EMAIL,
  260. {
  261. token: verificationToken,
  262. },
  263. );
  264. currentUserErrorGuard.assertErrorResult(verifyCustomerAccount);
  265. expect(verifyCustomerAccount.message).toBe(`A password must be provided.`);
  266. expect(verifyCustomerAccount.errorCode).toBe(ErrorCode.MISSING_PASSWORD_ERROR);
  267. });
  268. it('verification fails with invalid password', async () => {
  269. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  270. VERIFY_EMAIL,
  271. {
  272. token: verificationToken,
  273. password: '2short',
  274. },
  275. );
  276. currentUserErrorGuard.assertErrorResult(verifyCustomerAccount);
  277. expect(verifyCustomerAccount.message).toBe(`Password is invalid`);
  278. expect((verifyCustomerAccount as PasswordValidationError).validationErrorMessage).toBe(
  279. `Password must be more than 8 characters`,
  280. );
  281. expect(verifyCustomerAccount.errorCode).toBe(ErrorCode.PASSWORD_VALIDATION_ERROR);
  282. });
  283. it('verification succeeds with password and correct token', async () => {
  284. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  285. VERIFY_EMAIL,
  286. {
  287. password,
  288. token: verificationToken,
  289. },
  290. );
  291. currentUserErrorGuard.assertSuccess(verifyCustomerAccount);
  292. expect(verifyCustomerAccount.identifier).toBe('test1@test.com');
  293. const { activeCustomer } = await shopClient.query<GetActiveCustomer.Query>(GET_ACTIVE_CUSTOMER);
  294. newCustomerId = activeCustomer!.id;
  295. });
  296. it('registration silently fails if attempting to register an email already verified', async () => {
  297. const input: RegisterCustomerInput = {
  298. firstName: 'Dodgy',
  299. lastName: 'Hacker',
  300. emailAddress,
  301. };
  302. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  303. REGISTER_ACCOUNT,
  304. {
  305. input,
  306. },
  307. );
  308. successErrorGuard.assertSuccess(registerCustomerAccount);
  309. await waitForSendEmailFn();
  310. expect(registerCustomerAccount.success).toBe(true);
  311. expect(sendEmailFn).not.toHaveBeenCalled();
  312. });
  313. it('verification fails if attempted a second time', async () => {
  314. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  315. VERIFY_EMAIL,
  316. {
  317. password,
  318. token: verificationToken,
  319. },
  320. );
  321. currentUserErrorGuard.assertErrorResult(verifyCustomerAccount);
  322. expect(verifyCustomerAccount.message).toBe(`Verification token not recognized`);
  323. expect(verifyCustomerAccount.errorCode).toBe(ErrorCode.VERIFICATION_TOKEN_INVALID_ERROR);
  324. });
  325. it('customer history contains entries for registration & verification', async () => {
  326. const { customer } = await adminClient.query<
  327. GetCustomerHistory.Query,
  328. GetCustomerHistory.Variables
  329. >(GET_CUSTOMER_HISTORY, {
  330. id: newCustomerId,
  331. });
  332. expect(customer?.history.items.map(pick(['type', 'data']))).toEqual([
  333. {
  334. type: HistoryEntryType.CUSTOMER_REGISTERED,
  335. data: {
  336. strategy: 'native',
  337. },
  338. },
  339. {
  340. // second entry because we register twice above
  341. type: HistoryEntryType.CUSTOMER_REGISTERED,
  342. data: {
  343. strategy: 'native',
  344. },
  345. },
  346. {
  347. type: HistoryEntryType.CUSTOMER_VERIFIED,
  348. data: {
  349. strategy: 'native',
  350. },
  351. },
  352. ]);
  353. });
  354. });
  355. describe('customer account creation with up-front password', () => {
  356. const password = 'password';
  357. const emailAddress = 'test2@test.com';
  358. let verificationToken: string;
  359. it('registerCustomerAccount fails with invalid password', async () => {
  360. const input: RegisterCustomerInput = {
  361. firstName: 'Lu',
  362. lastName: 'Tester',
  363. phoneNumber: '443324',
  364. emailAddress,
  365. password: '12345678',
  366. };
  367. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  368. REGISTER_ACCOUNT,
  369. {
  370. input,
  371. },
  372. );
  373. successErrorGuard.assertErrorResult(registerCustomerAccount);
  374. expect(registerCustomerAccount.errorCode).toBe(ErrorCode.PASSWORD_VALIDATION_ERROR);
  375. expect(registerCustomerAccount.message).toBe(`Password is invalid`);
  376. expect((registerCustomerAccount as PasswordValidationError).validationErrorMessage).toBe(
  377. `Don't use 12345678!`,
  378. );
  379. });
  380. it('register a new account with password', async () => {
  381. const verificationTokenPromise = getVerificationTokenPromise();
  382. const input: RegisterCustomerInput = {
  383. firstName: 'Lu',
  384. lastName: 'Tester',
  385. phoneNumber: '443324',
  386. emailAddress,
  387. password,
  388. };
  389. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  390. REGISTER_ACCOUNT,
  391. {
  392. input,
  393. },
  394. );
  395. successErrorGuard.assertSuccess(registerCustomerAccount);
  396. verificationToken = await verificationTokenPromise;
  397. expect(registerCustomerAccount.success).toBe(true);
  398. expect(sendEmailFn).toHaveBeenCalled();
  399. expect(verificationToken).toBeDefined();
  400. const { customers } = await adminClient.query<GetCustomerList.Query, GetCustomerList.Variables>(
  401. GET_CUSTOMER_LIST,
  402. {
  403. options: {
  404. filter: {
  405. emailAddress: {
  406. eq: emailAddress,
  407. },
  408. },
  409. },
  410. },
  411. );
  412. expect(
  413. pick(customers.items[0], ['firstName', 'lastName', 'emailAddress', 'phoneNumber']),
  414. ).toEqual(pick(input, ['firstName', 'lastName', 'emailAddress', 'phoneNumber']));
  415. });
  416. it('login fails before verification', async () => {
  417. const result = await shopClient.asUserWithCredentials(emailAddress, password);
  418. expect(result.errorCode).toBe(ErrorCode.NOT_VERIFIED_ERROR);
  419. expect(result.message).toBe('Please verify this email address before logging in');
  420. });
  421. it('verification fails with password', async () => {
  422. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  423. VERIFY_EMAIL,
  424. {
  425. token: verificationToken,
  426. password: 'new password',
  427. },
  428. );
  429. currentUserErrorGuard.assertErrorResult(verifyCustomerAccount);
  430. expect(verifyCustomerAccount.message).toBe(`A password has already been set during registration`);
  431. expect(verifyCustomerAccount.errorCode).toBe(ErrorCode.PASSWORD_ALREADY_SET_ERROR);
  432. });
  433. it('verification succeeds with no password and correct token', async () => {
  434. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  435. VERIFY_EMAIL,
  436. {
  437. token: verificationToken,
  438. },
  439. );
  440. currentUserErrorGuard.assertSuccess(verifyCustomerAccount);
  441. expect(verifyCustomerAccount.identifier).toBe('test2@test.com');
  442. const { activeCustomer } = await shopClient.query<GetActiveCustomer.Query>(GET_ACTIVE_CUSTOMER);
  443. });
  444. });
  445. describe('password reset', () => {
  446. let passwordResetToken: string;
  447. let customer: GetCustomer.Customer;
  448. beforeAll(async () => {
  449. const result = await adminClient.query<GetCustomer.Query, GetCustomer.Variables>(GET_CUSTOMER, {
  450. id: 'T_1',
  451. });
  452. customer = result.customer!;
  453. });
  454. beforeEach(() => {
  455. sendEmailFn = jest.fn();
  456. });
  457. it('requestPasswordReset silently fails with invalid identifier', async () => {
  458. const { requestPasswordReset } = await shopClient.query<
  459. RequestPasswordReset.Mutation,
  460. RequestPasswordReset.Variables
  461. >(REQUEST_PASSWORD_RESET, {
  462. identifier: 'invalid-identifier',
  463. });
  464. successErrorGuard.assertSuccess(requestPasswordReset);
  465. await waitForSendEmailFn();
  466. expect(requestPasswordReset.success).toBe(true);
  467. expect(sendEmailFn).not.toHaveBeenCalled();
  468. expect(passwordResetToken).not.toBeDefined();
  469. });
  470. it('requestPasswordReset sends reset token', async () => {
  471. const passwordResetTokenPromise = getPasswordResetTokenPromise();
  472. const { requestPasswordReset } = await shopClient.query<
  473. RequestPasswordReset.Mutation,
  474. RequestPasswordReset.Variables
  475. >(REQUEST_PASSWORD_RESET, {
  476. identifier: customer.emailAddress,
  477. });
  478. successErrorGuard.assertSuccess(requestPasswordReset);
  479. passwordResetToken = await passwordResetTokenPromise;
  480. expect(requestPasswordReset.success).toBe(true);
  481. expect(sendEmailFn).toHaveBeenCalled();
  482. expect(passwordResetToken).toBeDefined();
  483. });
  484. it('resetPassword returns error result with wrong token', async () => {
  485. const { resetPassword } = await shopClient.query<ResetPassword.Mutation, ResetPassword.Variables>(
  486. RESET_PASSWORD,
  487. {
  488. password: 'newPassword',
  489. token: 'bad-token',
  490. },
  491. );
  492. currentUserErrorGuard.assertErrorResult(resetPassword);
  493. expect(resetPassword.message).toBe(`Password reset token not recognized`);
  494. expect(resetPassword.errorCode).toBe(ErrorCode.PASSWORD_RESET_TOKEN_INVALID_ERROR);
  495. });
  496. it('resetPassword fails with invalid password', async () => {
  497. const { resetPassword } = await shopClient.query<ResetPassword.Mutation, ResetPassword.Variables>(
  498. RESET_PASSWORD,
  499. {
  500. token: passwordResetToken,
  501. password: '2short',
  502. },
  503. );
  504. currentUserErrorGuard.assertErrorResult(resetPassword);
  505. expect(resetPassword.message).toBe(`Password is invalid`);
  506. expect((resetPassword as PasswordValidationError).validationErrorMessage).toBe(
  507. `Password must be more than 8 characters`,
  508. );
  509. expect(resetPassword.errorCode).toBe(ErrorCode.PASSWORD_VALIDATION_ERROR);
  510. });
  511. it('resetPassword works with valid token', async () => {
  512. const { resetPassword } = await shopClient.query<ResetPassword.Mutation, ResetPassword.Variables>(
  513. RESET_PASSWORD,
  514. {
  515. token: passwordResetToken,
  516. password: 'newPassword',
  517. },
  518. );
  519. currentUserErrorGuard.assertSuccess(resetPassword);
  520. expect(resetPassword.identifier).toBe(customer.emailAddress);
  521. const loginResult = await shopClient.asUserWithCredentials(customer.emailAddress, 'newPassword');
  522. expect(loginResult.identifier).toBe(customer.emailAddress);
  523. });
  524. it('customer history for password reset', async () => {
  525. const result = await adminClient.query<GetCustomerHistory.Query, GetCustomerHistory.Variables>(
  526. GET_CUSTOMER_HISTORY,
  527. {
  528. id: customer.id,
  529. options: {
  530. // skip CUSTOMER_ADDRESS_CREATED entry
  531. skip: 3,
  532. },
  533. },
  534. );
  535. expect(result.customer?.history.items.map(pick(['type', 'data']))).toEqual([
  536. {
  537. type: HistoryEntryType.CUSTOMER_PASSWORD_RESET_REQUESTED,
  538. data: {},
  539. },
  540. {
  541. type: HistoryEntryType.CUSTOMER_PASSWORD_RESET_VERIFIED,
  542. data: {},
  543. },
  544. ]);
  545. });
  546. });
  547. describe('updating emailAddress', () => {
  548. let emailUpdateToken: string;
  549. let customer: GetCustomer.Customer;
  550. const NEW_EMAIL_ADDRESS = 'new@address.com';
  551. const PASSWORD = 'newPassword';
  552. beforeAll(async () => {
  553. const result = await adminClient.query<GetCustomer.Query, GetCustomer.Variables>(GET_CUSTOMER, {
  554. id: 'T_1',
  555. });
  556. customer = result.customer!;
  557. });
  558. beforeEach(() => {
  559. sendEmailFn = jest.fn();
  560. });
  561. it('throws if not logged in', async () => {
  562. try {
  563. await shopClient.asAnonymousUser();
  564. await shopClient.query<
  565. RequestUpdateEmailAddress.Mutation,
  566. RequestUpdateEmailAddress.Variables
  567. >(REQUEST_UPDATE_EMAIL_ADDRESS, {
  568. password: PASSWORD,
  569. newEmailAddress: NEW_EMAIL_ADDRESS,
  570. });
  571. fail('should have thrown');
  572. } catch (err) {
  573. expect(getErrorCode(err)).toBe('FORBIDDEN');
  574. }
  575. });
  576. it('return error result if password is incorrect', async () => {
  577. await shopClient.asUserWithCredentials(customer.emailAddress, PASSWORD);
  578. const { requestUpdateCustomerEmailAddress } = await shopClient.query<
  579. RequestUpdateEmailAddress.Mutation,
  580. RequestUpdateEmailAddress.Variables
  581. >(REQUEST_UPDATE_EMAIL_ADDRESS, {
  582. password: 'bad password',
  583. newEmailAddress: NEW_EMAIL_ADDRESS,
  584. });
  585. successErrorGuard.assertErrorResult(requestUpdateCustomerEmailAddress);
  586. expect(requestUpdateCustomerEmailAddress.message).toBe('The provided credentials are invalid');
  587. expect(requestUpdateCustomerEmailAddress.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR);
  588. });
  589. it('return error result email address already in use', async () => {
  590. await shopClient.asUserWithCredentials(customer.emailAddress, PASSWORD);
  591. const result = await adminClient.query<GetCustomer.Query, GetCustomer.Variables>(GET_CUSTOMER, {
  592. id: 'T_2',
  593. });
  594. const otherCustomer = result.customer!;
  595. const { requestUpdateCustomerEmailAddress } = await shopClient.query<
  596. RequestUpdateEmailAddress.Mutation,
  597. RequestUpdateEmailAddress.Variables
  598. >(REQUEST_UPDATE_EMAIL_ADDRESS, {
  599. password: PASSWORD,
  600. newEmailAddress: otherCustomer.emailAddress,
  601. });
  602. successErrorGuard.assertErrorResult(requestUpdateCustomerEmailAddress);
  603. expect(requestUpdateCustomerEmailAddress.message).toBe('The email address is not available.');
  604. expect(requestUpdateCustomerEmailAddress.errorCode).toBe(ErrorCode.EMAIL_ADDRESS_CONFLICT_ERROR);
  605. });
  606. it('triggers event with token', async () => {
  607. await shopClient.asUserWithCredentials(customer.emailAddress, PASSWORD);
  608. const emailUpdateTokenPromise = getEmailUpdateTokenPromise();
  609. await shopClient.query<RequestUpdateEmailAddress.Mutation, RequestUpdateEmailAddress.Variables>(
  610. REQUEST_UPDATE_EMAIL_ADDRESS,
  611. {
  612. password: PASSWORD,
  613. newEmailAddress: NEW_EMAIL_ADDRESS,
  614. },
  615. );
  616. const { identifierChangeToken, pendingIdentifier } = await emailUpdateTokenPromise;
  617. emailUpdateToken = identifierChangeToken!;
  618. expect(pendingIdentifier).toBe(NEW_EMAIL_ADDRESS);
  619. expect(emailUpdateToken).toBeTruthy();
  620. });
  621. it('cannot login with new email address before verification', async () => {
  622. const result = await shopClient.asUserWithCredentials(NEW_EMAIL_ADDRESS, PASSWORD);
  623. expect(result.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR);
  624. });
  625. it('return error result for bad token', async () => {
  626. const { updateCustomerEmailAddress } = await shopClient.query<
  627. UpdateEmailAddress.Mutation,
  628. UpdateEmailAddress.Variables
  629. >(UPDATE_EMAIL_ADDRESS, { token: 'bad token' });
  630. successErrorGuard.assertErrorResult(updateCustomerEmailAddress);
  631. expect(updateCustomerEmailAddress.message).toBe('Identifier change token not recognized');
  632. expect(updateCustomerEmailAddress.errorCode).toBe(
  633. ErrorCode.IDENTIFIER_CHANGE_TOKEN_INVALID_ERROR,
  634. );
  635. });
  636. it('verify the new email address', async () => {
  637. const { updateCustomerEmailAddress } = await shopClient.query<
  638. UpdateEmailAddress.Mutation,
  639. UpdateEmailAddress.Variables
  640. >(UPDATE_EMAIL_ADDRESS, { token: emailUpdateToken });
  641. successErrorGuard.assertSuccess(updateCustomerEmailAddress);
  642. expect(updateCustomerEmailAddress.success).toBe(true);
  643. // Allow for occasional race condition where the event does not
  644. // publish before the assertions are made.
  645. await new Promise(resolve => setTimeout(resolve, 10));
  646. expect(sendEmailFn).toHaveBeenCalled();
  647. expect(sendEmailFn.mock.calls[0][0] instanceof IdentifierChangeEvent).toBe(true);
  648. });
  649. it('can login with new email address after verification', async () => {
  650. await shopClient.asUserWithCredentials(NEW_EMAIL_ADDRESS, PASSWORD);
  651. const { activeCustomer } = await shopClient.query<GetActiveCustomer.Query>(GET_ACTIVE_CUSTOMER);
  652. expect(activeCustomer!.id).toBe(customer.id);
  653. expect(activeCustomer!.emailAddress).toBe(NEW_EMAIL_ADDRESS);
  654. });
  655. it('cannot login with old email address after verification', async () => {
  656. const result = await shopClient.asUserWithCredentials(customer.emailAddress, PASSWORD);
  657. expect(result.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR);
  658. });
  659. it('customer history for email update', async () => {
  660. const result = await adminClient.query<GetCustomerHistory.Query, GetCustomerHistory.Variables>(
  661. GET_CUSTOMER_HISTORY,
  662. {
  663. id: customer.id,
  664. options: {
  665. skip: 5,
  666. },
  667. },
  668. );
  669. expect(result.customer?.history.items.map(pick(['type', 'data']))).toEqual([
  670. {
  671. type: HistoryEntryType.CUSTOMER_EMAIL_UPDATE_REQUESTED,
  672. data: {
  673. newEmailAddress: 'new@address.com',
  674. oldEmailAddress: 'hayden.zieme12@hotmail.com',
  675. },
  676. },
  677. {
  678. type: HistoryEntryType.CUSTOMER_EMAIL_UPDATE_VERIFIED,
  679. data: {
  680. newEmailAddress: 'new@address.com',
  681. oldEmailAddress: 'hayden.zieme12@hotmail.com',
  682. },
  683. },
  684. ]);
  685. });
  686. });
  687. async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) {
  688. try {
  689. const status = await shopClient.queryStatus(operation, variables);
  690. expect(status).toBe(200);
  691. } catch (e) {
  692. const errorCode = getErrorCode(e);
  693. if (!errorCode) {
  694. fail(`Unexpected failure: ${e}`);
  695. } else {
  696. fail(`Operation should be allowed, got status ${getErrorCode(e)}`);
  697. }
  698. }
  699. }
  700. async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) {
  701. try {
  702. const status = await shopClient.query(operation, variables);
  703. fail(`Should have thrown`);
  704. } catch (e) {
  705. expect(getErrorCode(e)).toBe('FORBIDDEN');
  706. }
  707. }
  708. function getErrorCode(err: any): string {
  709. return err.response.errors[0].extensions.code;
  710. }
  711. async function createAdministratorWithPermissions(
  712. code: string,
  713. permissions: Permission[],
  714. ): Promise<{ identifier: string; password: string }> {
  715. const roleResult = await shopClient.query<CreateRole.Mutation, CreateRole.Variables>(CREATE_ROLE, {
  716. input: {
  717. code,
  718. description: '',
  719. permissions,
  720. },
  721. });
  722. const role = roleResult.createRole;
  723. const identifier = `${code}@${Math.random().toString(16).substr(2, 8)}`;
  724. const password = `test`;
  725. const adminResult = await shopClient.query<
  726. CreateAdministrator.Mutation,
  727. CreateAdministrator.Variables
  728. >(CREATE_ADMINISTRATOR, {
  729. input: {
  730. emailAddress: identifier,
  731. firstName: code,
  732. lastName: 'Admin',
  733. password,
  734. roleIds: [role.id],
  735. },
  736. });
  737. const admin = adminResult.createAdministrator;
  738. return {
  739. identifier,
  740. password,
  741. };
  742. }
  743. /**
  744. * A "sleep" function which allows the sendEmailFn time to get called.
  745. */
  746. function waitForSendEmailFn() {
  747. return new Promise(resolve => setTimeout(resolve, 10));
  748. }
  749. });
  750. describe('Expiring tokens', () => {
  751. const { server, adminClient, shopClient } = createTestEnvironment(
  752. mergeConfig(testConfig(), {
  753. plugins: [TestEmailPlugin as any],
  754. authOptions: {
  755. verificationTokenDuration: '1ms',
  756. },
  757. }),
  758. );
  759. beforeAll(async () => {
  760. await server.init({
  761. initialData,
  762. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  763. customerCount: 1,
  764. });
  765. await adminClient.asSuperAdmin();
  766. }, TEST_SETUP_TIMEOUT_MS);
  767. beforeEach(() => {
  768. sendEmailFn = jest.fn();
  769. });
  770. afterAll(async () => {
  771. await server.destroy();
  772. });
  773. it('attempting to verify after token has expired throws', async () => {
  774. const verificationTokenPromise = getVerificationTokenPromise();
  775. const input: RegisterCustomerInput = {
  776. firstName: 'Barry',
  777. lastName: 'Wallace',
  778. emailAddress: 'barry.wallace@test.com',
  779. };
  780. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  781. REGISTER_ACCOUNT,
  782. {
  783. input,
  784. },
  785. );
  786. successErrorGuard.assertSuccess(registerCustomerAccount);
  787. const verificationToken = await verificationTokenPromise;
  788. expect(registerCustomerAccount.success).toBe(true);
  789. expect(sendEmailFn).toHaveBeenCalledTimes(1);
  790. expect(verificationToken).toBeDefined();
  791. await new Promise(resolve => setTimeout(resolve, 3));
  792. const { verifyCustomerAccount } = await shopClient.query<Verify.Mutation, Verify.Variables>(
  793. VERIFY_EMAIL,
  794. {
  795. password: 'test',
  796. token: verificationToken,
  797. },
  798. );
  799. currentUserErrorGuard.assertErrorResult(verifyCustomerAccount);
  800. expect(verifyCustomerAccount.message).toBe(
  801. `Verification token has expired. Use refreshCustomerVerification to send a new token.`,
  802. );
  803. expect(verifyCustomerAccount.errorCode).toBe(ErrorCode.VERIFICATION_TOKEN_EXPIRED_ERROR);
  804. });
  805. it('attempting to reset password after token has expired returns error result', async () => {
  806. const { customer } = await adminClient.query<GetCustomer.Query, GetCustomer.Variables>(GET_CUSTOMER, {
  807. id: 'T_1',
  808. });
  809. const passwordResetTokenPromise = getPasswordResetTokenPromise();
  810. const { requestPasswordReset } = await shopClient.query<
  811. RequestPasswordReset.Mutation,
  812. RequestPasswordReset.Variables
  813. >(REQUEST_PASSWORD_RESET, {
  814. identifier: customer!.emailAddress,
  815. });
  816. successErrorGuard.assertSuccess(requestPasswordReset);
  817. const passwordResetToken = await passwordResetTokenPromise;
  818. expect(requestPasswordReset.success).toBe(true);
  819. expect(sendEmailFn).toHaveBeenCalledTimes(1);
  820. expect(passwordResetToken).toBeDefined();
  821. await new Promise(resolve => setTimeout(resolve, 3));
  822. const { resetPassword } = await shopClient.query<ResetPassword.Mutation, ResetPassword.Variables>(
  823. RESET_PASSWORD,
  824. {
  825. password: 'test',
  826. token: passwordResetToken,
  827. },
  828. );
  829. currentUserErrorGuard.assertErrorResult(resetPassword);
  830. expect(resetPassword.message).toBe(`Password reset token has expired`);
  831. expect(resetPassword.errorCode).toBe(ErrorCode.PASSWORD_RESET_TOKEN_EXPIRED_ERROR);
  832. });
  833. });
  834. describe('Registration without email verification', () => {
  835. const { server, shopClient } = createTestEnvironment(
  836. mergeConfig(testConfig(), {
  837. plugins: [TestEmailPlugin as any],
  838. authOptions: {
  839. requireVerification: false,
  840. },
  841. }),
  842. );
  843. const userEmailAddress = 'glen.beardsley@test.com';
  844. beforeAll(async () => {
  845. await server.init({
  846. initialData,
  847. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  848. customerCount: 1,
  849. });
  850. }, TEST_SETUP_TIMEOUT_MS);
  851. beforeEach(() => {
  852. sendEmailFn = jest.fn();
  853. });
  854. afterAll(async () => {
  855. await server.destroy();
  856. });
  857. it('Returns error result if no password is provided', async () => {
  858. const input: RegisterCustomerInput = {
  859. firstName: 'Glen',
  860. lastName: 'Beardsley',
  861. emailAddress: userEmailAddress,
  862. };
  863. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  864. REGISTER_ACCOUNT,
  865. {
  866. input,
  867. },
  868. );
  869. successErrorGuard.assertErrorResult(registerCustomerAccount);
  870. expect(registerCustomerAccount.message).toBe('A password must be provided.');
  871. expect(registerCustomerAccount.errorCode).toBe(ErrorCode.MISSING_PASSWORD_ERROR);
  872. });
  873. it('register a new account with password', async () => {
  874. const input: RegisterCustomerInput = {
  875. firstName: 'Glen',
  876. lastName: 'Beardsley',
  877. emailAddress: userEmailAddress,
  878. password: 'test',
  879. };
  880. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  881. REGISTER_ACCOUNT,
  882. {
  883. input,
  884. },
  885. );
  886. successErrorGuard.assertSuccess(registerCustomerAccount);
  887. expect(registerCustomerAccount.success).toBe(true);
  888. expect(sendEmailFn).not.toHaveBeenCalled();
  889. });
  890. it('can login after registering', async () => {
  891. await shopClient.asUserWithCredentials(userEmailAddress, 'test');
  892. const result = await shopClient.query(
  893. gql`
  894. query GetMe {
  895. me {
  896. identifier
  897. }
  898. }
  899. `,
  900. );
  901. expect(result.me.identifier).toBe(userEmailAddress);
  902. });
  903. });
  904. describe('Updating email address without email verification', () => {
  905. const { server, adminClient, shopClient } = createTestEnvironment(
  906. mergeConfig(testConfig(), {
  907. plugins: [TestEmailPlugin as any],
  908. authOptions: {
  909. requireVerification: false,
  910. },
  911. }),
  912. );
  913. let customer: GetCustomer.Customer;
  914. const NEW_EMAIL_ADDRESS = 'new@address.com';
  915. beforeAll(async () => {
  916. await server.init({
  917. initialData,
  918. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  919. customerCount: 1,
  920. });
  921. await adminClient.asSuperAdmin();
  922. const result = await adminClient.query<GetCustomer.Query, GetCustomer.Variables>(GET_CUSTOMER, {
  923. id: 'T_1',
  924. });
  925. customer = result.customer!;
  926. }, TEST_SETUP_TIMEOUT_MS);
  927. beforeEach(() => {
  928. sendEmailFn = jest.fn();
  929. });
  930. afterAll(async () => {
  931. await server.destroy();
  932. });
  933. it('updates email address', async () => {
  934. await shopClient.asUserWithCredentials(customer.emailAddress, 'test');
  935. const { requestUpdateCustomerEmailAddress } = await shopClient.query<
  936. RequestUpdateEmailAddress.Mutation,
  937. RequestUpdateEmailAddress.Variables
  938. >(REQUEST_UPDATE_EMAIL_ADDRESS, {
  939. password: 'test',
  940. newEmailAddress: NEW_EMAIL_ADDRESS,
  941. });
  942. successErrorGuard.assertSuccess(requestUpdateCustomerEmailAddress);
  943. expect(requestUpdateCustomerEmailAddress.success).toBe(true);
  944. expect(sendEmailFn).toHaveBeenCalledTimes(1);
  945. expect(sendEmailFn.mock.calls[0][0] instanceof IdentifierChangeEvent).toBe(true);
  946. const { activeCustomer } = await shopClient.query<GetActiveCustomer.Query>(GET_ACTIVE_CUSTOMER);
  947. expect(activeCustomer!.emailAddress).toBe(NEW_EMAIL_ADDRESS);
  948. });
  949. });
  950. function getVerificationTokenPromise(): Promise<string> {
  951. return new Promise<any>(resolve => {
  952. sendEmailFn.mockImplementation((event: AccountRegistrationEvent) => {
  953. resolve(event.user.getNativeAuthenticationMethod().verificationToken);
  954. });
  955. });
  956. }
  957. function getPasswordResetTokenPromise(): Promise<string> {
  958. return new Promise<any>(resolve => {
  959. sendEmailFn.mockImplementation((event: PasswordResetEvent) => {
  960. resolve(event.user.getNativeAuthenticationMethod().passwordResetToken);
  961. });
  962. });
  963. }
  964. function getEmailUpdateTokenPromise(): Promise<{
  965. identifierChangeToken: string | null;
  966. pendingIdentifier: string | null;
  967. }> {
  968. return new Promise(resolve => {
  969. sendEmailFn.mockImplementation((event: IdentifierChangeRequestEvent) => {
  970. resolve(
  971. pick(event.user.getNativeAuthenticationMethod(), [
  972. 'identifierChangeToken',
  973. 'pendingIdentifier',
  974. ]),
  975. );
  976. });
  977. });
  978. }