Skip to content
This repository has been archived by the owner on Oct 16, 2020. It is now read-only.

feat: allow urls with authentication #28

Merged
merged 7 commits into from
Nov 4, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,11 @@ async function getIpfs (opts, { store, getState, dispatch }) {
}
}
if (opts.tryApi) {
const { apiAddress, defaultApiAddress } = getState().ipfs
let { apiAddress, defaultApiAddress } = getState().ipfs
const { location } = root
if (isURL(apiAddress)) {
apiAddress = parseURL(apiAddress)
}
const res = await tryApi({ apiAddress, defaultApiAddress, location, IpfsApi, ipfsConnectionTest })
if (res) {
return dispatch({ type: 'IPFS_INIT_FINISHED', payload: res })
Expand Down Expand Up @@ -182,6 +185,20 @@ function isMultiaddress (addr) {
}
}

function isURL (addr) {
if (addr === null || addr === undefined || typeof addr === 'undefined') {
hacdias marked this conversation as resolved.
Show resolved Hide resolved
return false
}

try {
// eslint-disable-next-line
new URL(addr)
return true
} catch (e) {
return false
}
}

function getUserOpts (key) {
let userOpts = null
if (root.localStorage) {
Expand Down Expand Up @@ -214,9 +231,26 @@ function saveUserOpts (key, val) {

function getUserProvidedIpfsApi () {
const ipfsApi = getUserOpts('ipfsApi')
if (ipfsApi && !isMultiaddress(ipfsApi)) {
if (ipfsApi && !isMultiaddress(ipfsApi) && !isURL(ipfsApi)) {
console.warn(`The ipfsApi address ${ipfsApi} is invalid.`)
return null
}
return ipfsApi
}

function parseURL (addr) {
const url = new URL(addr)

const opts = {
host: url.hostname,
port: url.port,
protocol: url.protocol.slice(0, -1),
headers: {}
}

if (url.username) {
opts.headers.authorization = `Basic ${btoa(unescape(encodeURIComponent(url.username + ':' + url.password)))}`
}

return opts
}