From 15cd180a83f370b090b63b663cd6e427dd5666ac Mon Sep 17 00:00:00 2001 From: Rishabh Gupta <38923768+imrishabh18@users.noreply.github.com> Date: Sat, 15 Feb 2025 01:25:22 +0530 Subject: [PATCH] fix: already logged in (#77) * fix: already logged in * format fix and test add --- cli/auth/login/register.ts | 10 +++++++++- lib/cli-config/index.ts | 4 ++++ tests/cli/auth/login.test.ts | 23 +++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 tests/cli/auth/login.test.ts diff --git a/cli/auth/login/register.ts b/cli/auth/login/register.ts index 3911afc..a17a409 100644 --- a/cli/auth/login/register.ts +++ b/cli/auth/login/register.ts @@ -1,5 +1,5 @@ import type { Command } from "commander" -import { setSessionToken } from "lib/cli-config" +import { setSessionToken, getSessionToken } from "lib/cli-config" import delay from "delay" import { getKy } from "lib/registry-api/get-ky" import type { EndpointResponse } from "lib/registry-api/endpoint-types" @@ -7,6 +7,14 @@ import type { EndpointResponse } from "lib/registry-api/endpoint-types" export const registerAuthLogin = (program: Command) => { // Define the login action once to share between both commands const loginAction = async () => { + const sessionToken = getSessionToken() + if (sessionToken) { + console.log( + "Already logged in! Use 'tsci logout' if you need to switch accounts.", + ) + return + } + const ky = getKy() const { login_page } = await ky diff --git a/lib/cli-config/index.ts b/lib/cli-config/index.ts index a9e64db..c438061 100644 --- a/lib/cli-config/index.ts +++ b/lib/cli-config/index.ts @@ -12,6 +12,10 @@ export const cliConfig: TypedConfigstore = new Configstore( "tscircuit", ) +export const getSessionToken = (): string | undefined => { + return cliConfig.get("sessionToken") +} + export const setSessionToken = (token: string) => { cliConfig.set("sessionToken", token) const decoded = jwtDecode<{ diff --git a/tests/cli/auth/login.test.ts b/tests/cli/auth/login.test.ts new file mode 100644 index 0000000..0528547 --- /dev/null +++ b/tests/cli/auth/login.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from "bun:test" +import { setSessionToken } from "lib/cli-config" +import { getCliTestFixture } from "../../fixtures/get-cli-test-fixture" + +// A dummy valid JWT token (header.payload.signature) +const dummyJwtToken = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." + + "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ." + + "SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" + +test("login command: already logged in", async () => { + const { runCommand } = await getCliTestFixture() + + // Simulate an already logged in state by setting a session token. + setSessionToken(dummyJwtToken) + + const { stdout, stderr } = await runCommand("tsci login") + + expect(stderr).toBe("") + expect(stdout).toContain( + "Already logged in! Use 'tsci logout' if you need to switch accounts.", + ) +})