logout.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const log = require('npmlog')
  2. const getAuth = require('npm-registry-fetch/auth.js')
  3. const npmFetch = require('npm-registry-fetch')
  4. const BaseCommand = require('./base-command.js')
  5. class Logout extends BaseCommand {
  6. /* istanbul ignore next - see test/lib/load-all-commands.js */
  7. static get description () {
  8. return 'Log out of the registry'
  9. }
  10. /* istanbul ignore next - see test/lib/load-all-commands.js */
  11. static get name () {
  12. return 'logout'
  13. }
  14. /* istanbul ignore next - see test/lib/load-all-commands.js */
  15. static get params () {
  16. return [
  17. 'registry',
  18. 'scope',
  19. ]
  20. }
  21. exec (args, cb) {
  22. this.logout(args).then(() => cb()).catch(cb)
  23. }
  24. async logout (args) {
  25. const registry = this.npm.config.get('registry')
  26. const scope = this.npm.config.get('scope')
  27. const regRef = scope ? `${scope}:registry` : 'registry'
  28. const reg = this.npm.config.get(regRef) || registry
  29. const auth = getAuth(reg, this.npm.flatOptions)
  30. if (auth.token) {
  31. log.verbose('logout', `clearing token for ${reg}`)
  32. await npmFetch(`/-/user/token/${encodeURIComponent(auth.token)}`, {
  33. ...this.npm.flatOptions,
  34. method: 'DELETE',
  35. ignoreBody: true,
  36. })
  37. } else if (auth.isBasicAuth)
  38. log.verbose('logout', `clearing user credentials for ${reg}`)
  39. else {
  40. const msg = `not logged in to ${reg}, so can't log out!`
  41. throw Object.assign(new Error(msg), { code: 'ENEEDAUTH' })
  42. }
  43. if (scope)
  44. this.npm.config.delete(regRef, 'user')
  45. this.npm.config.clearCredentialsByURI(reg)
  46. await this.npm.config.save('user')
  47. }
  48. }
  49. module.exports = Logout