authentication-strategy.e2e-spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. input => input.identifier != null,
  53. );
  54. const customerGuard: ErrorResultGuard<CustomerFragment> = createErrorResultGuard(
  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. expect(authenticate.authenticationError).toBe('');
  75. });
  76. it('fails with an expried token', async () => {
  77. const { authenticate } = await shopClient.query(AUTHENTICATE, {
  78. input: {
  79. test_strategy: {
  80. token: 'expired-token',
  81. },
  82. },
  83. });
  84. expect(authenticate.message).toBe('The provided credentials are invalid');
  85. expect(authenticate.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR);
  86. expect(authenticate.authenticationError).toBe('Expired token');
  87. });
  88. it('creates a new Customer with valid token', async () => {
  89. const { customers: before } = await adminClient.query<GetCustomers.Query>(GET_CUSTOMERS);
  90. expect(before.totalItems).toBe(1);
  91. const { authenticate } = await shopClient.query<Authenticate.Mutation>(AUTHENTICATE, {
  92. input: {
  93. test_strategy: {
  94. token: VALID_AUTH_TOKEN,
  95. userData,
  96. },
  97. },
  98. });
  99. currentUserGuard.assertSuccess(authenticate);
  100. expect(authenticate.identifier).toEqual(userData.email);
  101. const { customers: after } = await adminClient.query<GetCustomers.Query>(GET_CUSTOMERS);
  102. expect(after.totalItems).toBe(2);
  103. expect(after.items.map(i => i.emailAddress)).toEqual([
  104. 'hayden.zieme12@hotmail.com',
  105. userData.email,
  106. ]);
  107. newCustomerId = after.items[1].id;
  108. });
  109. it('creates customer history entry', async () => {
  110. const { customer } = await adminClient.query<
  111. GetCustomerHistory.Query,
  112. GetCustomerHistory.Variables
  113. >(GET_CUSTOMER_HISTORY, {
  114. id: newCustomerId,
  115. });
  116. expect(
  117. customer?.history.items.sort((a, b) => (a.id > b.id ? 1 : -1)).map(pick(['type', 'data'])),
  118. ).toEqual([
  119. {
  120. type: HistoryEntryType.CUSTOMER_REGISTERED,
  121. data: {
  122. strategy: 'test_strategy',
  123. },
  124. },
  125. {
  126. type: HistoryEntryType.CUSTOMER_VERIFIED,
  127. data: {
  128. strategy: 'test_strategy',
  129. },
  130. },
  131. ]);
  132. });
  133. it('user authenticationMethod populated', async () => {
  134. const { customer } = await adminClient.query<
  135. GetCustomerUserAuth.Query,
  136. GetCustomerUserAuth.Variables
  137. >(GET_CUSTOMER_USER_AUTH, {
  138. id: newCustomerId,
  139. });
  140. expect(customer?.user?.authenticationMethods.length).toBe(1);
  141. expect(customer?.user?.authenticationMethods[0].strategy).toBe('test_strategy');
  142. });
  143. it('creates authenticated session', async () => {
  144. const { me } = await shopClient.query<Me.Query>(ME);
  145. expect(me?.identifier).toBe(userData.email);
  146. });
  147. it('log out', async () => {
  148. await shopClient.asAnonymousUser();
  149. });
  150. it('logging in again re-uses created User & Customer', async () => {
  151. const { authenticate } = await shopClient.query<Authenticate.Mutation>(AUTHENTICATE, {
  152. input: {
  153. test_strategy: {
  154. token: VALID_AUTH_TOKEN,
  155. userData,
  156. },
  157. },
  158. });
  159. currentUserGuard.assertSuccess(authenticate);
  160. expect(authenticate.identifier).toEqual(userData.email);
  161. const { customers: after } = await adminClient.query<GetCustomers.Query>(GET_CUSTOMERS);
  162. expect(after.totalItems).toBe(2);
  163. expect(after.items.map(i => i.emailAddress)).toEqual([
  164. 'hayden.zieme12@hotmail.com',
  165. userData.email,
  166. ]);
  167. });
  168. it('registerCustomerAccount with external email', async () => {
  169. const successErrorGuard: ErrorResultGuard<{ success: boolean }> = createErrorResultGuard(
  170. input => input.success != null,
  171. );
  172. const { registerCustomerAccount } = await shopClient.query<Register.Mutation, Register.Variables>(
  173. REGISTER_ACCOUNT,
  174. {
  175. input: {
  176. emailAddress: userData.email,
  177. },
  178. },
  179. );
  180. successErrorGuard.assertSuccess(registerCustomerAccount);
  181. expect(registerCustomerAccount.success).toBe(true);
  182. const { customer } = await adminClient.query<
  183. GetCustomerUserAuth.Query,
  184. GetCustomerUserAuth.Variables
  185. >(GET_CUSTOMER_USER_AUTH, {
  186. id: newCustomerId,
  187. });
  188. expect(customer?.user?.authenticationMethods.length).toBe(2);
  189. expect(customer?.user?.authenticationMethods[1].strategy).toBe('native');
  190. const { customer: customer2 } = await adminClient.query<
  191. GetCustomerHistory.Query,
  192. GetCustomerHistory.Variables
  193. >(GET_CUSTOMER_HISTORY, {
  194. id: newCustomerId,
  195. options: {
  196. skip: 2,
  197. },
  198. });
  199. expect(customer2?.history.items.map(pick(['type', 'data']))).toEqual([
  200. {
  201. type: HistoryEntryType.CUSTOMER_REGISTERED,
  202. data: {
  203. strategy: 'native',
  204. },
  205. },
  206. ]);
  207. });
  208. });
  209. describe('native auth', () => {
  210. const testEmailAddress = 'test-person@testdomain.com';
  211. // https://github.com/vendure-ecommerce/vendure/issues/486#issuecomment-704991768
  212. it('allows login for an email address which is shared by a previously-deleted Customer', async () => {
  213. const { createCustomer: result1 } = await adminClient.query<
  214. CreateCustomer.Mutation,
  215. CreateCustomer.Variables
  216. >(CREATE_CUSTOMER, {
  217. input: {
  218. firstName: 'Test',
  219. lastName: 'Person',
  220. emailAddress: testEmailAddress,
  221. },
  222. password: 'password1',
  223. });
  224. customerGuard.assertSuccess(result1);
  225. await adminClient.query<DeleteCustomer.Mutation, DeleteCustomer.Variables>(DELETE_CUSTOMER, {
  226. id: result1.id,
  227. });
  228. const { createCustomer: result2 } = await adminClient.query<
  229. CreateCustomer.Mutation,
  230. CreateCustomer.Variables
  231. >(CREATE_CUSTOMER, {
  232. input: {
  233. firstName: 'Test',
  234. lastName: 'Person',
  235. emailAddress: testEmailAddress,
  236. },
  237. password: 'password2',
  238. });
  239. customerGuard.assertSuccess(result2);
  240. const { authenticate } = await shopClient.query(AUTHENTICATE, {
  241. input: {
  242. native: {
  243. username: testEmailAddress,
  244. password: 'password2',
  245. },
  246. },
  247. });
  248. currentUserGuard.assertSuccess(authenticate);
  249. expect(pick(authenticate, ['id', 'identifier'])).toEqual({
  250. id: result2.user!.id,
  251. identifier: result2.emailAddress,
  252. });
  253. });
  254. });
  255. });
  256. const AUTHENTICATE = gql`
  257. mutation Authenticate($input: AuthenticationInput!) {
  258. authenticate(input: $input) {
  259. ...CurrentUser
  260. ... on InvalidCredentialsError {
  261. authenticationError
  262. errorCode
  263. message
  264. }
  265. }
  266. }
  267. ${CURRENT_USER_FRAGMENT}
  268. `;
  269. const GET_CUSTOMERS = gql`
  270. query GetCustomers {
  271. customers {
  272. totalItems
  273. items {
  274. id
  275. emailAddress
  276. }
  277. }
  278. }
  279. `;
  280. const GET_CUSTOMER_USER_AUTH = gql`
  281. query GetCustomerUserAuth($id: ID!) {
  282. customer(id: $id) {
  283. id
  284. user {
  285. id
  286. verified
  287. authenticationMethods {
  288. id
  289. strategy
  290. }
  291. }
  292. }
  293. }
  294. `;