|
| 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 | + |
| 11 | +class AddUser extends BaseCommand { |
| 12 | + static get description () { |
| 13 | + return 'Add a registry user account' |
| 14 | + } |
| 15 | + |
| 16 | + static get name () { |
| 17 | + return 'adduser' |
| 18 | + } |
| 19 | + |
| 20 | + static get params () { |
| 21 | + return [ |
| 22 | + 'registry', |
| 23 | + 'scope', |
| 24 | + ] |
| 25 | + } |
| 26 | + |
| 27 | + exec (args, cb) { |
| 28 | + this.adduser(args).then(() => cb()).catch(cb) |
| 29 | + } |
| 30 | + |
| 31 | + async adduser (args) { |
| 32 | + const scope = this.npm.config.get('scope') |
| 33 | + console.log(scope) |
| 34 | + const registry = this.getRegistry(this.npm.flatOptions) |
| 35 | + const auth = this.getAuthType(this.npm.flatOptions) |
| 36 | + const creds = this.npm.config.getCredentialsByURI(registry) |
| 37 | + |
| 38 | + log.disableProgress() |
| 39 | + |
| 40 | + log.notice('', `Log in on ${replaceInfo(registry)}`) |
| 41 | + |
| 42 | + const { message, newCreds } = await auth(this.npm, { |
| 43 | + ...this.npm.flatOptions, |
| 44 | + creds, |
| 45 | + registry, |
| 46 | + scope, |
| 47 | + }) |
| 48 | + |
| 49 | + await this.updateConfig({ |
| 50 | + newCreds, |
| 51 | + registry, |
| 52 | + scope, |
| 53 | + }) |
| 54 | + |
| 55 | + this.npm.output(message) |
| 56 | + } |
| 57 | + |
| 58 | + getRegistry ({ scope, registry }) { |
| 59 | + if (scope) { |
| 60 | + const scopedRegistry = this.npm.config.get(`${scope}:registry`) |
| 61 | + const cliRegistry = this.npm.config.get('registry', 'cli') |
| 62 | + if (scopedRegistry && !cliRegistry) |
| 63 | + return scopedRegistry |
| 64 | + } |
| 65 | + return registry |
| 66 | + } |
| 67 | + |
| 68 | + getAuthType ({ authType }) { |
| 69 | + const type = authTypes[authType] |
| 70 | + |
| 71 | + if (!type) |
| 72 | + throw new Error('no such auth module') |
| 73 | + |
| 74 | + return type |
| 75 | + } |
| 76 | + |
| 77 | + async updateConfig ({ newCreds, registry, scope }) { |
| 78 | + this.npm.config.delete('_token', 'user') // prevent legacy pollution |
| 79 | + |
| 80 | + this.npm.config.setCredentialsByURI(registry, newCreds) |
| 81 | + |
| 82 | + if (scope) |
| 83 | + this.npm.config.set(scope + ':registry', registry, 'user') |
| 84 | + await this.npm.config.save('user') |
| 85 | + } |
| 86 | +} |
| 87 | +module.exports = AddUser |
0 commit comments