@topgroup/diginext
Version:
A BUILD SERVER & CLI to deploy apps to any Kubernetes clusters.
216 lines (215 loc) • 10.1 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cliAuthenticate = exports.cliLogout = exports.cliLogin = exports.showProfile = void 0;
const chalk_1 = __importDefault(require("chalk"));
const cli_table_1 = __importDefault(require("cli-table"));
const log_1 = require("diginext-utils/dist/xconsole/log");
const inquirer_1 = __importDefault(require("inquirer"));
const lodash_1 = require("lodash");
const open_1 = __importDefault(require("open"));
const app_config_1 = require("../../app.config");
const config_1 = require("../../config/config");
const fetchApi_1 = require("../../modules/api/fetchApi");
const mongodb_1 = require("../../plugins/mongodb");
const showProfile = async (options) => {
var _a;
const { buildServerUrl, currentUser, apiToken } = (0, config_1.getCliConfig)();
if (!buildServerUrl || !currentUser || !((_a = currentUser.token) === null || _a === void 0 ? void 0 : _a.access_token))
return (0, log_1.logError)(`Unauthenticated.`);
const { status, data, messages } = await (0, fetchApi_1.fetchApi)({ url: `/auth/profile`, access_token: currentUser.token.access_token, api_key: apiToken });
if (status === 0 || !data)
return (0, log_1.logError)(`Authentication failed, invalid "access_token": ${messages.join(",")}.`);
const user = data;
const ws = user.activeWorkspace;
const role = user.activeRole;
const table = new cli_table_1.default();
table.push(["Name", user.name]);
table.push(["Username", user.slug]);
table.push(["Email", user.email]);
table.push(["Workspace", `${ws.name} (${ws.slug})`]);
table.push(["Role", `${role.name} (${role.type})`]);
console.log(table.toString());
};
exports.showProfile = showProfile;
const cliLogin = async (options) => {
var _a, _b;
const { secondAction, url, accessToken, apiToken } = options;
const { buildServerUrl: currentServerUrl } = (0, config_1.getCliConfig)();
let access_token = accessToken;
let buildServerUrl = (_b = (_a = url !== null && url !== void 0 ? url : secondAction) !== null && _a !== void 0 ? _a : currentServerUrl) !== null && _b !== void 0 ? _b : app_config_1.Config.DEFAULT_DX_SERVER_URL;
if (!buildServerUrl) {
(0, log_1.logError)(`Please provide your build server URL: "dx login <workspace_url>" or "dx login --help". Eg. https://build.example.com`);
return;
}
if (!buildServerUrl.startsWith("http"))
buildServerUrl = buildServerUrl.indexOf("localhost") > -1 ? `http://${buildServerUrl}` : `https://${buildServerUrl}`;
const tokenDisplayUrl = `${buildServerUrl}/cli`;
const cliConfig = (0, config_1.saveCliConfig)({
buildServerUrl: (0, lodash_1.trimEnd)(buildServerUrl.indexOf(":3000") > -1 ? buildServerUrl.replace(/3000/, "6969") : buildServerUrl, "/"),
});
// remove old "refresh_token"
(0, config_1.saveCliConfig)({
access_token: null,
refresh_token: null,
apiToken: null,
currentUser: null,
});
// open login page of build server:
if (!access_token && !apiToken) {
(0, open_1.default)(tokenDisplayUrl);
const { inputAccessToken } = await inquirer_1.default.prompt([
{
type: "password",
name: "inputAccessToken",
message: "Enter your access token:",
validate: function (value) {
if (value.length) {
return true;
}
else {
return `Access token is required.`;
}
},
},
]);
access_token = inputAccessToken;
}
let currentUser;
// validate the "access_token" -> get "userId":
const { status, data, messages } = await (0, fetchApi_1.fetchApi)({ url: `/auth/profile`, access_token, api_key: apiToken });
if (status === 0) {
(0, log_1.logError)(`Authentication failed, invalid "access_token": ${messages.join(",")}.`);
return;
}
currentUser = data;
if (options.isDebugging)
console.log("currentUser :>> ", currentUser);
// "access_token" is VALID -> save it to local machine!
(0, config_1.saveCliConfig)({
access_token: apiToken ? null : access_token,
refresh_token: apiToken ? null : currentUser.token.refresh_token,
apiToken,
currentWorkspace: currentUser.activeWorkspace,
});
const { workspaces = [], activeWorkspace } = currentUser;
let currentWorkspace;
// If no workspace existed, throw error! (because workspace creation flow is on the admin UI)
if (workspaces.length < 1) {
(0, log_1.logError)(`This account isn't integrated with any workspaces. Select or create one here: ${buildServerUrl}/workspace/select?redirect_url=${buildServerUrl}/cli`);
return;
}
currentWorkspace = activeWorkspace;
if (options.isDebugging)
console.log("currentWorkspace :>> ", currentWorkspace);
if (!currentUser.token)
currentUser.token = {};
currentUser.token.access_token = access_token;
// save this user & workspace to CLI config
(0, config_1.saveCliConfig)({ currentUser, currentWorkspace });
(0, log_1.logSuccess)(`Hello, ${currentUser.name}! You're logged into "${currentWorkspace.name}" workspace.`);
return currentUser;
};
exports.cliLogin = cliLogin;
const cliLogout = async () => {
(0, config_1.saveCliConfig)({
access_token: null,
refresh_token: null,
apiToken: null,
currentUser: null,
currentWorkspace: null,
github_access_token: null,
});
return (0, log_1.logSuccess)(`You're logged out.`);
};
exports.cliLogout = cliLogout;
async function cliAuthenticate(options) {
var _a;
let accessToken, refreshToken, workspace, user;
const { access_token: currentAccessToken = options.apiToken ? null : options.token, refresh_token: currentRefreshToken = options.apiToken ? null : options.refreshToken, apiToken = options.apiToken, buildServerUrl, } = (0, config_1.getCliConfig)();
accessToken = currentAccessToken;
if (options.isDebugging) {
console.log("=====================================");
console.log(" cliAuthenticate() > currentAccessToken :>> ", currentAccessToken);
console.log(" cliAuthenticate() > currentRefreshToken :>> ", currentRefreshToken);
console.log(" cliAuthenticate() > apiToken :>> ", apiToken);
console.log(" cliAuthenticate() > buildServerUrl :>> ", buildServerUrl);
console.log("=====================================");
}
// check old build server url
if (buildServerUrl && !buildServerUrl.includes("app.dxup.dev")) {
(0, log_1.logWarn)(`Your current build server url is: ${buildServerUrl}`);
(0, log_1.logWarn)(`If you want to deploy on DXUP platform, update it to: "https://app.dxup.dev"`);
(0, log_1.logWarn)(`You can do that by running:`, chalk_1.default.cyan(`dx login app.dxup.dev`));
}
const continueToLoginStep = async (url) => {
var _a;
// clear old/expired/cached "access_token" and "refresh_token"
(0, config_1.saveCliConfig)({
access_token: null,
refresh_token: null,
apiToken: null,
currentUser: null,
currentWorkspace: null,
github_access_token: null,
});
// request login API
options.url = url;
const _user = await (0, exports.cliLogin)(options);
if (!_user) {
(0, log_1.logError)(`Failed to login: User not found.`);
return;
}
if ((_a = _user.token) === null || _a === void 0 ? void 0 : _a.access_token)
accessToken = _user.token.access_token;
return _user;
};
if (!accessToken && !apiToken && buildServerUrl) {
user = await continueToLoginStep(buildServerUrl);
if (!user)
return;
}
const profileRes = await (0, fetchApi_1.fetchApi)({
url: `/auth/profile`,
access_token: apiToken ? undefined : accessToken,
api_key: apiToken,
isDebugging: options.isDebugging,
});
const { status, data: userData, messages } = profileRes;
user = userData;
if (options.isDebugging)
console.log("[ACCOUNT] user :>> ", user);
if (!status || (0, lodash_1.isEmpty)(user) || (0, lodash_1.isEmpty)(user === null || user === void 0 ? void 0 : user.activeWorkspace)) {
if (options.isDebugging)
console.log(`[ACCOUNT] profileRes :>>`, profileRes);
if (profileRes.messages.join(".").indexOf("ENETDOWN") > -1) {
(0, log_1.logError)(`Unable to connect: ${buildServerUrl} is down.`);
return;
}
// don't give up, keep trying...
if (buildServerUrl)
user = await continueToLoginStep(buildServerUrl);
}
// Assign user & workspace to use across all CLI commands
options.author = user;
options.userId = mongodb_1.MongoDB.toString(user._id);
options.username = (_a = user.username) !== null && _a !== void 0 ? _a : user.slug;
options.workspace = user.activeWorkspace;
options.workspaceId = mongodb_1.MongoDB.toString(options.workspace._id);
// Save "currentUser", "access_token", "refresh_token" for next API requests
const cliConfig = {
currentUser: user,
currentWorkspace: options.workspace,
access_token: options.apiToken ? null : user.token.access_token,
refresh_token: options.apiToken ? null : user.token.refresh_token,
apiToken: apiToken || options.apiToken,
};
if (options.isDebugging)
console.log("cliAuthenticate() > cliConfig :>> ", cliConfig);
(0, config_1.saveCliConfig)(cliConfig);
return user;
}
exports.cliAuthenticate = cliAuthenticate;
exports.default = { cliLogin: exports.cliLogin, cliLogout: exports.cliLogout, cliAuthenticate };