auth.e2e-spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. beforeEach(() => {
  57. sendEmailFn = jest.fn();
  58. });
  59. describe('admin permissions', () => {
  60. describe('Anonymous user', () => {
  61. beforeAll(async () => {
  62. await client.asAnonymousUser();
  63. });
  64. it('can attempt login', async () => {
  65. await assertRequestAllowed<LoginMutationArgs>(ATTEMPT_LOGIN, {
  66. username: SUPER_ADMIN_USER_IDENTIFIER,
  67. password: SUPER_ADMIN_USER_PASSWORD,
  68. rememberMe: false,
  69. });
  70. });
  71. });
  72. describe('ReadCatalog', () => {
  73. beforeAll(async () => {
  74. await client.asSuperAdmin();
  75. const { identifier, password } = await createAdministratorWithPermissions('ReadCatalog', [
  76. Permission.ReadCatalog,
  77. ]);
  78. await client.asUserWithCredentials(identifier, password);
  79. });
  80. it('can read', async () => {
  81. await assertRequestAllowed(GET_PRODUCT_LIST);
  82. });
  83. it('cannot uppdate', async () => {
  84. await assertRequestForbidden<UpdateProductMutationArgs>(UPDATE_PRODUCT, {
  85. input: {
  86. id: '1',
  87. translations: [],
  88. },
  89. });
  90. });
  91. it('cannot create', async () => {
  92. await assertRequestForbidden<CreateProductMutationArgs>(CREATE_PRODUCT, {
  93. input: {
  94. translations: [],
  95. },
  96. });
  97. });
  98. });
  99. describe('CRUD on Customers', () => {
  100. beforeAll(async () => {
  101. await client.asSuperAdmin();
  102. const { identifier, password } = await createAdministratorWithPermissions('CRUDCustomer', [
  103. Permission.CreateCustomer,
  104. Permission.ReadCustomer,
  105. Permission.UpdateCustomer,
  106. Permission.DeleteCustomer,
  107. ]);
  108. await client.asUserWithCredentials(identifier, password);
  109. });
  110. it('can create', async () => {
  111. await assertRequestAllowed(
  112. gql`
  113. mutation CreateCustomer($input: CreateCustomerInput!) {
  114. createCustomer(input: $input) {
  115. id
  116. }
  117. }
  118. `,
  119. { input: { emailAddress: '', firstName: '', lastName: '' } },
  120. );
  121. });
  122. it('can read', async () => {
  123. await assertRequestAllowed(gql`
  124. query {
  125. customers {
  126. totalItems
  127. }
  128. }
  129. `);
  130. });
  131. });
  132. });
  133. describe('customer account creation', () => {
  134. const password = 'password';
  135. const emailAddress = 'test1@test.com';
  136. let verificationToken: string;
  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. expect(result.refreshCustomerVerification).toBe(true);
  186. expect(sendEmailFn).not.toHaveBeenCalled();
  187. });
  188. it('login fails before verification', async () => {
  189. try {
  190. await client.asUserWithCredentials(emailAddress, '');
  191. fail('should have thrown');
  192. } catch (err) {
  193. expect(getErrorCode(err)).toBe('UNAUTHORIZED');
  194. }
  195. });
  196. it('verification fails with wrong token', async () => {
  197. try {
  198. await client.query(VERIFY_EMAIL, {
  199. password,
  200. token: 'bad-token',
  201. });
  202. fail('should have thrown');
  203. } catch (err) {
  204. expect(err.message).toEqual(expect.stringContaining(`Verification token not recognized`));
  205. }
  206. });
  207. it('verification succeeds with correct token', async () => {
  208. const result = await client.query(VERIFY_EMAIL, {
  209. password,
  210. token: verificationToken,
  211. });
  212. expect(result.verifyCustomerAccount.user.identifier).toBe('test1@test.com');
  213. });
  214. it('verification fails if attempted a second time', async () => {
  215. try {
  216. await client.query(VERIFY_EMAIL, {
  217. password,
  218. token: verificationToken,
  219. });
  220. fail('should have thrown');
  221. } catch (err) {
  222. expect(err.message).toEqual(expect.stringContaining(`Verification token not recognized`));
  223. }
  224. });
  225. });
  226. function getVerificationTokenPromise(): Promise<string> {
  227. return new Promise<string>(resolve => {
  228. sendEmailFn.mockImplementation(ctx => {
  229. resolve(ctx.event.user.verificationToken);
  230. });
  231. });
  232. }
  233. async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) {
  234. try {
  235. const status = await client.queryStatus(operation, variables);
  236. expect(status).toBe(200);
  237. } catch (e) {
  238. const errorCode = getErrorCode(e);
  239. if (!errorCode) {
  240. fail(`Unexpected failure: ${e}`);
  241. } else {
  242. fail(`Operation should be allowed, got status ${getErrorCode(e)}`);
  243. }
  244. }
  245. }
  246. async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) {
  247. try {
  248. const status = await client.query(operation, variables);
  249. fail(`Should have thrown`);
  250. } catch (e) {
  251. expect(getErrorCode(e)).toBe('FORBIDDEN');
  252. }
  253. }
  254. function getErrorCode(err: any): string {
  255. return err.response.errors[0].extensions.code;
  256. }
  257. async function createAdministratorWithPermissions(
  258. code: string,
  259. permissions: Permission[],
  260. ): Promise<{ identifier: string; password: string }> {
  261. const roleResult = await client.query<CreateRole.Mutation, CreateRole.Variables>(CREATE_ROLE, {
  262. input: {
  263. code,
  264. description: '',
  265. permissions,
  266. },
  267. });
  268. const role = roleResult.createRole;
  269. const identifier = `${code}@${Math.random()
  270. .toString(16)
  271. .substr(2, 8)}`;
  272. const password = `test`;
  273. const adminResult = await client.query<CreateAdministrator.Mutation, CreateAdministrator.Variables>(
  274. CREATE_ADMINISTRATOR,
  275. {
  276. input: {
  277. emailAddress: identifier,
  278. firstName: code,
  279. lastName: 'Admin',
  280. password,
  281. roleIds: [role.id],
  282. },
  283. },
  284. );
  285. const admin = adminResult.createAdministrator;
  286. return {
  287. identifier,
  288. password,
  289. };
  290. }
  291. const REGISTER_ACCOUNT = gql`
  292. mutation Register($input: RegisterCustomerInput!) {
  293. registerCustomerAccount(input: $input)
  294. }
  295. `;
  296. const VERIFY_EMAIL = gql`
  297. mutation Verify($password: String!, $token: String!) {
  298. verifyCustomerAccount(password: $password, token: $token) {
  299. user {
  300. id
  301. identifier
  302. }
  303. }
  304. }
  305. `;
  306. const REFRESH_TOKEN = gql`
  307. mutation RefreshToken($emailAddress: String!) {
  308. refreshCustomerVerification(emailAddress: $emailAddress)
  309. }
  310. `;
  311. });