authentication-strategy.e2e-spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /* tslint:disable:no-non-null-assertion */
  2. import { ErrorCode } from '@vendure/common/lib/generated-shop-types';
  3. import { pick } from '@vendure/common/lib/pick';
  4. import { mergeConfig, NativeAuthenticationStrategy } from '@vendure/core';
  5. import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing';
  6. import gql from 'graphql-tag';
  7. import path from 'path';
  8. import { initialData } from '../../../e2e-common/e2e-initial-data';
  9. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  10. import { TestAuthenticationStrategy, VALID_AUTH_TOKEN } from './fixtures/test-authentication-strategies';
  11. import { CURRENT_USER_FRAGMENT } from './graphql/fragments';
  12. import {
  13. Authenticate,
  14. CreateCustomer,
  15. CurrentUser,
  16. CurrentUserFragment,
  17. CustomerFragment,
  18. DeleteCustomer,
  19. GetCustomerHistory,
  20. GetCustomers,
  21. GetCustomerUserAuth,
  22. HistoryEntryType,
  23. Me,
  24. } from './graphql/generated-e2e-admin-types';
  25. import { Register } from './graphql/generated-e2e-shop-types';
  26. import { CREATE_CUSTOMER, DELETE_CUSTOMER, GET_CUSTOMER_HISTORY, ME } from './graphql/shared-definitions';
  27. import { REGISTER_ACCOUNT } from './graphql/shop-definitions';
  28. import { assertThrowsWithMessage } from './utils/assert-throws-with-message';
  29. describe('AuthenticationStrategy', () => {
  30. const { server, adminClient, shopClient } = createTestEnvironment(
  31. mergeConfig(testConfig, {
  32. authOptions: {
  33. shopAuthenticationStrategy: [
  34. new NativeAuthenticationStrategy(),
  35. new TestAuthenticationStrategy(),
  36. ],
  37. },
  38. }),
  39. );
  40. beforeAll(async () => {
  41. await server.init({
  42. initialData,
  43. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  44. customerCount: 1,
  45. });
  46. await adminClient.asSuperAdmin();
  47. }, TEST_SETUP_TIMEOUT_MS);
  48. afterAll(async () => {
  49. await server.destroy();
  50. });
  51. const currentUserGuard: ErrorResultGuard<CurrentUserFragment> = createErrorResultGuard<
  52. CurrentUserFragment
  53. >(input => input.identifier != null);
  54. const customerGuard: ErrorResultGuard<CustomerFragment> = createErrorResultGuard<CustomerFragment>(
  55. input => input.emailAddress != null,
  56. );
  57. describe('external auth', () => {
  58. const userData = {
  59. email: 'test@email.com',
  60. firstName: 'Cixin',
  61. lastName: 'Liu',
  62. };
  63. let newCustomerId: string;
  64. it('fails with a bad token', async () => {
  65. const { authenticate } = await shopClient.query(AUTHENTICATE, {
  66. input: {
  67. test_strategy: {
  68. token: 'bad-token',
  69. },
  70. },
  71. });
  72. expect(authenticate.message).toBe('The provided credentials are invalid');
  73. expect(authenticate.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR);
  74. });
  75. it('creates a new Customer with valid token', async () => {
  76. const { customers: before } = await adminClient.query<GetCustomers.Query>(GET_CUSTOMERS);
  77. expect(before.totalItems).toBe(1);
  78. const { authenticate } = await shopClient.query<Authenticate.Mutation>(AUTHENTICATE, {
  79. input: {
  80. test_strategy: {
  81. token: VALID_AUTH_TOKEN,
  82. userData,
  83. },
  84. },
  85. });
  86. currentUserGuard.assertSuccess(authenticate);
  87. expect(authenticate.identifier).toEqual(userData.email);
  88. const { customers: after } = await adminClient.query<GetCustomers.Query>(GET_CUSTOMERS);
  89. expect(after.totalItems).toBe(2);
  90. expect(after.items.map(i => i.emailAddress)).toEqual([
  91. 'hayden.zieme12@hotmail.com',
  92. userData.email,
  93. ]);
  94. newCustomerId = after.items[1].id;
  95. });
  96. it('creates customer history entry', async () => {
  97. const { customer } = await adminClient.query<
  98. GetCustomerHistory.Query,
  99. GetCustomerHistory.Variables
  100. >(GET_CUSTOMER_HISTORY, {
  101. id: newCustomerId,
  102. });
  103. expect(
  104. customer?.history.items.sort((a, b) => (a.id > b.id ? 1 : -1)).map(pick(['type', 'data'])),
  105. ).toEqual([
  106. {
  107. type: HistoryEntryType.CUSTOMER_REGISTERED,
  108. data: {
  109. strategy: 'test_strategy',
  110. },
  111. },
  112. {
  113. type: HistoryEntryType.CUSTOMER_VERIFIED,
  114. data: {
  115. strategy: 'test_strategy',
  116. },
  117. },
  118. ]);
  119. });
  120. it('user authenticationMethod populated', async () => {
  121. const { customer } = await adminClient.query<
  122. GetCustomerUserAuth.Query,
  123. GetCustomerUserAuth.Variables
  124. >(GET_CUSTOMER_USER_AUTH, {
  125. id: newCustomerId,
  126. });
  127. expect(customer?.user?.authenticationMethods.length).toBe(1);
  128. expect(customer?.user?.authenticationMethods[0].strategy).toBe('test_strategy');
  129. });
  130. it('creates authenticated session', async () => {
  131. const { me } = await shopClient.query<Me.Query>(ME);
  132. expect(me?.identifier).toBe(userData.email);
  133. });
  134. it('log out', async () => {
  135. await shopClient.asAnonymousUser();
  136. });
  137. it('logging in again re-uses created User & Customer', async () => {
  138. const { authenticate } = await shopClient.query<Authenticate.Mutation>(AUTHENTICATE, {
  139. input: {
  140. test_strategy: {
  141. token: VALID_AUTH_TOKEN,
  142. userData,
  143. },
  144. },
  145. });
  146. currentUserGuard.assertSuccess(authenticate);
  147. expect(authenticate.identifier).toEqual(userData.email);
  148. const { customers: after } = await adminClient.query<GetCustomers.Query>(GET_CUSTOMERS);
  149. expect(after.totalItems).toBe(2);
  150. expect(after.items.map(i => i.emailAddress)).toEqual([
  151. 'hayden.zieme12@hotmail.com',
  152. userData.email,
  153. ]);
  154. });
  155. it('registerCustomerAccount with external email', async () => {
  156. const successErrorGuard: ErrorResultGuard<{ success: boolean }> = createErrorResultGuard<{
  157. success: boolean;
  158. }>(input => input.success != null);
  159. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  160. REGISTER_ACCOUNT,
  161. {
  162. input: {
  163. emailAddress: userData.email,
  164. },
  165. },
  166. );
  167. successErrorGuard.assertSuccess(registerCustomerAccount);
  168. expect(registerCustomerAccount.success).toBe(true);
  169. const { customer } = await adminClient.query<
  170. GetCustomerUserAuth.Query,
  171. GetCustomerUserAuth.Variables
  172. >(GET_CUSTOMER_USER_AUTH, {
  173. id: newCustomerId,
  174. });
  175. expect(customer?.user?.authenticationMethods.length).toBe(2);
  176. expect(customer?.user?.authenticationMethods[1].strategy).toBe('native');
  177. const { customer: customer2 } = await adminClient.query<
  178. GetCustomerHistory.Query,
  179. GetCustomerHistory.Variables
  180. >(GET_CUSTOMER_HISTORY, {
  181. id: newCustomerId,
  182. options: {
  183. skip: 2,
  184. },
  185. });
  186. expect(customer2?.history.items.map(pick(['type', 'data']))).toEqual([
  187. {
  188. type: HistoryEntryType.CUSTOMER_REGISTERED,
  189. data: {
  190. strategy: 'native',
  191. },
  192. },
  193. ]);
  194. });
  195. });
  196. describe('native auth', () => {
  197. const testEmailAddress = 'test-person@testdomain.com';
  198. // https://github.com/vendure-ecommerce/vendure/issues/486#issuecomment-704991768
  199. it('allows login for an email address which is shared by a previously-deleted Customer', async () => {
  200. const { createCustomer: result1 } = await adminClient.query<
  201. CreateCustomer.Mutation,
  202. CreateCustomer.Variables
  203. >(CREATE_CUSTOMER, {
  204. input: {
  205. firstName: 'Test',
  206. lastName: 'Person',
  207. emailAddress: testEmailAddress,
  208. },
  209. password: 'password1',
  210. });
  211. customerGuard.assertSuccess(result1);
  212. await adminClient.query<DeleteCustomer.Mutation, DeleteCustomer.Variables>(DELETE_CUSTOMER, {
  213. id: result1.id,
  214. });
  215. const { createCustomer: result2 } = await adminClient.query<
  216. CreateCustomer.Mutation,
  217. CreateCustomer.Variables
  218. >(CREATE_CUSTOMER, {
  219. input: {
  220. firstName: 'Test',
  221. lastName: 'Person',
  222. emailAddress: testEmailAddress,
  223. },
  224. password: 'password2',
  225. });
  226. customerGuard.assertSuccess(result2);
  227. const { authenticate } = await shopClient.query(AUTHENTICATE, {
  228. input: {
  229. native: {
  230. username: testEmailAddress,
  231. password: 'password2',
  232. },
  233. },
  234. });
  235. currentUserGuard.assertSuccess(authenticate);
  236. expect(pick(authenticate, ['id', 'identifier'])).toEqual({
  237. id: result2.user!.id,
  238. identifier: result2.emailAddress,
  239. });
  240. });
  241. });
  242. });
  243. const AUTHENTICATE = gql`
  244. mutation Authenticate($input: AuthenticationInput!) {
  245. authenticate(input: $input) {
  246. ...CurrentUser
  247. ... on ErrorResult {
  248. errorCode
  249. message
  250. }
  251. }
  252. }
  253. ${CURRENT_USER_FRAGMENT}
  254. `;
  255. const GET_CUSTOMERS = gql`
  256. query GetCustomers {
  257. customers {
  258. totalItems
  259. items {
  260. id
  261. emailAddress
  262. }
  263. }
  264. }
  265. `;
  266. const GET_CUSTOMER_USER_AUTH = gql`
  267. query GetCustomerUserAuth($id: ID!) {
  268. customer(id: $id) {
  269. id
  270. user {
  271. id
  272. verified
  273. authenticationMethods {
  274. id
  275. strategy
  276. }
  277. }
  278. }
  279. }
  280. `;