legacy.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const log = require('npmlog')
  2. const profile = require('npm-profile')
  3. const openUrl = require('../utils/open-url.js')
  4. const read = require('../utils/read-user-info.js')
  5. const loginPrompter = async (creds) => {
  6. const opts = { log: log }
  7. creds.username = await read.username('Username:', creds.username, opts)
  8. creds.password = await read.password('Password:', creds.password)
  9. creds.email = await read.email('Email: (this IS public) ', creds.email, opts)
  10. return creds
  11. }
  12. const login = async (npm, opts) => {
  13. let res
  14. const requestOTP = async () => {
  15. const otp = await read.otp(
  16. 'Enter one-time password from your authenticator app: '
  17. )
  18. return profile.loginCouch(
  19. opts.creds.username,
  20. opts.creds.password,
  21. { ...opts, otp }
  22. )
  23. }
  24. const addNewUser = async () => {
  25. let newUser
  26. try {
  27. newUser = await profile.adduserCouch(
  28. opts.creds.username,
  29. opts.creds.email,
  30. opts.creds.password,
  31. opts
  32. )
  33. } catch (err) {
  34. if (err.code === 'EOTP')
  35. newUser = await requestOTP()
  36. else
  37. throw err
  38. }
  39. return newUser
  40. }
  41. const openerPromise = (url) => openUrl(npm, url, 'to complete your login please visit')
  42. try {
  43. res = await profile.login(openerPromise, loginPrompter, opts)
  44. } catch (err) {
  45. const needsMoreInfo = !(opts &&
  46. opts.creds &&
  47. opts.creds.username &&
  48. opts.creds.password &&
  49. opts.creds.email)
  50. if (err.code === 'EOTP')
  51. res = await requestOTP()
  52. else if (needsMoreInfo)
  53. throw err
  54. else {
  55. // TODO: maybe this needs to check for err.code === 'E400' instead?
  56. res = await addNewUser()
  57. }
  58. }
  59. const newCreds = {}
  60. if (res && res.token)
  61. newCreds.token = res.token
  62. else {
  63. newCreds.username = opts.creds.username
  64. newCreds.password = opts.creds.password
  65. newCreds.email = opts.creds.email
  66. newCreds.alwaysAuth = opts.creds.alwaysAuth
  67. }
  68. const usermsg = opts.creds.username ? ` user ${opts.creds.username}` : ''
  69. const scopeMessage = opts.scope ? ` to scope ${opts.scope}` : ''
  70. const userout = opts.creds.username ? ` as ${opts.creds.username}` : ''
  71. const message = `Logged in${userout}${scopeMessage} on ${opts.registry}.`
  72. log.info('login', `Authorized${usermsg}`)
  73. return {
  74. message,
  75. newCreds,
  76. }
  77. }
  78. module.exports = login