read-user-info.js 2.0 KB

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