Skip to content

Commit

Permalink
Ability to enter custom server URL for CLI during login (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
uditdc authored Jun 20, 2023
1 parent a237ba1 commit 18885e7
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 61 deletions.
50 changes: 27 additions & 23 deletions src/commands/login/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import Chalk from "chalk"
import Fastify from "fastify";
import { getDb } from "../../store/db";
import { getConsoleServer } from "../../lib/urls";
import { openInBrowser } from '../../lib/browser';
import { openInBrowser } from "../../lib/browser";
import { getGatewayUrl } from "../../lib/urls"

const portastic = require("portastic");

const consoleServer = getConsoleServer();
const clientId = "7ddcb826-e84a-4102-b95b-d9b8d3a57176";

const fastify = Fastify({
Expand All @@ -25,7 +24,7 @@ fastify.get("/token/:userId", async (request: any, reply: any) => {
console.log("Error when attempting to login");
return;
}
console.log(`User returned from ${consoleServer} authenticated`);

reply.redirect("/complete");
});

Expand Down Expand Up @@ -87,33 +86,31 @@ fastify.get("/complete", async (request: any, reply: any) => {
</body>
</html>`;
reply.header("Content-Type", "text/html").send(html);
setTimeout(() => process.exit(0), 2000);

console.log('')
console.log(Chalk.green('Authentication Completed!'));
console.log('You have successfully authenticated with the server.')
console.log('')
fastify.close()
});

// run the server
const start = async () => {
const start = async (url: string) => {
try {
const ports = await portastic.find({ min: 8000, max: 8999 });
const port = ports[Math.floor(Math.random() * ports.length)];
const serverPort = ports[Math.floor(Math.random() * ports.length)];

// request a jwt from the console ui
fastify.get("/", async (request, reply) => {
console.log(`Sending user to ${consoleServer} to authenticate`);

// the web dev server will be under port 3000, and api under port 3005
const webServer =
process.env.NODE_ENV === "development"
? getConsoleServer(3000)
: consoleServer

reply.redirect(
`${webServer}/login?redirect=http://0.0.0.0:${port}/token&clientId=${clientId}`
`${url}/login?redirect=http://0.0.0.0:${serverPort}/token&clientId=${clientId}`
);
});

fastify.listen({ port }).then(async () => {
console.log(`Open Browser at http://0.0.0.0:${port} to complete login`)
openInBrowser(`http://0.0.0.0:${port}`)
fastify.listen({ port: serverPort }).then(async () => {
console.log(
`Open Browser at http://0.0.0.0:${serverPort} to complete login`
);
openInBrowser(`http://0.0.0.0:${serverPort}`);
});
} catch (err) {
fastify.log.error(err);
Expand All @@ -123,11 +120,18 @@ const start = async () => {

// run the command when cli is called
export function run(options?: any) {
if (options?.authUrl) {
getDb().set("config.authUrl", options?.authUrl.replace(/^https?:\/\//, '')).write();
}
if (options?.authPort) {
getDb().set("config.authPort", parseInt(options?.authPort)).write();
}

if (options?.authToken) {
// todo verify token is actually good before setting it
const token = options?.authToken;
getDb().set("config.token", token).write();
} else {
start();
const gatewayUrl = getGatewayUrl()
start(gatewayUrl);
}
}
2 changes: 2 additions & 0 deletions src/commands/wallet/remove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ export const removeWallet = () => {
console.log("disconnecting wallet");
const db = getDb();
db.set("config.token", null).write();
db.set("config.authUrl", null).write();
db.set("config.authPort", null).write();
console.log("user logged out");
};
16 changes: 13 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { run as runLogin } from './commands/login'
import { run as runSelfUpdate } from './commands/self-update'

import { openInBrowser } from './lib/browser'
import { getConsoleServer } from './lib/urls'
import { getGatewayUrl } from './lib/urls'
import { logger } from './lib/logger'
import { sitesCli } from './commands/sites'

Expand Down Expand Up @@ -69,11 +69,21 @@ function createCLI(argv: string[]) {
'Logs into your blockless account',
(yargs) => {
return yargs
.option('auth-url', {
alias: 'u',
description: 'Include an authentication host with your login command',
default: 'dashboard.blockless.network'
})
.option('auth-port', {
alias: 'p',
description: 'Include an authentication port with your login command',
default: 443
})
.option('auth-token', {
alias: 't',
description: 'Include an authentication token with your login command',
})
.group(['auth-token'], 'Options:')
.group(['auth-url', 'auth-port', 'auth-token'], 'Options:')
},
(argv) => {
runLogin(argv)
Expand Down Expand Up @@ -103,7 +113,7 @@ function createCLI(argv: string[]) {
'Opens the Console in the browser',
() => { },
async () => {
await openInBrowser(getConsoleServer())
await openInBrowser(getGatewayUrl())
}
)

Expand Down
9 changes: 4 additions & 5 deletions src/lib/http.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import axios from "axios"
import Chalk from 'chalk'
import { getToken } from "../store/db"
import { getConsoleServer } from "./urls"

const consoleServer = getConsoleServer()
import { getGatewayUrl } from "./urls"

export const consoleClient = axios.create({
baseURL: consoleServer,
headers: {
'Content-Type': 'application/json'
}
Expand All @@ -18,6 +14,9 @@ export const consoleClient = axios.create({
*/
consoleClient.interceptors.request.use(async (config) => {
const token = getToken()
const gatewayUrl = getGatewayUrl()

config.baseURL = gatewayUrl

if (token) {
config.headers = {
Expand Down
9 changes: 9 additions & 0 deletions src/lib/urls.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { getAuthUrl } from "../store/db"

// Console API Server
export const getConsoleServer = (
port?: number
Expand All @@ -7,6 +9,13 @@ export const getConsoleServer = (
return `${host}:${port ? port : devMode ? 3005 : 443}`;
};

export const getGatewayUrl = (): string => {
const authUrl = getAuthUrl()
const protocol = authUrl.port === 443 ? 'https' : 'http'

return authUrl ? `${protocol}://${authUrl.url}:${authUrl.port}` : getConsoleServer()
}

// WASI Repo Server
export const getWASMRepoServer = (
port?: number
Expand Down
73 changes: 43 additions & 30 deletions src/store/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,45 @@ import { store } from "./index";
import { existsSync, writeFileSync } from "fs";
import { execSync } from "child_process";

export const getDb = () => {
const lowdb = require("lowdb")
const FileSync = require("lowdb/adapters/FileSync")
const lowdbEncryption = require("lowdb-encryption")

const cliConfigFileName = "bls.cli.config.json"
const cliConfigFilePath = `${store.system.homedir}${store.system.appPath}`
const cliConfigFile = `${cliConfigFilePath}/${cliConfigFileName}`
let db: any = null

if (!existsSync(cliConfigFile)) {
if (!existsSync(cliConfigFilePath)) {
execSync(`mkdir -p ${cliConfigFilePath}`)
export const getDb = () => {
if (!db) {
const lowdb = require("lowdb")
const FileSync = require("lowdb/adapters/FileSync")
const lowdbEncryption = require("lowdb-encryption")

const cliConfigFileName = "bls.cli.config.json"
const cliConfigFilePath = `${store.system.homedir}${store.system.appPath}`
const cliConfigFile = `${cliConfigFilePath}/${cliConfigFileName}`

if (!existsSync(cliConfigFile)) {
if (!existsSync(cliConfigFilePath)) {
execSync(`mkdir -p ${cliConfigFilePath}`)
}
writeFileSync(cliConfigFile, JSON.stringify({}))
}
writeFileSync(cliConfigFile, JSON.stringify({}))
}

const defaultValue = {
config: {
token: "",
},
}

const adapter = new FileSync(
`${store.system.homedir}${store.system.appPath}/bls.cli.config.json`,
{
defaultValue,
...lowdbEncryption({
secret: "s3cr3t",
iterations: 100_000,
}),

const defaultValue = {
config: {
token: "",
},
}
)

const adapter = new FileSync(
`${store.system.homedir}${store.system.appPath}/bls.cli.config.json`,
{
defaultValue,
...lowdbEncryption({
secret: "s3cr3t",
iterations: 100_000,
}),
}
)

db = lowdb(adapter);
}

const db = lowdb(adapter);
return db.read()
};

Expand All @@ -49,3 +54,11 @@ export const getToken = () => {

return token;
};

export const getAuthUrl = (): { url: string, port: number } => {
const db = getDb();
const config = db.get("config").value();
const { authUrl, authPort } = config

return { url: authUrl, port: authPort }
}

0 comments on commit 18885e7

Please sign in to comment.