codekingpro/portable-devtools
114k
1const npmFetch = require('npm-registry-fetch')
2
3module.exports = async (npm, opts) => {
4 const { registry } = opts
5
6 // First, check if we have a user/pass-based auth
7 const creds = npm.config.getCredentialsByURI(registry)
8 if (creds.username) {
9 return creds.username
10 }
11
12 // No username, but we have other credentials; fetch the username from registry
13 if (creds.token || creds.certfile && creds.keyfile) {
14 const registryData = await npmFetch.json('/-/whoami', { ...opts })
15 if (typeof registryData?.username === 'string') {
16 return registryData.username
17 }
18 }
19
20 // At this point, even if they have a credentials object, it doesn't have a valid token.
21 throw Object.assign(
22 new Error('This command requires you to be logged in.'),
23 { code: 'ENEEDAUTH' }
24 )
25}
26 