auth.e2e-spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import { DocumentNode } from 'graphql';
  2. import gql from 'graphql-tag';
  3. import path from 'path';
  4. import {
  5. CREATE_ADMINISTRATOR,
  6. CREATE_ROLE,
  7. } from '../../admin-ui/src/app/data/definitions/administrator-definitions';
  8. import { ATTEMPT_LOGIN } from '../../admin-ui/src/app/data/definitions/auth-definitions';
  9. import {
  10. CREATE_PRODUCT,
  11. GET_PRODUCT_LIST,
  12. UPDATE_PRODUCT,
  13. } from '../../admin-ui/src/app/data/definitions/product-definitions';
  14. import {
  15. CreateAdministrator,
  16. CreateProductMutationArgs,
  17. CreateRole,
  18. LoginMutationArgs,
  19. Permission,
  20. RegisterCustomerInput,
  21. UpdateProductMutationArgs,
  22. } from '../../shared/generated-types';
  23. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '../../shared/shared-constants';
  24. import { NoopEmailGenerator } from '../src/config/email/noop-email-generator';
  25. import { defaultEmailTypes } from '../src/email/default-email-types';
  26. import { TEST_SETUP_TIMEOUT_MS } from './config/test-config';
  27. import { TestClient } from './test-client';
  28. import { TestServer } from './test-server';
  29. describe('Authorization & permissions', () => {
  30. const client = new TestClient();
  31. const server = new TestServer();
  32. let sendEmailFn: jest.Mock;
  33. beforeAll(async () => {
  34. const token = await server.init(
  35. {
  36. productCount: 1,
  37. customerCount: 1,
  38. },
  39. {
  40. emailOptions: {
  41. emailTemplatePath: 'src/email/templates',
  42. emailTypes: defaultEmailTypes,
  43. generator: new NoopEmailGenerator(),
  44. transport: {
  45. type: 'testing',
  46. onSend: ctx => sendEmailFn(ctx),
  47. },
  48. },
  49. },
  50. );
  51. await client.init();
  52. }, TEST_SETUP_TIMEOUT_MS);
  53. afterAll(async () => {
  54. await server.destroy();
  55. });
  56. describe('admin permissions', () => {
  57. describe('Anonymous user', () => {
  58. beforeAll(async () => {
  59. await client.asAnonymousUser();
  60. });
  61. it('can attempt login', async () => {
  62. await assertRequestAllowed<LoginMutationArgs>(ATTEMPT_LOGIN, {
  63. username: SUPER_ADMIN_USER_IDENTIFIER,
  64. password: SUPER_ADMIN_USER_PASSWORD,
  65. rememberMe: false,
  66. });
  67. });
  68. });
  69. describe('ReadCatalog', () => {
  70. beforeAll(async () => {
  71. await client.asSuperAdmin();
  72. const { identifier, password } = await createAdministratorWithPermissions('ReadCatalog', [
  73. Permission.ReadCatalog,
  74. ]);
  75. await client.asUserWithCredentials(identifier, password);
  76. });
  77. it('can read', async () => {
  78. await assertRequestAllowed(GET_PRODUCT_LIST);
  79. });
  80. it('cannot uppdate', async () => {
  81. await assertRequestForbidden<UpdateProductMutationArgs>(UPDATE_PRODUCT, {
  82. input: {
  83. id: '1',
  84. translations: [],
  85. },
  86. });
  87. });
  88. it('cannot create', async () => {
  89. await assertRequestForbidden<CreateProductMutationArgs>(CREATE_PRODUCT, {
  90. input: {
  91. translations: [],
  92. },
  93. });
  94. });
  95. });
  96. describe('CRUD on Customers', () => {
  97. beforeAll(async () => {
  98. await client.asSuperAdmin();
  99. const { identifier, password } = await createAdministratorWithPermissions('CRUDCustomer', [
  100. Permission.CreateCustomer,
  101. Permission.ReadCustomer,
  102. Permission.UpdateCustomer,
  103. Permission.DeleteCustomer,
  104. ]);
  105. await client.asUserWithCredentials(identifier, password);
  106. });
  107. it('can create', async () => {
  108. await assertRequestAllowed(
  109. gql`
  110. mutation CreateCustomer($input: CreateCustomerInput!) {
  111. createCustomer(input: $input) {
  112. id
  113. }
  114. }
  115. `,
  116. { input: { emailAddress: '', firstName: '', lastName: '' } },
  117. );
  118. });
  119. it('can read', async () => {
  120. await assertRequestAllowed(gql`
  121. query {
  122. customers {
  123. totalItems
  124. }
  125. }
  126. `);
  127. });
  128. });
  129. });
  130. describe('customer account creation', () => {
  131. const password = 'password';
  132. const emailAddress = 'test1@test.com';
  133. let verificationToken: string;
  134. beforeEach(() => {
  135. sendEmailFn = jest.fn();
  136. });
  137. it('register a new account', async () => {
  138. const verificationTokenPromise = getVerificationTokenPromise();
  139. const input: RegisterCustomerInput = {
  140. firstName: 'Sean',
  141. lastName: 'Tester',
  142. emailAddress,
  143. };
  144. const result = await client.query(REGISTER_ACCOUNT, { input });
  145. verificationToken = await verificationTokenPromise;
  146. expect(result.registerCustomerAccount).toBe(true);
  147. expect(sendEmailFn).toHaveBeenCalled();
  148. expect(verificationToken).toBeDefined();
  149. });
  150. it('issues a new token if attempting to register a second time', async () => {
  151. const sendEmail = new Promise<string>(resolve => {
  152. sendEmailFn.mockImplementation(ctx => {
  153. resolve(ctx.event.user.verificationToken);
  154. });
  155. });
  156. const input: RegisterCustomerInput = {
  157. firstName: 'Sean',
  158. lastName: 'Tester',
  159. emailAddress,
  160. };
  161. const result = await client.query(REGISTER_ACCOUNT, { input });
  162. const newVerificationToken = await sendEmail;
  163. expect(result.registerCustomerAccount).toBe(true);
  164. expect(sendEmailFn).toHaveBeenCalled();
  165. expect(newVerificationToken).not.toBe(verificationToken);
  166. verificationToken = newVerificationToken;
  167. });
  168. it('refreshCustomerVerification issues a new token', async () => {
  169. const sendEmail = new Promise<string>(resolve => {
  170. sendEmailFn.mockImplementation(ctx => {
  171. resolve(ctx.event.user.verificationToken);
  172. });
  173. });
  174. const result = await client.query(REFRESH_TOKEN, { emailAddress });
  175. const newVerificationToken = await sendEmail;
  176. expect(result.refreshCustomerVerification).toBe(true);
  177. expect(sendEmailFn).toHaveBeenCalled();
  178. expect(newVerificationToken).not.toBe(verificationToken);
  179. verificationToken = newVerificationToken;
  180. });
  181. it('refreshCustomerVerification does nothing with an unrecognized emailAddress', async () => {
  182. const result = await client.query(REFRESH_TOKEN, {
  183. emailAddress: 'never-been-registered@test.com',
  184. });
  185. await waitForSendEmailFn();
  186. expect(result.refreshCustomerVerification).toBe(true);
  187. expect(sendEmailFn).not.toHaveBeenCalled();
  188. });
  189. it('login fails before verification', async () => {
  190. try {
  191. await client.asUserWithCredentials(emailAddress, '');
  192. fail('should have thrown');
  193. } catch (err) {
  194. expect(getErrorCode(err)).toBe('UNAUTHORIZED');
  195. }
  196. });
  197. it('verification fails with wrong token', async () => {
  198. try {
  199. await client.query(VERIFY_EMAIL, {
  200. password,
  201. token: 'bad-token',
  202. });
  203. fail('should have thrown');
  204. } catch (err) {
  205. expect(err.message).toEqual(expect.stringContaining(`Verification token not recognized`));
  206. }
  207. });
  208. it('verification succeeds with correct token', async () => {
  209. const result = await client.query(VERIFY_EMAIL, {
  210. password,
  211. token: verificationToken,
  212. });
  213. expect(result.verifyCustomerAccount.user.identifier).toBe('test1@test.com');
  214. });
  215. it('registration silently fails if attempting to register an email already verified', async () => {
  216. const input: RegisterCustomerInput = {
  217. firstName: 'Dodgy',
  218. lastName: 'Hacker',
  219. emailAddress,
  220. };
  221. const result = await client.query(REGISTER_ACCOUNT, { input });
  222. await waitForSendEmailFn();
  223. expect(result.registerCustomerAccount).toBe(true);
  224. expect(sendEmailFn).not.toHaveBeenCalled();
  225. });
  226. it('verification fails if attempted a second time', async () => {
  227. try {
  228. await client.query(VERIFY_EMAIL, {
  229. password,
  230. token: verificationToken,
  231. });
  232. fail('should have thrown');
  233. } catch (err) {
  234. expect(err.message).toEqual(expect.stringContaining(`Verification token not recognized`));
  235. }
  236. });
  237. });
  238. function getVerificationTokenPromise(): Promise<string> {
  239. return new Promise<string>(resolve => {
  240. sendEmailFn.mockImplementation(ctx => {
  241. resolve(ctx.event.user.verificationToken);
  242. });
  243. });
  244. }
  245. async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) {
  246. try {
  247. const status = await client.queryStatus(operation, variables);
  248. expect(status).toBe(200);
  249. } catch (e) {
  250. const errorCode = getErrorCode(e);
  251. if (!errorCode) {
  252. fail(`Unexpected failure: ${e}`);
  253. } else {
  254. fail(`Operation should be allowed, got status ${getErrorCode(e)}`);
  255. }
  256. }
  257. }
  258. async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) {
  259. try {
  260. const status = await client.query(operation, variables);
  261. fail(`Should have thrown`);
  262. } catch (e) {
  263. expect(getErrorCode(e)).toBe('FORBIDDEN');
  264. }
  265. }
  266. function getErrorCode(err: any): string {
  267. return err.response.errors[0].extensions.code;
  268. }
  269. async function createAdministratorWithPermissions(
  270. code: string,
  271. permissions: Permission[],
  272. ): Promise<{ identifier: string; password: string }> {
  273. const roleResult = await client.query<CreateRole.Mutation, CreateRole.Variables>(CREATE_ROLE, {
  274. input: {
  275. code,
  276. description: '',
  277. permissions,
  278. },
  279. });
  280. const role = roleResult.createRole;
  281. const identifier = `${code}@${Math.random()
  282. .toString(16)
  283. .substr(2, 8)}`;
  284. const password = `test`;
  285. const adminResult = await client.query<CreateAdministrator.Mutation, CreateAdministrator.Variables>(
  286. CREATE_ADMINISTRATOR,
  287. {
  288. input: {
  289. emailAddress: identifier,
  290. firstName: code,
  291. lastName: 'Admin',
  292. password,
  293. roleIds: [role.id],
  294. },
  295. },
  296. );
  297. const admin = adminResult.createAdministrator;
  298. return {
  299. identifier,
  300. password,
  301. };
  302. }
  303. /**
  304. * A "sleep" function which allows the sendEmailFn time to get called.
  305. */
  306. function waitForSendEmailFn() {
  307. return new Promise(resolve => setTimeout(resolve, 10));
  308. }
  309. const REGISTER_ACCOUNT = gql`
  310. mutation Register($input: RegisterCustomerInput!) {
  311. registerCustomerAccount(input: $input)
  312. }
  313. `;
  314. const VERIFY_EMAIL = gql`
  315. mutation Verify($password: String!, $token: String!) {
  316. verifyCustomerAccount(password: $password, token: $token) {
  317. user {
  318. id
  319. identifier
  320. }
  321. }
  322. }
  323. `;
  324. const REFRESH_TOKEN = gql`
  325. mutation RefreshToken($emailAddress: String!) {
  326. refreshCustomerVerification(emailAddress: $emailAddress)
  327. }
  328. `;
  329. });