whoami.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict'
  2. const BB = require('bluebird')
  3. const npmConfig = require('./config/figgy-config.js')
  4. const fetch = require('libnpm/fetch')
  5. const figgyPudding = require('figgy-pudding')
  6. const npm = require('./npm.js')
  7. const output = require('./utils/output.js')
  8. const WhoamiConfig = figgyPudding({
  9. json: {},
  10. registry: {}
  11. })
  12. module.exports = whoami
  13. whoami.usage = 'npm whoami [--registry <registry>]\n(just prints username according to given registry)'
  14. function whoami ([spec], silent, cb) {
  15. // FIXME: need tighter checking on this, but is a breaking change
  16. if (typeof cb !== 'function') {
  17. cb = silent
  18. silent = false
  19. }
  20. const opts = WhoamiConfig(npmConfig())
  21. return BB.try(() => {
  22. // First, check if we have a user/pass-based auth
  23. const registry = opts.registry
  24. if (!registry) throw new Error('no default registry set')
  25. return npm.config.getCredentialsByURI(registry)
  26. }).then(({username, token}) => {
  27. if (username) {
  28. return username
  29. } else if (token) {
  30. return fetch.json('/-/whoami', opts.concat({
  31. spec
  32. })).then(({username}) => {
  33. if (username) {
  34. return username
  35. } else {
  36. throw Object.assign(new Error(
  37. 'Your auth token is no longer valid. Please log in again.'
  38. ), {code: 'ENEEDAUTH'})
  39. }
  40. })
  41. } else {
  42. // At this point, if they have a credentials object, it doesn't have a
  43. // token or auth in it. Probably just the default registry.
  44. throw Object.assign(new Error(
  45. 'This command requires you to be logged in.'
  46. ), {code: 'ENEEDAUTH'})
  47. }
  48. }).then(username => {
  49. if (silent) {
  50. } else if (opts.json) {
  51. output(JSON.stringify(username))
  52. } else {
  53. output(username)
  54. }
  55. return username
  56. }).nodeify(cb)
  57. }