auth.e2e-spec.ts 12 KB

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