All files / lib logout.js

100% Statements 28/28
100% Branches 12/12
100% Functions 3/3
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48    1x 1x 1x 1x 1x 1x 1x   1x         5x   1x 5x 5x 5x   5x   5x 3x 3x         2x 1x   1x 1x     4x 2x   4x   4x     1x  
'use strict'
 
const eu = encodeURIComponent
const log = require('npmlog')
const getAuth = require('npm-registry-fetch/auth.js')
const npmFetch = require('npm-registry-fetch')
const npm = require('./npm.js')
const usageUtil = require('./utils/usage.js')
const completion = require('./utils/completion/none.js')
 
const usage = usageUtil(
  'logout',
  'npm logout [--registry=<url>] [--scope=<@scope>]'
)
 
const cmd = (args, cb) => logout(args).then(() => cb()).catch(cb)
 
const logout = async (args) => {
  const { registry, scope } = npm.flatOptions
  const regRef = scope ? `${scope}:registry` : 'registry'
  const reg = npm.flatOptions[regRef] || registry
 
  const auth = getAuth(reg, npm.flatOptions)
 
  if (auth.token) {
    log.verbose('logout', `clearing token for ${reg}`)
    await npmFetch(`/-/user/token/${eu(auth.token)}`, {
      ...npm.flatOptions,
      method: 'DELETE',
      ignoreBody: true,
    })
  } else if (auth.username || auth.password)
    log.verbose('logout', `clearing user credentials for ${reg}`)
  else {
    const msg = `not logged in to ${reg}, so can't log out!`
    throw Object.assign(new Error(msg), { code: 'ENEEDAUTH' })
  }
 
  if (scope)
    npm.config.delete(regRef, 'user')
 
  npm.config.clearCredentialsByURI(reg)
 
  await npm.config.save('user')
}
 
module.exports = Object.assign(cmd, { completion, usage })