auth.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict'
  2. const config = require('./config.js')
  3. const url = require('url')
  4. module.exports = getAuth
  5. function getAuth (registry, opts) {
  6. if (!registry) { throw new Error('registry is required') }
  7. opts = config(opts)
  8. let AUTH = {}
  9. const regKey = registry && registryKey(registry)
  10. if (opts.forceAuth) {
  11. opts = opts.forceAuth
  12. }
  13. const doKey = (key, alias) => addKey(opts, AUTH, regKey, key, alias)
  14. doKey('token')
  15. doKey('_authToken', 'token')
  16. doKey('username')
  17. doKey('password')
  18. doKey('_password', 'password')
  19. doKey('email')
  20. doKey('_auth')
  21. doKey('otp')
  22. doKey('always-auth', 'alwaysAuth')
  23. if (AUTH.password) {
  24. AUTH.password = Buffer.from(AUTH.password, 'base64').toString('utf8')
  25. }
  26. if (AUTH._auth && !(AUTH.username && AUTH.password)) {
  27. let auth = Buffer.from(AUTH._auth, 'base64').toString()
  28. auth = auth.split(':')
  29. AUTH.username = auth.shift()
  30. AUTH.password = auth.join(':')
  31. }
  32. AUTH.alwaysAuth = AUTH.alwaysAuth === 'false' ? false : !!AUTH.alwaysAuth
  33. return AUTH
  34. }
  35. function addKey (opts, obj, scope, key, objKey) {
  36. if (opts[key]) {
  37. obj[objKey || key] = opts[key]
  38. }
  39. if (scope && opts[`${scope}:${key}`]) {
  40. obj[objKey || key] = opts[`${scope}:${key}`]
  41. }
  42. }
  43. // Called a nerf dart in the main codebase. Used as a "safe"
  44. // key when fetching registry info from config.
  45. function registryKey (registry) {
  46. const parsed = url.parse(registry)
  47. const formatted = url.format({
  48. host: parsed.host,
  49. pathname: parsed.pathname,
  50. slashes: parsed.slashes
  51. })
  52. return url.resolve(formatted, '.')
  53. }