adduser.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const log = require('npmlog')
  2. const replaceInfo = require('./utils/replace-info.js')
  3. const BaseCommand = require('./base-command.js')
  4. const authTypes = {
  5. legacy: require('./auth/legacy.js'),
  6. oauth: require('./auth/oauth.js'),
  7. saml: require('./auth/saml.js'),
  8. sso: require('./auth/sso.js'),
  9. }
  10. class AddUser extends BaseCommand {
  11. static get description () {
  12. return 'Add a registry user account'
  13. }
  14. static get name () {
  15. return 'adduser'
  16. }
  17. static get params () {
  18. return [
  19. 'registry',
  20. 'scope',
  21. ]
  22. }
  23. exec (args, cb) {
  24. this.adduser(args).then(() => cb()).catch(cb)
  25. }
  26. async adduser (args) {
  27. const { scope } = this.npm.flatOptions
  28. const registry = this.getRegistry(this.npm.flatOptions)
  29. const auth = this.getAuthType(this.npm.flatOptions)
  30. const creds = this.npm.config.getCredentialsByURI(registry)
  31. log.disableProgress()
  32. log.notice('', `Log in on ${replaceInfo(registry)}`)
  33. const { message, newCreds } = await auth(this.npm, {
  34. ...this.npm.flatOptions,
  35. creds,
  36. registry,
  37. scope,
  38. })
  39. await this.updateConfig({
  40. newCreds,
  41. registry,
  42. scope,
  43. })
  44. this.npm.output(message)
  45. }
  46. getRegistry ({ scope, registry }) {
  47. if (scope) {
  48. const scopedRegistry = this.npm.config.get(`${scope}:registry`)
  49. const cliRegistry = this.npm.config.get('registry', 'cli')
  50. if (scopedRegistry && !cliRegistry)
  51. return scopedRegistry
  52. }
  53. return registry
  54. }
  55. getAuthType ({ authType }) {
  56. const type = authTypes[authType]
  57. if (!type)
  58. throw new Error('no such auth module')
  59. return type
  60. }
  61. async updateConfig ({ newCreds, registry, scope }) {
  62. this.npm.config.delete('_token', 'user') // prevent legacy pollution
  63. this.npm.config.setCredentialsByURI(registry, newCreds)
  64. if (scope)
  65. this.npm.config.set(scope + ':registry', registry, 'user')
  66. await this.npm.config.save('user')
  67. }
  68. }
  69. module.exports = AddUser