get-identity.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. const npmFetch = require('npm-registry-fetch')
  2. const needsAuthError = (msg) =>
  3. Object.assign(new Error(msg), { code: 'ENEEDAUTH' })
  4. module.exports = async (npm, opts = {}) => {
  5. const { registry } = opts
  6. if (!registry)
  7. throw Object.assign(new Error('No registry specified.'), { code: 'ENOREGISTRY' })
  8. // First, check if we have a user/pass-based auth
  9. const creds = npm.config.getCredentialsByURI(registry)
  10. const { username: usernameFromURI, token } = creds
  11. if (usernameFromURI) {
  12. // Found username; return it
  13. return usernameFromURI
  14. } else if (token) {
  15. // No username, but we have a token; fetch the username from registry
  16. const registryData = await npmFetch.json('/-/whoami', {
  17. ...opts,
  18. })
  19. const { username: usernameFromRegistry } = registryData
  20. // Retrieved username from registry; return it
  21. if (usernameFromRegistry)
  22. return usernameFromRegistry
  23. else {
  24. // Didn't get username from registry; bad token
  25. throw needsAuthError(
  26. 'Your auth token is no longer valid. Please login again.'
  27. )
  28. }
  29. } else {
  30. // At this point, if they have a credentials object, it doesn't have a
  31. // token or auth in it. Probably just the default registry.
  32. throw needsAuthError('This command requires you to be logged in.')
  33. }
  34. }