Is it possible to generate username with Lambda trigger PreSignUp_AdminCreateUser?

Viewed 443

I'm looking at generating the username automatically behind the scenes so that users signing up simply need to give their phone number, which then later can be changed without changing the username (main identifier).

Hence, I know it could be done behind the scenes in the client but I'm looking at doing it with a lambda trigger in Cognito, namely the PreSignUp_AdminCreateUser trigger source. The code works well, but I get an error that the username is supposed to be the one that was submitted in the client call on iOS.

My lambda looks like:

"use strict";

exports.handler = function(event, context, callback) {
  if (event.triggerSource === "PreSignUp_SignUp") {
    // generate unique random username
    var username = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < 16; i++) {
        username += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    console.log("Generated a unique username: " + username);
    event.userName = username;
  }
  return callback(null, event);
};

Should this be possible? Has anyone done something similar for Cognito?

1 Answers

That is not possible.

Whether the trigger source is PreSignUp_SignUp or PreSignUp_AdminCreateUser, the event response has only three boolean parameters, namely: autoConfirmUser, autoVerifyPhone and autoVerifyEmail. So, the username must be part of the user attributes in the event request.

See Pre Sign-up Lambda Trigger Parameters.

Related