Alexey Korepanov
by Alexey Korepanov
1 min read

Categories

Tags

Many applications require unauthorized/guest user accounts with (probably limited) access to server resources.

Amplify allows guest access but what if you need full-featured Cognito records for such users? What if you would want them to be converted later to the full accounts and keep user preferences and other associated server resources? You can add a Guest User button to the authentication screen which would do the following:

const email = 'guest-' + 'something-random@example.com';
const username = 'random username';
const password = 'random password';
try {
  await Auth.signUp({
    username,
    password,
    attributes: {
      email,
    },
  });
  await Auth.signIn({ username, password });
} catch (error) {
  // Handle errors
}

It will create a Cognito user with random username, password and e-mail.

Unfortunately you would need to set a couple of flags for these users in Cognito. In order to do that run amplify update auth and create a pre-singnup function with the following content:

exports.handler = (event, context, callback) => {
  const { email } = event.request.userAttributes;
  if (/^guest-(.+)@example.com$/.test(email)) {
    const confirm = {
      autoVerifyEmail: true,
      autoConfirmUser: true,
    };
    event.response = confirm;
  }
  context.done(null, event);
};

Now your guest users will automatically become confirmed and will have verified, though non-existing e-mail address.