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