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