| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541 |
- /* tslint:disable:no-non-null-assertion */
- import { DocumentNode } from 'graphql';
- import gql from 'graphql-tag';
- import path from 'path';
- import {
- CREATE_ADMINISTRATOR,
- CREATE_ROLE,
- } from '../../admin-ui/src/app/data/definitions/administrator-definitions';
- import { GET_CUSTOMER } from '../../admin-ui/src/app/data/definitions/customer-definitions';
- import { RegisterCustomerInput } from '../../shared/generated-shop-types';
- import { CreateAdministrator, CreateRole, GetCustomer, Permission } from '../../shared/generated-types';
- import { NoopEmailGenerator } from '../src/config/email/noop-email-generator';
- import { defaultEmailTypes } from '../src/email/default-email-types';
- import { TEST_SETUP_TIMEOUT_MS } from './config/test-config';
- import { TestAdminClient, TestShopClient } from './test-client';
- import { TestServer } from './test-server';
- import { assertThrowsWithMessage } from './test-utils';
- let sendEmailFn: jest.Mock;
- const emailOptions = {
- emailTemplatePath: 'src/email/templates',
- emailTypes: defaultEmailTypes,
- generator: new NoopEmailGenerator(),
- transport: {
- type: 'testing' as 'testing',
- onSend: ctx => sendEmailFn(ctx),
- },
- };
- describe('Shop auth & accounts', () => {
- const shopClient = new TestShopClient();
- const adminClient = new TestAdminClient();
- const server = new TestServer();
- beforeAll(async () => {
- const token = await server.init(
- {
- productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
- customerCount: 1,
- },
- {
- emailOptions,
- },
- );
- await shopClient.init();
- await adminClient.init();
- }, TEST_SETUP_TIMEOUT_MS);
- afterAll(async () => {
- await server.destroy();
- });
- describe('customer account creation', () => {
- const password = 'password';
- const emailAddress = 'test1@test.com';
- let verificationToken: string;
- beforeEach(() => {
- sendEmailFn = jest.fn();
- });
- it(
- 'errors if a password is provided',
- assertThrowsWithMessage(async () => {
- const input: RegisterCustomerInput = {
- firstName: 'Sofia',
- lastName: 'Green',
- emailAddress: 'sofia.green@test.com',
- password: 'test',
- };
- const result = await shopClient.query(REGISTER_ACCOUNT, { input });
- }, 'Do not provide a password when `authOptions.requireVerification` is set to "true"'),
- );
- it('register a new account', async () => {
- const verificationTokenPromise = getVerificationTokenPromise();
- const input: RegisterCustomerInput = {
- firstName: 'Sean',
- lastName: 'Tester',
- emailAddress,
- };
- const result = await shopClient.query(REGISTER_ACCOUNT, { input });
- verificationToken = await verificationTokenPromise;
- expect(result.registerCustomerAccount).toBe(true);
- expect(sendEmailFn).toHaveBeenCalled();
- expect(verificationToken).toBeDefined();
- });
- it('issues a new token if attempting to register a second time', async () => {
- const sendEmail = new Promise<string>(resolve => {
- sendEmailFn.mockImplementation(ctx => {
- resolve(ctx.event.user.verificationToken);
- });
- });
- const input: RegisterCustomerInput = {
- firstName: 'Sean',
- lastName: 'Tester',
- emailAddress,
- };
- const result = await shopClient.query(REGISTER_ACCOUNT, { input });
- const newVerificationToken = await sendEmail;
- expect(result.registerCustomerAccount).toBe(true);
- expect(sendEmailFn).toHaveBeenCalled();
- expect(newVerificationToken).not.toBe(verificationToken);
- verificationToken = newVerificationToken;
- });
- it('refreshCustomerVerification issues a new token', async () => {
- const sendEmail = new Promise<string>(resolve => {
- sendEmailFn.mockImplementation(ctx => {
- resolve(ctx.event.user.verificationToken);
- });
- });
- const result = await shopClient.query(REFRESH_TOKEN, { emailAddress });
- const newVerificationToken = await sendEmail;
- expect(result.refreshCustomerVerification).toBe(true);
- expect(sendEmailFn).toHaveBeenCalled();
- expect(newVerificationToken).not.toBe(verificationToken);
- verificationToken = newVerificationToken;
- });
- it('refreshCustomerVerification does nothing with an unrecognized emailAddress', async () => {
- const result = await shopClient.query(REFRESH_TOKEN, {
- emailAddress: 'never-been-registered@test.com',
- });
- await waitForSendEmailFn();
- expect(result.refreshCustomerVerification).toBe(true);
- expect(sendEmailFn).not.toHaveBeenCalled();
- });
- it('login fails before verification', async () => {
- try {
- await shopClient.asUserWithCredentials(emailAddress, '');
- fail('should have thrown');
- } catch (err) {
- expect(getErrorCode(err)).toBe('UNAUTHORIZED');
- }
- });
- it(
- 'verification fails with wrong token',
- assertThrowsWithMessage(
- () =>
- shopClient.query(VERIFY_EMAIL, {
- password,
- token: 'bad-token',
- }),
- `Verification token not recognized`,
- ),
- );
- it('verification succeeds with correct token', async () => {
- const result = await shopClient.query(VERIFY_EMAIL, {
- password,
- token: verificationToken,
- });
- expect(result.verifyCustomerAccount.user.identifier).toBe('test1@test.com');
- });
- it('registration silently fails if attempting to register an email already verified', async () => {
- const input: RegisterCustomerInput = {
- firstName: 'Dodgy',
- lastName: 'Hacker',
- emailAddress,
- };
- const result = await shopClient.query(REGISTER_ACCOUNT, { input });
- await waitForSendEmailFn();
- expect(result.registerCustomerAccount).toBe(true);
- expect(sendEmailFn).not.toHaveBeenCalled();
- });
- it(
- 'verification fails if attempted a second time',
- assertThrowsWithMessage(
- () =>
- shopClient.query(VERIFY_EMAIL, {
- password,
- token: verificationToken,
- }),
- `Verification token not recognized`,
- ),
- );
- });
- describe('password reset', () => {
- let passwordResetToken: string;
- let customer: GetCustomer.Customer;
- beforeAll(async () => {
- const result = await adminClient.query<GetCustomer.Query, GetCustomer.Variables>(GET_CUSTOMER, {
- id: 'T_1',
- });
- customer = result.customer!;
- });
- beforeEach(() => {
- sendEmailFn = jest.fn();
- });
- it('requestPasswordReset silently fails with invalid identifier', async () => {
- const result = await shopClient.query(REQUEST_PASSWORD_RESET, {
- identifier: 'invalid-identifier',
- });
- await waitForSendEmailFn();
- expect(result.requestPasswordReset).toBe(true);
- expect(sendEmailFn).not.toHaveBeenCalled();
- expect(passwordResetToken).not.toBeDefined();
- });
- it('requestPasswordReset sends reset token', async () => {
- const passwordResetTokenPromise = getPasswordResetTokenPromise();
- const result = await shopClient.query(REQUEST_PASSWORD_RESET, {
- identifier: customer.emailAddress,
- });
- passwordResetToken = await passwordResetTokenPromise;
- expect(result.requestPasswordReset).toBe(true);
- expect(sendEmailFn).toHaveBeenCalled();
- expect(passwordResetToken).toBeDefined();
- });
- it(
- 'resetPassword fails with wrong token',
- assertThrowsWithMessage(
- () =>
- shopClient.query(RESET_PASSWORD, {
- password: 'newPassword',
- token: 'bad-token',
- }),
- `Password reset token not recognized`,
- ),
- );
- it('resetPassword works with valid token', async () => {
- const result = await shopClient.query(RESET_PASSWORD, {
- token: passwordResetToken,
- password: 'newPassword',
- });
- const loginResult = await shopClient.asUserWithCredentials(customer.emailAddress, 'newPassword');
- expect(loginResult.user.identifier).toBe(customer.emailAddress);
- });
- });
- async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) {
- try {
- const status = await shopClient.queryStatus(operation, variables);
- expect(status).toBe(200);
- } catch (e) {
- const errorCode = getErrorCode(e);
- if (!errorCode) {
- fail(`Unexpected failure: ${e}`);
- } else {
- fail(`Operation should be allowed, got status ${getErrorCode(e)}`);
- }
- }
- }
- async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) {
- try {
- const status = await shopClient.query(operation, variables);
- fail(`Should have thrown`);
- } catch (e) {
- expect(getErrorCode(e)).toBe('FORBIDDEN');
- }
- }
- function getErrorCode(err: any): string {
- return err.response.errors[0].extensions.code;
- }
- async function createAdministratorWithPermissions(
- code: string,
- permissions: Permission[],
- ): Promise<{ identifier: string; password: string }> {
- const roleResult = await shopClient.query<CreateRole.Mutation, CreateRole.Variables>(CREATE_ROLE, {
- input: {
- code,
- description: '',
- permissions,
- },
- });
- const role = roleResult.createRole;
- const identifier = `${code}@${Math.random()
- .toString(16)
- .substr(2, 8)}`;
- const password = `test`;
- const adminResult = await shopClient.query<
- CreateAdministrator.Mutation,
- CreateAdministrator.Variables
- >(CREATE_ADMINISTRATOR, {
- input: {
- emailAddress: identifier,
- firstName: code,
- lastName: 'Admin',
- password,
- roleIds: [role.id],
- },
- });
- const admin = adminResult.createAdministrator;
- return {
- identifier,
- password,
- };
- }
- /**
- * A "sleep" function which allows the sendEmailFn time to get called.
- */
- function waitForSendEmailFn() {
- return new Promise(resolve => setTimeout(resolve, 10));
- }
- });
- describe('Expiring tokens', () => {
- const shopClient = new TestShopClient();
- const adminClient = new TestAdminClient();
- const server = new TestServer();
- beforeAll(async () => {
- const token = await server.init(
- {
- productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
- customerCount: 1,
- },
- {
- emailOptions,
- authOptions: {
- verificationTokenDuration: '1ms',
- },
- },
- );
- await shopClient.init();
- await adminClient.init();
- }, TEST_SETUP_TIMEOUT_MS);
- beforeEach(() => {
- sendEmailFn = jest.fn();
- });
- afterAll(async () => {
- await server.destroy();
- });
- it(
- 'attempting to verify after token has expired throws',
- assertThrowsWithMessage(async () => {
- const verificationTokenPromise = getVerificationTokenPromise();
- const input: RegisterCustomerInput = {
- firstName: 'Barry',
- lastName: 'Wallace',
- emailAddress: 'barry.wallace@test.com',
- };
- const result = await shopClient.query(REGISTER_ACCOUNT, { input });
- const verificationToken = await verificationTokenPromise;
- expect(result.registerCustomerAccount).toBe(true);
- expect(sendEmailFn).toHaveBeenCalledTimes(1);
- expect(verificationToken).toBeDefined();
- await new Promise(resolve => setTimeout(resolve, 3));
- return shopClient.query(VERIFY_EMAIL, {
- password: 'test',
- token: verificationToken,
- });
- }, `Verification token has expired. Use refreshCustomerVerification to send a new token.`),
- );
- it(
- 'attempting to reset password after token has expired throws',
- assertThrowsWithMessage(async () => {
- const { customer } = await adminClient.query<GetCustomer.Query, GetCustomer.Variables>(
- GET_CUSTOMER,
- { id: 'T_1' },
- );
- const passwordResetTokenPromise = getPasswordResetTokenPromise();
- const result = await shopClient.query(REQUEST_PASSWORD_RESET, {
- identifier: customer!.emailAddress,
- });
- const passwordResetToken = await passwordResetTokenPromise;
- expect(result.requestPasswordReset).toBe(true);
- expect(sendEmailFn).toHaveBeenCalledTimes(1);
- expect(passwordResetToken).toBeDefined();
- await new Promise(resolve => setTimeout(resolve, 3));
- return shopClient.query(RESET_PASSWORD, {
- password: 'test',
- token: passwordResetToken,
- });
- }, `Password reset token has expired.`),
- );
- });
- describe('Registration without email verification', () => {
- const shopClient = new TestShopClient();
- const server = new TestServer();
- const userEmailAddress = 'glen.beardsley@test.com';
- beforeAll(async () => {
- const token = await server.init(
- {
- productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
- customerCount: 1,
- },
- {
- emailOptions,
- authOptions: {
- requireVerification: false,
- },
- },
- );
- await shopClient.init();
- }, TEST_SETUP_TIMEOUT_MS);
- beforeEach(() => {
- sendEmailFn = jest.fn();
- });
- afterAll(async () => {
- await server.destroy();
- });
- it(
- 'errors if no password is provided',
- assertThrowsWithMessage(async () => {
- const input: RegisterCustomerInput = {
- firstName: 'Glen',
- lastName: 'Beardsley',
- emailAddress: userEmailAddress,
- };
- const result = await shopClient.query(REGISTER_ACCOUNT, { input });
- }, 'A password must be provided when `authOptions.requireVerification` is set to "false"'),
- );
- it('register a new account with password', async () => {
- const input: RegisterCustomerInput = {
- firstName: 'Glen',
- lastName: 'Beardsley',
- emailAddress: userEmailAddress,
- password: 'test',
- };
- const result = await shopClient.query(REGISTER_ACCOUNT, { input });
- expect(result.registerCustomerAccount).toBe(true);
- expect(sendEmailFn).not.toHaveBeenCalled();
- });
- it('can login after registering', async () => {
- await shopClient.asUserWithCredentials(userEmailAddress, 'test');
- const result = await shopClient.query(
- gql`
- query {
- me {
- identifier
- }
- }
- `,
- );
- expect(result.me.identifier).toBe(userEmailAddress);
- });
- });
- function getVerificationTokenPromise(): Promise<string> {
- return new Promise<string>(resolve => {
- sendEmailFn.mockImplementation(ctx => {
- resolve(ctx.event.user.verificationToken);
- });
- });
- }
- function getPasswordResetTokenPromise(): Promise<string> {
- return new Promise<string>(resolve => {
- sendEmailFn.mockImplementation(ctx => {
- resolve(ctx.event.user.passwordResetToken);
- });
- });
- }
- const REGISTER_ACCOUNT = gql`
- mutation Register($input: RegisterCustomerInput!) {
- registerCustomerAccount(input: $input)
- }
- `;
- const VERIFY_EMAIL = gql`
- mutation Verify($password: String!, $token: String!) {
- verifyCustomerAccount(password: $password, token: $token) {
- user {
- id
- identifier
- }
- }
- }
- `;
- const REFRESH_TOKEN = gql`
- mutation RefreshToken($emailAddress: String!) {
- refreshCustomerVerification(emailAddress: $emailAddress)
- }
- `;
- const REQUEST_PASSWORD_RESET = gql`
- mutation RequestPasswordReset($identifier: String!) {
- requestPasswordReset(emailAddress: $identifier)
- }
- `;
- const RESET_PASSWORD = gql`
- mutation ResetPassword($token: String!, $password: String!) {
- resetPassword(token: $token, password: $password) {
- user {
- id
- identifier
- }
- }
- }
- `;
|