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

refactor: initialize the user auth state synchronously #639

Merged
merged 1 commit into from
Mar 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 9 additions & 0 deletions .changeset/lemon-radios-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"wrangler": patch
---

refactor: initialize the user auth state synchronously

We can now initialize the user state synchronously, which means that
we can remove the checks for whether it has been done or not in each
of the user auth functions.
4 changes: 4 additions & 0 deletions packages/wrangler/src/__tests__/helpers/mock-account-id.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { reinitialiseAuthTokens } from "../../user";

const ORIGINAL_CLOUDFLARE_API_TOKEN = process.env.CLOUDFLARE_API_TOKEN;
const ORIGINAL_CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID;

Expand All @@ -16,6 +18,8 @@ export function mockApiToken({
} else {
process.env.CLOUDFLARE_API_TOKEN = apiToken;
}
// Now we have updated the environment, we must reinitialize the user auth state.
reinitialiseAuthTokens();
});
afterEach(() => {
process.env.CLOUDFLARE_API_TOKEN = ORIGINAL_CLOUDFLARE_API_TOKEN;
Expand Down
27 changes: 0 additions & 27 deletions packages/wrangler/src/__tests__/helpers/mock-user.ts

This file was deleted.

3 changes: 3 additions & 0 deletions packages/wrangler/src/__tests__/helpers/run-in-tmp.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as fs from "node:fs";
import os from "node:os";
import * as path from "node:path";
import { reinitialiseAuthTokens } from "../../user";

const originalCwd = process.cwd();

Expand All @@ -19,6 +20,8 @@ export function runInTempDir({ homedir }: { homedir?: string } = {}) {
// This is because the module gets transpiled so that the "method" `homedir()` gets converted to a
// getter that is not configurable (and so cannot be spied upon).
jest.spyOn(os, "homedir").mockReturnValue(homedir);
// Now that we have changed the home directory location, we must reinitialize the user auth state
reinitialiseAuthTokens();
}
});

Expand Down
23 changes: 14 additions & 9 deletions packages/wrangler/src/__tests__/logout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { existsSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import fetchMock from "jest-fetch-mock";
import { initialise } from "../user";
import {
reinitialiseAuthTokens,
USER_AUTH_CONFIG_FILE,
writeAuthConfigFile,
} from "../user";
import { mockConsoleMethods } from "./helpers/mock-console";
import { writeUserConfig } from "./helpers/mock-user";
import { runInTempDir } from "./helpers/run-in-tmp";
import { runWrangler } from "./helpers/run-wrangler";

Expand All @@ -14,14 +17,15 @@ describe("wrangler", () => {

describe("logout", () => {
it("should exit with a message stating the user is not logged in", async () => {
await initialise();
await runWrangler("logout");
expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
});

it("should logout user that has been properly logged in", async () => {
writeUserConfig("some-oauth-tok", "some-refresh-tok");

writeAuthConfigFile({
oauth_token: "some-oauth-tok",
refresh_token: "some-refresh-tok",
});
// Mock out the response for a request to revoke the auth tokens,
// checking the form of the request is as expected.
fetchMock.mockResponseOnce(async (req) => {
Expand All @@ -30,7 +34,8 @@ describe("wrangler", () => {
return "";
});

await initialise();
// Now that we have changed the auth tokens in the wrangler.toml we must reinitialize the user auth state.
reinitialiseAuthTokens();
await runWrangler("logout");

expect(std.out).toMatchInlineSnapshot(`
Expand All @@ -42,9 +47,9 @@ describe("wrangler", () => {
expect(fetchMock).toHaveBeenCalledTimes(1);

// Make sure that logout removed the config file containing the auth tokens.
expect(
existsSync(path.join(os.homedir(), ".wrangler/config/default.toml"))
).toBe(false);
expect(existsSync(path.join(os.homedir(), USER_AUTH_CONFIG_FILE))).toBe(
false
);
});
});
});
15 changes: 8 additions & 7 deletions packages/wrangler/src/__tests__/whoami.test.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
import { render } from "ink-testing-library";
import React from "react";
import { initialise } from "../user";
import { reinitialiseAuthTokens, writeAuthConfigFile } from "../user";
import { getUserInfo, WhoAmI } from "../whoami";
import { setMockResponse } from "./helpers/mock-cfetch";
import { writeUserConfig } from "./helpers/mock-user";
import { runInTempDir } from "./helpers/run-in-tmp";
import type { UserInfo } from "../whoami";

describe("getUserInfo()", () => {
runInTempDir({ homedir: "./home" });

it("should return undefined if there is no config file", async () => {
await initialise();
const userInfo = await getUserInfo();
expect(userInfo).toBeUndefined();
});

it("should return undefined if there is an empty config file", async () => {
writeUserConfig();
await initialise();
writeAuthConfigFile({});
// Now that we have changed the auth tokens in the wrangler.toml we must reinitialize the user auth state.
reinitialiseAuthTokens();
const userInfo = await getUserInfo();
expect(userInfo).toBeUndefined();
});

it("should return the user's email and accounts if authenticated via config token", async () => {
writeUserConfig("some-oauth-token");
writeAuthConfigFile({ oauth_token: "some-oauth-token" });
// Now that we have changed the auth tokens in the wrangler.toml we must reinitialize the user auth state.
reinitialiseAuthTokens();

setMockResponse("/user", () => {
return { email: "user@example.com" };
});
Expand All @@ -36,7 +38,6 @@ describe("getUserInfo()", () => {
];
});

await initialise();
const userInfo = await getUserInfo();

expect(userInfo).toEqual({
Expand Down
2 changes: 0 additions & 2 deletions packages/wrangler/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import {
login,
logout,
listScopes,
initialise as initialiseUserConfig,
loginOrRefreshIfRequired,
getAccountId,
validateScopeKeys,
Expand Down Expand Up @@ -2340,7 +2339,6 @@ export async function main(argv: string[]): Promise<void> {
wrangler.exitProcess(false);

try {
await initialiseUserConfig();
await wrangler.parse();
} catch (e) {
if (e instanceof CommandLineArgsError) {
Expand Down
Loading