Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CLI: Auth0 integration #334

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
12 changes: 4 additions & 8 deletions packages/cli/src/cli/commands/config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import nunjucks from "nunjucks";
import ora from "ora";
import { getApiConfig } from "../../lib/apiConfig";
import {
deleteConfigDetails,
getLocalConfigDetails,
persistConfigDetails,
} from "../../lib/localStorage";
import * as LocalStorage from "../../lib/localStorage";
import { errorHandler } from "../exceptions";

nunjucks.configure({ autoescape: true });
Expand All @@ -17,7 +13,7 @@ export const setTargetEnvironment = errorHandler<"production" | "staging">(
async (resolve, reject) => {
const spinner = ora("Updating config file").start();
try {
await persistConfigDetails({
await LocalStorage.persistConfigDetails({
targetEnvironment: target,
});

Expand All @@ -38,7 +34,7 @@ export const resetTargetEnvironment = errorHandler<void>((): Promise<void> => {
async (resolve, reject) => {
const spinner = ora("Deleting config file").start();
try {
await deleteConfigDetails();
await LocalStorage.deleteConfigDetails();
spinner.succeed(`Successfully deleted config file`);
resolve();
} catch (e) {
Expand All @@ -56,7 +52,7 @@ export const printConfigurationData = errorHandler<void>(
async (resolve, reject) => {
const spinner = ora("Retrieving configuration data").start();
try {
const localConfig = await getLocalConfigDetails();
const localConfig = await LocalStorage.getConfigDetails();
const apiConfig = await getApiConfig();
console.log(JSON.stringify({ localConfig, apiConfig }, null, 4));
spinner.succeed(`Successfully retrieved configuration data`);
Expand Down
13 changes: 8 additions & 5 deletions packages/cli/src/cli/commands/import/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { drive_v3, google } from "googleapis";
import ora from "ora";
import showdown from "showdown";
import AddOnApiHelper from "../../../lib/addonApiHelper";
import { getLocalAuthDetails } from "../../../lib/localStorage";
import { GoogleAuthProvider } from "../../../lib/auth";
import { Logger } from "../../../lib/logger";
import { errorHandler } from "../../exceptions";

Expand Down Expand Up @@ -38,19 +38,22 @@ export const importFromMarkdown = errorHandler<MarkdownImportParams>(
const content = fs.readFileSync(filePath).toString();

// Check user has required permission to create drive file
await AddOnApiHelper.getIdToken([
await AddOnApiHelper.getGoogleTokens([
"https://www.googleapis.com/auth/drive.file",
]);
const authDetails = await getLocalAuthDetails();
if (!authDetails) {
const provider = new GoogleAuthProvider([
"https://www.googleapis.com/auth/drive.file",
]);
const tokens = await provider.getTokens();
if (!tokens) {
logger.error(chalk.red(`ERROR: Failed to retrieve login details.`));
exit(1);
}

// Create Google Doc
const spinner = ora("Creating document on the Google Drive...").start();
const oauth2Client = new OAuth2Client();
oauth2Client.setCredentials(authDetails);
oauth2Client.setCredentials(tokens);
const drive = google.drive({
version: "v3",
auth: oauth2Client,
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/cli/commands/import/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { GaxiosResponse } from "gaxios";
import { OAuth2Client } from "google-auth-library";
import { drive_v3, google } from "googleapis";
import AddOnApiHelper from "../../../lib/addonApiHelper";
import { getLocalAuthDetails } from "../../../lib/localStorage";
import { GoogleAuthProvider } from "../../../lib/auth";
import { Logger } from "../../../lib/logger";

export function preprocessBaseURL(originalBaseURL: string) {
Expand Down Expand Up @@ -33,19 +33,22 @@ export function preprocessBaseURL(originalBaseURL: string) {
}

export async function getAuthedDrive(logger: Logger) {
await AddOnApiHelper.getIdToken([
await AddOnApiHelper.getGoogleTokens([
"https://www.googleapis.com/auth/drive.file",
]);

const authDetails = await getLocalAuthDetails();

if (!authDetails) {
// TODO: Add domain
const provider = new GoogleAuthProvider([
"https://www.googleapis.com/auth/drive.file",
]);
const tokens = await provider.getTokens();
if (!tokens) {
logger.error(chalk.red(`ERROR: Failed to retrieve login details. `));
exit(1);
}

const oauth2Client = new OAuth2Client();
oauth2Client.setCredentials(authDetails);
oauth2Client.setCredentials(tokens);
return google.drive({
version: "v3",
auth: oauth2Client,
Expand Down
113 changes: 14 additions & 99 deletions packages/cli/src/cli/commands/login.ts
Original file line number Diff line number Diff line change
@@ -1,108 +1,23 @@
import { readFileSync } from "fs";
import http from "http";
import { dirname, join } from "path";
import url, { fileURLToPath } from "url";
import { parseJwt } from "@pantheon-systems/pcc-sdk-core";
import { OAuth2Client } from "google-auth-library";
import nunjucks from "nunjucks";
import open from "open";
import ora from "ora";
import destroyer from "server-destroy";
import AddOnApiHelper from "../../lib/addonApiHelper";
import { getApiConfig } from "../../lib/apiConfig";
import {
getLocalAuthDetails,
persistAuthDetails,
} from "../../lib/localStorage";
import { getAuthProvider } from "../../lib/auth";
import { errorHandler } from "../exceptions";

nunjucks.configure({ autoescape: true });

const OAUTH_SCOPES = ["https://www.googleapis.com/auth/userinfo.email"];

function login(extraScopes: string[]): Promise<void> {
return new Promise(
// eslint-disable-next-line no-async-promise-executor -- Handling promise rejection in the executor
async (resolve, reject) => {
const spinner = ora("Logging you in...").start();
try {
const authData = await getLocalAuthDetails(extraScopes);
if (authData) {
const scopes = authData.scope?.split(" ");

if (
!extraScopes?.length ||
extraScopes.find((x) => scopes?.includes(x))
) {
const jwtPayload = parseJwt(authData.id_token as string);
spinner.succeed(
`You are already logged in as ${jwtPayload.email}.`,
);
return resolve();
}
}

const apiConfig = await getApiConfig();
const oAuth2Client = new OAuth2Client({
clientId: apiConfig.googleClientId,
redirectUri: apiConfig.googleRedirectUri,
});

// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: [...OAUTH_SCOPES, ...extraScopes],
});

const server = http.createServer(async (req, res) => {
try {
if (!req.url) {
throw new Error("No URL path provided");
}

if (req.url.indexOf("/oauth-redirect") > -1) {
const qs = new url.URL(req.url, "http://localhost:3030")
.searchParams;
const code = qs.get("code");
const currDir = dirname(fileURLToPath(import.meta.url));
const content = readFileSync(
join(currDir, "../templates/loginSuccess.html"),
);
const credentials = await AddOnApiHelper.getToken(code as string);
const jwtPayload = parseJwt(credentials.id_token as string);
await persistAuthDetails(credentials);

res.end(
nunjucks.renderString(content.toString(), {
email: jwtPayload.email,
}),
);
server.destroy();

spinner.succeed(
`You are successfully logged in as ${jwtPayload.email}`,
);
resolve();
}
} catch (e) {
spinner.fail();
reject(e);
}
});

destroyer(server);

server.listen(3030, () => {
open(authorizeUrl, { wait: true }).then((cp) => cp.kill());
});
} catch (e) {
spinner.fail();
reject(e);
}
},
);
async function login({
authType,
scopes,
}: {
authType: "auth0" | "google";
scopes?: string[];
}): Promise<void> {
const provider = getAuthProvider(authType, scopes);
await provider.login();
}
export default errorHandler<string[]>(login);
export default errorHandler<{
authType: "auth0" | "google";
scopes?: string[];
}>(login);
export const LOGIN_EXAMPLES = [
{ description: "Login the user", command: "$0 login" },
];
3 changes: 2 additions & 1 deletion packages/cli/src/cli/commands/logout.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { existsSync, rmSync } from "fs";
import ora from "ora";
import { AUTH_FILE_PATH } from "../../lib/localStorage";
import { AUTH_FILE_PATH, GOOGLE_AUTH_FILE_PATH } from "../../lib/localStorage";
import { errorHandler } from "../exceptions";

const logout = async () => {
const spinner = ora("Logging you out...").start();
try {
if (existsSync(AUTH_FILE_PATH)) rmSync(AUTH_FILE_PATH);
if (existsSync(GOOGLE_AUTH_FILE_PATH)) rmSync(GOOGLE_AUTH_FILE_PATH);
spinner.succeed("Successfully logged you out from PPC client!");
} catch (e) {
spinner.fail();
Expand Down
38 changes: 25 additions & 13 deletions packages/cli/src/cli/commands/sites/site.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,32 @@ import dayjs from "dayjs";
import ora from "ora";
import AddOnApiHelper from "../../../lib/addonApiHelper";
import { printTable } from "../../../lib/cliDisplay";
import { errorHandler } from "../../exceptions";
import { errorHandler, IncorrectAccount } from "../../exceptions";

export const createSite = errorHandler<string>(async (url: string) => {
const spinner = ora("Creating site...").start();
try {
const siteId = await AddOnApiHelper.createSite(url);
spinner.succeed(
`Successfully created the site with given details. Id: ${siteId}`,
);
} catch (e) {
spinner.fail();
throw e;
}
});
export const createSite = errorHandler<{ url: string; googleAccount: string }>(
async ({ url, googleAccount }) => {
const spinner = ora("Creating site...").start();
if (!googleAccount) {
spinner.fail("You must provide Google workspace account");
return;
}

try {
const siteId = await AddOnApiHelper.createSite(url, googleAccount);
spinner.succeed(
`Successfully created the site with given details. Id: ${siteId}`,
);
} catch (e) {
if (e instanceof IncorrectAccount) {
spinner.fail(
"Selected account doesn't match with account provided in the CLI.",
);
return;
}
throw e;
}
},
);

export const deleteSite = errorHandler<{
id: string;
Expand Down
11 changes: 6 additions & 5 deletions packages/cli/src/cli/commands/whoAmI.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { parseJwt } from "@pantheon-systems/pcc-sdk-core";
import chalk from "chalk";
import { getLocalAuthDetails } from "../../lib/localStorage";
import { Auth0Provider } from "../../lib/auth";
import { errorHandler } from "../exceptions";

const printWhoAmI = async () => {
try {
const authData = await getLocalAuthDetails();
if (!authData) {
const provider = new Auth0Provider();
const tokens = await provider.getTokens();
if (!tokens) {
console.log("You aren't logged in.");
} else {
const jwtPayload = parseJwt(authData.id_token as string);
console.log(`You're logged in as ${jwtPayload.email}`);
const jwtPayload = parseJwt(tokens.access_token as string);
console.log(`You're logged in as ${jwtPayload["pcc/email"]}`);
}
} catch (e) {
chalk.red("Something went wrong - couldn't retrieve auth info.");
Expand Down
7 changes: 7 additions & 0 deletions packages/cli/src/cli/exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ export class UserNotLoggedIn extends Error {
this.name = this.constructor.name;
}
}

export class IncorrectAccount extends Error {
constructor() {
super("Selected account doesn't match with account provided in the CLI.");
this.name = this.constructor.name;
}
}
export class HTTPNotFound extends Error {
constructor() {
super("Not Found");
Expand Down
13 changes: 11 additions & 2 deletions packages/cli/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,17 @@ yargs(hideBin(process.argv))
type: "string",
demandOption: true,
});
yargs.option("googleAccount", {
describe: "Google workspace account email",
type: "string",
demandOption: false,
});
},
async (args) => await createSite(args.url as string),
async (args) =>
await createSite({
url: args.url as string,
googleAccount: args.googleAccount as string,
}),
)
.command(
"delete [options]",
Expand Down Expand Up @@ -887,7 +896,7 @@ yargs(hideBin(process.argv))
() => {
// noop
},
async () => await login([]),
async () => await login({ authType: "auth0" }),
)
.command(
"logout",
Expand Down
Loading
Loading