How to make sign-up invitation only?

meteor, user-accounts

Solution

You can do this with the built in package, but I found it alot easier and powerful to roll a simple implementation.

You'll need to:

- Create a collection, eg `UserInvitations` to contain the invites to become a user.

- Create UI for making `UserInvitations` / insert some using `meteor mongo`

Using `iron-router` or similar create a route, eg:

Router.map ->
  @route 'register',
    path: '/register/:invitationId'
    template: 'userRegistration'
    data: ->
      return {
        invitationId: @params.invitationId
      }
    onBeforeAction: ->
      if Meteor.userId()?
        Router.go('home')
      return

When the form in `userRegistration` is submitted - call

Accounts.createUser({invitationId: Template.instance().data.invitationId /*,.. other fields */})

On the server, make an `Accounts.onCreateUser` hook to pass through the `invitationId` from options to the user

Accounts.onCreateUser(function(options, user){
  user.invitationId = options.invitationId
  return user;
});

Also, on the server make an `Accounts.validateNewUser` hook to check the `invitationId` and mark the invitation as used

Accounts.validateNewUser(function(user){
  check(user.invitationId, String);
  // validate invitation
  invitation = UserInvitations.findOne({_id: user.invitationId, used: false});
  if (!invitation){
    throw new Meteor.Error(403, "Please provide a valid invitation");
  }
  // prevent the token being re-used.
  UserInvitations.update({_id: user.invitationId, used: false}, {$set: {used: true}});

  return true
});

Now, only users that have a valid unused `invitationId` can register.

EDIT: Oct 2014 - Updated to use meteor 0.9.x API's

Problem

Using Meteor accounts (and `accounts-ui`) is there an easy way to make new user sign-ups invitation only? For example by providing an invitation link or an invitation code. The only thing related I could find in the Meteor documentation is Meteor.sendEnrollmentEmail but it doesn't solve my problem.

Original source