Repository URL to install this package:
|
Version:
7.1.2-patch-delete ▾
|
import { Credentials, CredentialsArray } from '../typings'
function validateCredentials(creds: Credentials) {
if (typeof creds === 'string') {
if (creds.includes(':') === false) {
throw new TypeError(
'auth must have `:` (user:password) when providing a string'
)
}
return
}
if (!Array.isArray(creds)) {
throw new Error('credentials should have been transformed')
}
if (typeof creds[0] !== 'string') {
throw new TypeError('auth option `user` must be a string')
}
if (typeof creds[1] !== 'string') {
throw new TypeError('auth option `pass` must be a string')
}
if (creds.length > 2) {
throw new Error('auth option can only have two keys `[user, pass]`')
}
}
function fromStringToCredentials(creds: string) {
const index = creds.indexOf(':')
return [creds.substr(0, index), creds.substr(index + 1)]
}
function ensureLengthTwo(creds: CredentialsArray) {
if (creds.length === 1) {
if (process.env.NODE_ENV !== 'production') {
console.warn('giving no password for user request')
}
creds.push('')
}
}
export function toAuth(creds: Credentials = ['', '']) {
if (process.env.NODE_ENV !== 'production') {
validateCredentials(creds)
}
if (typeof creds === 'string' && creds.includes(':') === true) {
return fromStringToCredentials(creds)
}
ensureLengthTwo(creds as CredentialsArray)
const authString = (creds as CredentialsArray).join(':')
const buffer = Buffer.from(authString)
return `Basic ${buffer.toString('base64')}`
}