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