Skip to content

Commit

Permalink
Merge pull request #19 from dynamicweb/allow-protocols-for-environments
Browse files Browse the repository at this point in the history
Allowing setting protocol when setting up environments, https by default
  • Loading branch information
frederik5480 authored Feb 2, 2023
2 parents da6fbd7 + ef1486f commit fa2ff6a
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 68 deletions.
15 changes: 5 additions & 10 deletions bin/commands/command.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { Agent } from 'https';
import fetch from 'node-fetch';
import path from 'path';
import fs from 'fs';
import { setupEnv } from './env.js';
import { setupEnv, getAgent } from './env.js';
import { setupUser } from './login.js';

const agent = new Agent({
rejectUnauthorized: false
})

const exclude = ['_', '$0', 'command', 'list', 'json']

export function commandCommand() {
Expand Down Expand Up @@ -48,12 +43,12 @@ async function handleCommand(argv) {

async function getProperties(env, user, command) {
return `This option currently doesn't work`
let res = await fetch(`https://${env.host}/Admin/Api/CommandByName?name=${command}`, {
let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/CommandByName?name=${command}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${user.apiKey}`
},
agent: agent
agent: getAgent(env.protocol)
})
if (res.ok) {
let body = await res.json()
Expand All @@ -77,14 +72,14 @@ function parseJsonOrPath(json) {
}

async function runCommand(env, user, command, queryParams, data) {
let res = await fetch(`https://${env.host}/Admin/Api/${command}?` + new URLSearchParams(queryParams), {
let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/${command}?` + new URLSearchParams(queryParams), {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Authorization': `Bearer ${user.apiKey}`,
'Content-Type': 'application/json'
},
agent: agent
agent: getAgent(env.protocol)
})
if (!res.ok) {
console.log(`Error when doing request ${res.url}`)
Expand Down
11 changes: 3 additions & 8 deletions bin/commands/database.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import fetch from 'node-fetch';
import fs from 'fs';
import _path from 'path';
import { Agent } from 'https';
import { setupEnv } from './env.js';
import { setupEnv, getAgent } from './env.js';
import { setupUser } from './login.js';

const agent = new Agent({
rejectUnauthorized: false
})

export function databaseCommand() {
return {
command: 'database [path]',
Expand Down Expand Up @@ -43,13 +38,13 @@ async function handleDatabase(argv) {

async function download(env, user, path, verbose) {
let filename = 'database.bacpac';
fetch(`https://${env.host}/Admin/Api/DatabaseDownload`, {
fetch(`${env.protocol}://${env.host}/Admin/Api/DatabaseDownload`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${user.apiKey}`,
'content-type': 'application/json'
},
agent: agent
agent: getAgent(env.protocol)
}).then(async (res) => {
if (verbose) console.log(res)
const header = res.headers.get('Content-Disposition');
Expand Down
22 changes: 22 additions & 0 deletions bin/commands/env.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { updateConfig, getConfig } from './config.js'
import { Agent as HttpAgent } from 'http';
import { Agent as HttpsAgent } from 'https';
import yargsInteractive from 'yargs-interactive';

const httpAgent = new HttpAgent({
rejectUnauthorized: false
})

const httpsAgent = new HttpsAgent({
rejectUnauthorized: false
})

export function getAgent(protocol) {
return protocol === 'http' ? httpAgent : httpsAgent;
}

export function envCommand() {
return {
command: 'env [env]',
Expand Down Expand Up @@ -29,6 +43,10 @@ export async function setupEnv(argv) {
let env;
if (getConfig().env) {
env = getConfig().env[argv.env] || getConfig().env[getConfig()?.current?.env];
if (!env.protocol) {
console.log('Protocol for environment not set, defaulting to https');
env.protocol = 'https';
}
}
if (!env) {
console.log('Current environment not set, please set it')
Expand Down Expand Up @@ -58,6 +76,9 @@ async function handleEnv(argv) {
environment: {
type: 'input'
},
protocol: {
type: 'input'
},
host: {
type: 'input'
},
Expand All @@ -75,6 +96,7 @@ export async function interactiveEnv(argv, options) {
.then(async (result) => {
getConfig().env = getConfig().env || {};
getConfig().env[result.environment] = getConfig().env[result.environment] || {};
getConfig().env[result.environment].protocol = result.protocol || 'https';
if (result.host)
getConfig().env[result.environment].host = result.host;
if (result.environment) {
Expand Down
19 changes: 7 additions & 12 deletions bin/commands/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,10 @@ import path from 'path';
import fs from 'fs';
import extract from 'extract-zip';
import FormData from 'form-data';
import { Agent } from 'https';
import { setupEnv } from './env.js';
import { setupEnv, getAgent } from './env.js';
import { setupUser } from './login.js';
import { interactiveConfirm } from '../utils.js';

const agent = new Agent({
rejectUnauthorized: false
})

export function filesCommand() {
return {
command: 'files [dirPath] [outPath]',
Expand Down Expand Up @@ -157,14 +152,14 @@ async function download(env, user, dirPath, outPath, recursive, outname, raw, ia
'DirectoryPath': dirPath ?? '',
'ExcludeDirectories': [ excludeDirectories ],
}
fetch(`https://${env.host}/Admin/Api/${endpoint}`, {
fetch(`${env.protocol}://${env.host}/Admin/Api/${endpoint}`, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Authorization': `Bearer ${user.apiKey}`,
'Content-Type': 'application/json'
},
agent: agent
agent: getAgent(env.protocol)
}).then((res) => {
const header = res.headers.get('content-disposition');
const parts = header?.split(';');
Expand Down Expand Up @@ -195,12 +190,12 @@ async function download(env, user, dirPath, outPath, recursive, outname, raw, ia
}

async function getFilesStructure(env, user, dirPath, recursive, includeFiles) {
let res = await fetch(`https://${env.host}/Admin/Api/DirectoryAll?DirectoryPath=${dirPath ?? '/'}&recursive=${recursive ?? 'false'}&includeFiles=${includeFiles ?? 'false'}`, {
let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/DirectoryAll?DirectoryPath=${dirPath ?? '/'}&recursive=${recursive ?? 'false'}&includeFiles=${includeFiles ?? 'false'}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${user.apiKey}`
},
agent: agent
agent: getAgent(env.protocol)
});
if (res.ok) {
return await res.json();
Expand All @@ -214,13 +209,13 @@ export async function uploadFile(env, user, localFilePath, destinationPath) {
let form = new FormData();
form.append('path', destinationPath);
form.append('files', fs.createReadStream(localFilePath));
let res = await fetch(`https://${env.host}/Admin/Api/Upload`, {
let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/Upload`, {
method: 'POST',
body: form,
headers: {
'Authorization': `Bearer ${user.apiKey}`
},
agent: agent
agent: getAgent(env.protocol)
});
if (res.ok) {
if (env.verbose) console.log(await res.json())
Expand Down
11 changes: 3 additions & 8 deletions bin/commands/install.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import fetch from 'node-fetch';
import path from 'path';
import { Agent } from 'https';
import { setupEnv } from './env.js';
import { setupEnv, getAgent } from './env.js';
import { setupUser } from './login.js';
import { uploadFile } from './files.js';

const agent = new Agent({
rejectUnauthorized: false
})

export function installCommand() {
return {
command: 'install [filePath]',
Expand Down Expand Up @@ -40,14 +35,14 @@ async function installAddin(env, user, resolvedPath) {
'AddinProvider': 'Dynamicweb.Marketplace.Providers.LocalAddinProvider',
'Package': path.basename(resolvedPath)
}
let res = await fetch(`https://${env.host}/Admin/Api/AddinInstall`, {
let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/AddinInstall`, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${user.apiKey}`
},
agent: agent
agent: getAgent(env.protocol)
});

if (res.ok) {
Expand Down
40 changes: 20 additions & 20 deletions bin/commands/login.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import fetch from 'node-fetch';
import { interactiveEnv } from './env.js'
import { interactiveEnv, getAgent } from './env.js'
import { updateConfig, getConfig } from './config.js';
import yargsInteractive from 'yargs-interactive';
import { Agent } from 'https';

const agent = new Agent({
rejectUnauthorized: false
})

export function loginCommand() {
return {
Expand Down Expand Up @@ -74,15 +69,19 @@ export async function interactiveLogin(argv, options) {
await yargsInteractive()
.interactive(options)
.then(async (result) => {
if (!getConfig().env || !getConfig().env[result.environment] || !getConfig().env[result.environment].host) {
if (!argv.host)
if (!getConfig().env || !getConfig().env[result.environment] || !getConfig().env[result.environment].host || !getConfig().env[result.environment].protocol) {
if (!argv.host || !argv.protocol)
console.log(`The environment specified is missing parameters, please specify them`)
await interactiveEnv(argv, {
environment: {
type: 'input',
default: result.environment,
prompt: 'never'
},
protocol: {
type: 'input',
prompt: 'if-no-arg'
},
host: {
type: 'input',
prompt: 'if-no-arg'
Expand All @@ -97,8 +96,9 @@ export async function interactiveLogin(argv, options) {
}

async function loginInteractive(result) {
var token = await login(result.username, result.password, result.environment);
var apiKey = await getApiKey(token, result.environment)
var protocol = getConfig().env[result.environment].protocol;
var token = await login(result.username, result.password, result.environment, protocol);
var apiKey = await getApiKey(token, result.environment, protocol)
getConfig().env = getConfig().env || {};
getConfig().env[result.environment].users = getConfig().env[result.environment].users || {};
getConfig().env[result.environment].users[result.username] = getConfig().env[result.environment].users[result.username] || {};
Expand All @@ -108,22 +108,22 @@ async function loginInteractive(result) {
updateConfig();
}

async function login(username, password, env) {
async function login(username, password, env, protocol) {
let data = new URLSearchParams();
data.append('Username', username);
data.append('Password', password);
var res = await fetch(`https://${getConfig().env[env].host}/Admin/Authentication/Login`, {
var res = await fetch(`${protocol}://${getConfig().env[env].host}/Admin/Authentication/Login`, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
agent: agent
agent: getAgent(protocol)
});

if (res.ok) {
let user = parseCookies(res.headers.get('set-cookie')).user;
return await getToken(user, env)
return await getToken(user, env, protocol)
}
else {
console.log(res)
Expand All @@ -146,33 +146,33 @@ function parseCookies (cookieHeader) {
return list;
}

async function getToken(user, env) {
var res = await fetch(`https://${getConfig().env[env].host}/Admin/Authentication/Token`, {
async function getToken(user, env, protocol) {
var res = await fetch(`${getConfig().env[env].protocol}://${getConfig().env[env].host}/Admin/Authentication/Token`, {
method: 'GET',
headers: {
'cookie': `Dynamicweb.Admin=${user}`
},
agent: agent
agent: getAgent(protocol)
});
if (res.ok) {
return (await res.json()).token
}
}

async function getApiKey(token, env) {
async function getApiKey(token, env, protocol) {
let data = {
'Name': 'addin',
'Prefix': 'addin',
'Description': 'Auto-generated ApiKey by DW CLI'
};
var res = await fetch(`https://${getConfig().env[env].host}/Admin/Api/ApiKeySave`, {
var res = await fetch(`${protocol}://${getConfig().env[env].host}/Admin/Api/ApiKeySave`, {
method: 'POST',
body: JSON.stringify( { 'model': data } ),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
agent: agent
agent: getAgent(protocol)
});

if (res.ok) {
Expand Down
15 changes: 5 additions & 10 deletions bin/commands/query.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import { Agent } from 'https';
import fetch from 'node-fetch';
import { setupEnv } from './env.js';
import { setupEnv, getAgent } from './env.js';
import { setupUser } from './login.js';
import yargsInteractive from 'yargs-interactive';

const agent = new Agent({
rejectUnauthorized: false
})

const exclude = ['_', '$0', 'query', 'list', 'i', 'l', 'interactive']

export function queryCommand() {
Expand Down Expand Up @@ -50,12 +45,12 @@ async function getProperties(argv) {
let env = await setupEnv(argv);
let user = await setupUser(argv, env);

let res = await fetch(`https://${env.host}/Admin/Api/QueryByName?name=${argv.query}`, {
let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/QueryByName?name=${argv.query}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${user.apiKey}`
},
agent: agent
agent: getAgent(env.protocol)
})
if (res.ok) {
let body = await res.json()
Expand Down Expand Up @@ -83,12 +78,12 @@ async function getQueryParams(argv) {
}

async function runQuery(env, user, query, params) {
let res = await fetch(`https://${env.host}/Admin/Api/${query}?` + new URLSearchParams(params), {
let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/${query}?` + new URLSearchParams(params), {
method: 'GET',
headers: {
'Authorization': `Bearer ${user.apiKey}`
},
agent: agent
agent: getAgent(env.protocol)
})
if (!res.ok) {
console.log(`Error when doing request ${res.url}`)
Expand Down
1 change: 1 addition & 0 deletions bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ function baseCommand() {
handler: () => {
console.log(`Environment: ${getConfig()?.current?.env}`)
console.log(`User: ${getConfig()?.env[getConfig()?.current?.env]?.current?.user}`)
console.log(`Protocol: ${getConfig()?.env[getConfig()?.current?.env]?.protocol}`)
console.log(`Host: ${getConfig()?.env[getConfig()?.current?.env]?.host}`)
}
}
Expand Down

0 comments on commit fa2ff6a

Please sign in to comment.