Prompt the user for a `username` and `password` return a `UserSession` This function will run again on any error so it will retry until it works
function authenticate() {
  const authPromtpts = [
    {
      type: "text",
      name: "username",
      message: "Username"
    },
    {
      type: "password",
      name: "password",
      message: "Password"
    }
  ];

  let session;

  // prompts returns a `Promise` that resolves with the users input
  return prompts(authPromtpts)
    .then(({ username, password }) => {
      session = new UserSession({
        username,
        password
      });

      // this will generate a token and use it to get into about a user
      return session.getUser();
    })
    .then(self => {
      return session;
    })
    .catch(error => {
      // in case of an `ArcGISRequestError` assume the `username` and `password`
      // are incorrect run the `authenticate` function again
      if (error.name === "ArcGISRequestError") {
        console.log(
          chalk.bold.red("Incorrect username and/or password please try again")
        );
        return authenticate();
      }

      // if this is a different error just log the error message and exit
      console.log(
        `${chalk.bold.red(error.name)} ${chalk.bold.red(error.message)}`
      );
    });
}