logout.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const npmFetch = require('npm-registry-fetch')
  2. const { getAuth } = npmFetch
  3. const { log } = require('proc-log')
  4. const BaseCommand = require('../base-cmd.js')
  5. class Logout extends BaseCommand {
  6. static description = 'Log out of the registry'
  7. static name = 'logout'
  8. static params = [
  9. 'registry',
  10. 'scope',
  11. ]
  12. async exec () {
  13. const registry = this.npm.config.get('registry')
  14. const scope = this.npm.config.get('scope')
  15. const regRef = scope ? `${scope}:registry` : 'registry'
  16. const reg = this.npm.config.get(regRef) || registry
  17. const auth = getAuth(reg, this.npm.flatOptions)
  18. const level = this.npm.config.find(`${auth.regKey}:${auth.authKey}`)
  19. // find the config level and only delete from there
  20. if (auth.token) {
  21. log.verbose('logout', `clearing token for ${reg}`)
  22. await npmFetch(`/-/user/token/${encodeURIComponent(auth.token)}`, {
  23. ...this.npm.flatOptions,
  24. registry: reg,
  25. method: 'DELETE',
  26. ignoreBody: true,
  27. })
  28. } else if (auth.isBasicAuth) {
  29. log.verbose('logout', `clearing user credentials for ${reg}`)
  30. } else {
  31. const msg = `not logged in to ${reg}, so can't log out!`
  32. throw Object.assign(new Error(msg), { code: 'ENEEDAUTH' })
  33. }
  34. if (scope) {
  35. this.npm.config.delete(regRef, level)
  36. }
  37. this.npm.config.clearCredentialsByURI(reg, level)
  38. await this.npm.config.save(level)
  39. }
  40. }
  41. module.exports = Logout