read-user-info.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict'
  2. const Bluebird = require('bluebird')
  3. const readAsync = Bluebird.promisify(require('read'))
  4. const userValidate = require('npm-user-validate')
  5. const log = require('npmlog')
  6. exports.otp = readOTP
  7. exports.password = readPassword
  8. exports.username = readUsername
  9. exports.email = readEmail
  10. function read (opts) {
  11. return Bluebird.try(() => {
  12. log.clearProgress()
  13. return readAsync(opts)
  14. }).finally(() => {
  15. log.showProgress()
  16. })
  17. }
  18. function readOTP (msg, otp, isRetry) {
  19. if (!msg) {
  20. msg = [
  21. 'This command requires a one-time password (OTP) from your authenticator app.',
  22. 'Enter one below. You can also pass one on the command line by appending --otp=123456.',
  23. 'For more information, see:',
  24. 'https://docs.npmjs.com/getting-started/using-two-factor-authentication',
  25. 'Enter OTP: '
  26. ].join('\n')
  27. }
  28. if (isRetry && otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp)) return otp.replace(/\s+/g, '')
  29. return read({prompt: msg, default: otp || ''})
  30. .then((otp) => readOTP(msg, otp, true))
  31. }
  32. function readPassword (msg, password, isRetry) {
  33. if (!msg) msg = 'npm password: '
  34. if (isRetry && password) return password
  35. return read({prompt: msg, silent: true, default: password || ''})
  36. .then((password) => readPassword(msg, password, true))
  37. }
  38. function readUsername (msg, username, opts, isRetry) {
  39. if (!msg) msg = 'npm username: '
  40. if (isRetry && username) {
  41. const error = userValidate.username(username)
  42. if (error) {
  43. opts.log && opts.log.warn(error.message)
  44. } else {
  45. return Promise.resolve(username.trim())
  46. }
  47. }
  48. return read({prompt: msg, default: username || ''})
  49. .then((username) => readUsername(msg, username, opts, true))
  50. }
  51. function readEmail (msg, email, opts, isRetry) {
  52. if (!msg) msg = 'email (this IS public): '
  53. if (isRetry && email) {
  54. const error = userValidate.email(email)
  55. if (error) {
  56. opts.log && opts.log.warn(error.message)
  57. } else {
  58. return email.trim()
  59. }
  60. }
  61. return read({prompt: msg, default: email || ''})
  62. .then((username) => readEmail(msg, username, opts, true))
  63. }