read-user-info.js 2.0 KB

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