1.0.0 • Published 6 months ago

@danielbiegler/vendure-plugin-user-registration-guard v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

Banner Image

Vendure Plugin: User Registration Guard

Let's you flexibly customize if and how you prevent users from registering with your Vendure instance.

For example, reduce fraud by blocking disposable email providers or IP ranges from registering with your Vendure instance or harden your admin accounts by only allowing specific domains in email addresses.

Features

  • Let's you create arbitrarily complex assertions for Customer registrations and Administrator creations
  • Logical operators (AND, OR) for when you have multiple checks
  • Publishes a BlockedCustomerRegistrationEvent or BlockedCreateAdministratorEvent on the EventBus for your consumption, for example if you'd like to monitor failed attempts
  • Works via Nestjs Interceptor and does not(!) override the existing mutation APIs (registerCustomerAccount, createAdministrator), which makes this plugin integrate seamlessly with your own resolver overrides
    • Also supports TypeScript Generics so you can use your own extended types!
    • Also let's you inject providers into your assertions i.e. use Vendure's or your own custom services
  • Nicely commented and documented
  • No dependencies

End-To-End Tests

 ✓ user-registration-guard/e2e/email.e2e-spec.ts (4)
 ✓ user-registration-guard/e2e/events.e2e-spec.ts (4)
 ✓ user-registration-guard/e2e/injector.e2e-spec.ts (2)
 ✓ user-registration-guard/e2e/ip.e2e-spec.ts (2)
 ✓ user-registration-guard/e2e/logical-and_fail.e2e-spec.ts (2)
 ✓ user-registration-guard/e2e/logical-and_ok.e2e-spec.ts (2)
 ✓ user-registration-guard/e2e/logical-or_fail.e2e-spec.ts (2)
 ✓ user-registration-guard/e2e/logical-or_ok.e2e-spec.ts (2)
 ✓ user-registration-guard/e2e/reject.e2e-spec.ts (2)

 Test Files  9 passed (9)
      Tests  22 passed (22)

How To: Usage

The plugin does not extend the API, has no dependencies and requires no migration.

1. Add the plugin to your Vendure Config

You can find the package over on npm and install it via:

npm i @danielbiegler/vendure-plugin-user-registration-guard
import { UserRegistrationGuardPlugin } from "@danielbiegler/vendure-plugin-user-registration-guard";
export const config: VendureConfig = {
  // ...
  plugins: [
    UserRegistrationGuardPlugin.init({
      shop: {
        assert: {
          /* AND means every single assertion must
             be true to allow user registration */
          logicalOperator: "AND",
          functions: [ /* Insert your assertions here */ ],
        },
      },
      admin: {
        assert: {
          /* OR means user registration is allowed
             if a single assertion is true */
          logicalOperator: "OR",
          functions: [ /* You may leave this empty too */ ],
        },
      },
    }),
  ],
}

Please refer to the specific docs for how and what you can customize.

2. Create an assertion

Here's an example assertion where we block customer registrations if the email ends with example.com:

const blockExampleDotCom: AssertFunctionShopApi = async (ctx, args, injector) => {
  const isAllowed = !args.input.emailAddress.endsWith("example.com");
  return {
    isAllowed,
    reason: !isAllowed ? 'Failed because email ends with "example.com"' : undefined,
  };
};

The reason field is helpful for when you're subscribing to the published events and want to log or understand why somebody got blocked.

In your assertions, see the types, you'll receive these arguments:

For example, if you'd like to block IP ranges you can access the underlying Express Request object through the RequestContext .

export const onlyAllowLocalIp: AssertFunctionShopApi = async (ctx, args) => {
  // `includes` instead of strict comparison because local ips may include other bits
  return {
    isAllowed: ctx.req?.ip?.includes("127.0.0.1") ?? false,
  };
};

If you'd like to delegate the decision to a service you may inject it like so:

export const example: AssertFunctionShopApi = async (ctx, args, injector) => {
  const service = injector.get(BlacklistService);

  // Make sure to handle errors in a real environment
  return service.canUserRegister(ctx, args);
};

If you've extended your GraphQL API types you may override the TypeScript Generic to get completions in your assertion functions like so:

const example: AssertFunctionShopApi<{ example: boolean; /* ... */ }> = async (ctx, args, injector) => {
  return { isAllowed: args.example };
};

3. Add it to the plugin

import { UserRegistrationGuardPlugin } from "@danielbiegler/vendure-plugin-user-registration-guard";
export const config: VendureConfig = {
  // ...
  plugins: [
    UserRegistrationGuardPlugin.init({
      shop: {
        assert: {
          logicalOperator: "AND",
          functions: [ blockExampleDotCom ],
        },
      },
      admin: {
        assert: {
          logicalOperator: "AND",
          functions: [],
        },
      },
    }),
  ],
}

4. Try registering new customers

mutation {
  registerCustomerAccount(input: {
    emailAddress: "example@example.com",
    # ...
  }) {
    __typename
  }
}

This user will now be blocked from registering according to our blockExampleDotCom assertion.

Handling errors

The plugin is non-intrusive and does not extend the API itself to avoid introducing unhandled errors in your code.

It respects RegisterCustomerAccountResult being a Union, so we don't throw an error, but return a NativeAuthStrategyError. You may handle the error just like the other RegisterCustomerAccountResult types like PasswordValidationError for example.

In contrast, for admins we do throw the error! This is a little different because by default the createAdministrator mutation does not return a Union with error types.

Granted, the NativeAuthStrategyError is technically not correct for blocking registrations and doesn't communicate the blocking properly, but it's the only reasonable error type in the Union for a default non-api-extended Vendure instance. You might want to add some comments in your registration logic that the error means blockage.

5. Subscribe to events

You may want to subscribe to the EventBus to monitor blocked registration attempts.

this.eventBus
  .ofType(BlockedCustomerRegistrationEvent<MutationRegisterCustomerAccountArgs>)
  .subscribe(async (event) => {
    const rejecteds = event.assertions.filter((a) => !a.isAllowed);
    console.log(`Blocked customer registration! ${rejecteds.length}/${event.assertions.length} assertions failed, see reasons:`);
    rejecteds.forEach(r => console.log("  -", r.reason));

    // Example output:
    // Blocked customer registration! 1/1 assertions failed, see reasons:
    //   - Failed because email ends with "example.com"
  });

this.eventBus
  // You can even override the passed in args if you've extended your Graphql API
  .ofType(BlockedCreateAdministratorEvent<{ example: boolean }>).subscribe(async (event) => {
    event.args.example // is typed now! :)
  });

Credits