legacy.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict'
  2. const read = require('../utils/read-user-info.js')
  3. const profile = require('libnpm/profile')
  4. const log = require('npmlog')
  5. const figgyPudding = require('figgy-pudding')
  6. const npmConfig = require('../config/figgy-config.js')
  7. const output = require('../utils/output.js')
  8. const openUrl = require('../utils/open-url')
  9. const openerPromise = (url) => new Promise((resolve, reject) => {
  10. openUrl(url, 'to complete your login please visit', (er) => er ? reject(er) : resolve())
  11. })
  12. const loginPrompter = (creds) => {
  13. const opts = { log: log }
  14. return read.username('Username:', creds.username, opts).then((u) => {
  15. creds.username = u
  16. return read.password('Password:', creds.password)
  17. }).then((p) => {
  18. creds.password = p
  19. return read.email('Email: (this IS public) ', creds.email, opts)
  20. }).then((e) => {
  21. creds.email = e
  22. return creds
  23. })
  24. }
  25. const LoginOpts = figgyPudding({
  26. 'always-auth': {},
  27. creds: {},
  28. log: {default: () => log},
  29. registry: {},
  30. scope: {}
  31. })
  32. module.exports.login = (creds = {}, registry, scope, cb) => {
  33. const opts = LoginOpts(npmConfig()).concat({scope, registry, creds})
  34. login(opts).then((newCreds) => cb(null, newCreds)).catch(cb)
  35. }
  36. function login (opts) {
  37. return profile.login(openerPromise, loginPrompter, opts)
  38. .catch((err) => {
  39. if (err.code === 'EOTP') throw err
  40. const u = opts.creds.username
  41. const p = opts.creds.password
  42. const e = opts.creds.email
  43. if (!(u && p && e)) throw err
  44. return profile.adduserCouch(u, e, p, opts)
  45. })
  46. .catch((err) => {
  47. if (err.code !== 'EOTP') throw err
  48. return read.otp(
  49. 'Enter one-time password from your authenticator app: '
  50. ).then(otp => {
  51. const u = opts.creds.username
  52. const p = opts.creds.password
  53. return profile.loginCouch(u, p, opts.concat({otp}))
  54. })
  55. }).then((result) => {
  56. const newCreds = {}
  57. if (result && result.token) {
  58. newCreds.token = result.token
  59. } else {
  60. newCreds.username = opts.creds.username
  61. newCreds.password = opts.creds.password
  62. newCreds.email = opts.creds.email
  63. newCreds.alwaysAuth = opts['always-auth']
  64. }
  65. const usermsg = opts.creds.username ? ' user ' + opts.creds.username : ''
  66. opts.log.info('login', 'Authorized' + usermsg)
  67. const scopeMessage = opts.scope ? ' to scope ' + opts.scope : ''
  68. const userout = opts.creds.username ? ' as ' + opts.creds.username : ''
  69. output('Logged in%s%s on %s.', userout, scopeMessage, opts.registry)
  70. return newCreds
  71. })
  72. }