get-npm-username.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. const { ValidationError } = require("@lerna/validation-error");
  3. const { getFetchConfig } = require("./fetch-config");
  4. const { getProfileData } = require("./get-profile-data");
  5. const { getWhoAmI } = require("./get-whoami");
  6. module.exports.getNpmUsername = getNpmUsername;
  7. /**
  8. * Retrieve username of logged-in user.
  9. * @param {import("./fetch-config").FetchConfig} options
  10. * @returns {Promise<string>}
  11. */
  12. function getNpmUsername(options) {
  13. const opts = getFetchConfig(options, {
  14. // don't wait forever for third-party failures to be dealt with
  15. fetchRetries: 0,
  16. });
  17. opts.log.info("", "Verifying npm credentials");
  18. return getProfileData(opts)
  19. .catch((err) => {
  20. // Many third-party registries do not implement the user endpoint
  21. // Legacy npm Enterprise returns E500 instead of E404
  22. if (err.code === "E500" || err.code === "E404") {
  23. return getWhoAmI(opts);
  24. }
  25. // re-throw 401 Unauthorized (and all other unexpected errors)
  26. throw err;
  27. })
  28. .then(success, failure);
  29. function success(result) {
  30. opts.log.silly("get npm username", "received %j", result);
  31. if (!result.username) {
  32. throw new ValidationError(
  33. "ENEEDAUTH",
  34. "You must be logged in to publish packages. Use `npm login` and try again."
  35. );
  36. }
  37. return result.username;
  38. }
  39. // catch request errors, not auth expired errors
  40. function failure(err) {
  41. // Log the error cleanly to stderr
  42. opts.log.pause();
  43. console.error(err.message); // eslint-disable-line no-console
  44. opts.log.resume();
  45. if (opts.registry === "https://registry.npmjs.org/") {
  46. throw new ValidationError("EWHOAMI", "Authentication error. Use `npm whoami` to troubleshoot.");
  47. }
  48. opts.log.warn(
  49. "EWHOAMI",
  50. "Unable to determine npm username from third-party registry, this command will likely fail soon!"
  51. );
  52. }
  53. }