Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(github): reauthenticate github toast (#3706)

Will Hutchinsond8c07cebd35d
diff --git a/js/app/packages/app/component/GithubReauthenticationPrompt.test.tsx b/js/app/packages/app/component/GithubReauthenticationPrompt.test.tsx
new file mode 100644
index 0000000000..990a6d0434
--- /dev/null
+++ b/js/app/packages/app/component/GithubReauthenticationPrompt.test.tsx
@@ -0,0 +1,156 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { err as resultErr, ok as resultOk } from 'neverthrow';
+import { render } from 'solid-js/web';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ checkGithubLinkStatus: vi.fn(),
+ reauthenticateGithub: vi.fn(),
+ toastCustom: vi.fn(),
+ toastDismiss: vi.fn(),
+ toastFailure: vi.fn(),
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: {
+ custom: mocks.toastCustom,
+ dismiss: mocks.toastDismiss,
+ failure: mocks.toastFailure,
+ },
+}));
+
+vi.mock('@service-auth/client', () => ({
+ authServiceClient: {
+ checkGithubLinkStatus: mocks.checkGithubLinkStatus,
+ reauthenticateGithub: mocks.reauthenticateGithub,
+ },
+}));
+
+import { GithubReauthenticationPrompt } from './GithubReauthenticationPrompt';
+
+type ToastAction = {
+ label: string;
+ onClick: () => Promise<void> | void;
+};
+
+type ToastConfig = {
+ actions: ToastAction[];
+ content?: () => unknown;
+ title: string;
+};
+
+type ToastOptions = {
+ duration?: number;
+ onDismiss?: () => void;
+ persistent?: boolean;
+};
+
+function renderPrompt(): () => void {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const dispose = render(() => <GithubReauthenticationPrompt />, container);
+
+ return () => {
+ dispose();
+ container.remove();
+ };
+}
+
+async function flushPromises(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+function getReconnectAction(): ToastAction {
+ const config = mocks.toastCustom.mock.calls[0]?.[0] as
+ | ToastConfig
+ | undefined;
+ if (!config) throw new Error('Expected GitHub reauthentication toast');
+
+ const action = config.actions.find((item) => item.label === 'Reconnect');
+ if (!action) throw new Error('Expected reconnect toast action');
+
+ return action;
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ window.history.replaceState(null, '', '/tasks');
+
+ mocks.checkGithubLinkStatus.mockReset();
+ mocks.reauthenticateGithub.mockReset();
+ mocks.toastCustom.mockReset();
+ mocks.toastDismiss.mockReset();
+ mocks.toastFailure.mockReset();
+
+ mocks.toastCustom.mockReturnValue(101);
+});
+
+afterEach(() => {
+ vi.runOnlyPendingTimers();
+ vi.useRealTimers();
+});
+
+describe('GithubReauthenticationPrompt', () => {
+ it('shows a reconnect toast globally when GitHub reauthentication is required', async () => {
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultErr([
+ {
+ code: 'REAUTHENTICATION_REQUIRED',
+ message: 'ReauthenticationRequired',
+ },
+ ])
+ );
+ const originalUrl = window.location.href;
+ const authorizationUrl = `${originalUrl}#github-reauth`;
+ mocks.reauthenticateGithub.mockResolvedValue(resultOk(authorizationUrl));
+
+ const cleanup = renderPrompt();
+ await flushPromises();
+ await getReconnectAction().onClick();
+
+ const options = mocks.toastCustom.mock.calls[0]?.[1] as ToastOptions;
+
+ expect(mocks.checkGithubLinkStatus).toHaveBeenCalledTimes(1);
+ expect(mocks.toastCustom).toHaveBeenCalledTimes(1);
+ expect(options.persistent).toBe(true);
+ expect(options.duration).toBeUndefined();
+ expect(options.onDismiss).toEqual(expect.any(Function));
+ expect(mocks.toastDismiss).toHaveBeenCalledWith(101);
+ expect(mocks.reauthenticateGithub).toHaveBeenCalledWith(originalUrl);
+ expect(window.location.href).toBe(authorizationUrl);
+
+ cleanup();
+ });
+
+ it('does not show a reconnect toast for valid GitHub links', async () => {
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultOk({ reauthentication_required: false })
+ );
+
+ const cleanup = renderPrompt();
+ await flushPromises();
+
+ expect(mocks.checkGithubLinkStatus).toHaveBeenCalledTimes(1);
+ expect(mocks.toastCustom).not.toHaveBeenCalled();
+
+ cleanup();
+ });
+
+ it('does not show a reconnect toast when no GitHub link exists', async () => {
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultErr([{ code: 'NOT_FOUND', message: 'No GitHub link found' }])
+ );
+
+ const cleanup = renderPrompt();
+ await flushPromises();
+
+ expect(mocks.checkGithubLinkStatus).toHaveBeenCalledTimes(1);
+ expect(mocks.toastCustom).not.toHaveBeenCalled();
+
+ cleanup();
+ });
+});
diff --git a/js/app/packages/app/component/GithubReauthenticationPrompt.tsx b/js/app/packages/app/component/GithubReauthenticationPrompt.tsx
new file mode 100644
index 0000000000..9e447653c1
--- /dev/null
+++ b/js/app/packages/app/component/GithubReauthenticationPrompt.tsx
@@ -0,0 +1,72 @@
+import { toast } from '@core/component/Toast/Toast';
+import { authServiceClient } from '@service-auth/client';
+import { onMount } from 'solid-js';
+
+let githubReauthenticationToastId: number | undefined;
+
+function clearGithubReauthenticationToastState(): void {
+ githubReauthenticationToastId = undefined;
+}
+
+async function handleGithubReauthenticationToastAction(): Promise<void> {
+ if (githubReauthenticationToastId !== undefined) {
+ toast.dismiss(githubReauthenticationToastId);
+ }
+ clearGithubReauthenticationToastState();
+
+ const result = await authServiceClient.reauthenticateGithub(
+ window.location.href
+ );
+
+ if (result.isErr()) {
+ toast.failure('Failed to start GitHub reconnect flow');
+ return;
+ }
+
+ window.location.href = result.value;
+}
+
+function showGithubReauthenticationToast(): void {
+ if (githubReauthenticationToastId !== undefined) return;
+
+ githubReauthenticationToastId = toast.custom(
+ {
+ title: 'Reconnect GitHub',
+ content(): string {
+ return 'Your GitHub authorization has expired. Reconnect GitHub to restore pull request details.';
+ },
+ actions: [
+ {
+ label: 'Reconnect',
+ onClick: handleGithubReauthenticationToastAction,
+ },
+ ],
+ },
+ {
+ persistent: true,
+ onDismiss: clearGithubReauthenticationToastState,
+ }
+ );
+}
+
+async function checkGithubReauthenticationStatus(): Promise<void> {
+ const response = await authServiceClient.checkGithubLinkStatus();
+
+ const needsReauthentication = response.isOk()
+ ? response.value.reauthentication_required
+ : response.error.some(
+ (error) => error.code === 'REAUTHENTICATION_REQUIRED'
+ );
+
+ if (needsReauthentication) {
+ showGithubReauthenticationToast();
+ }
+}
+
+export function GithubReauthenticationPrompt() {
+ onMount(() => {
+ void checkGithubReauthenticationStatus();
+ });
+
+ return null;
+}
diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsx
index 8d158a0f0b..401fb38455 100644
--- a/js/app/packages/app/component/Layout.tsx
+++ b/js/app/packages/app/component/Layout.tsx
@@ -32,6 +32,7 @@ import Banner from './banner/Banner';
import { GlobalBulkEditEntityModal } from './bulk-edit-entity/BulkEditEntityModal';
import { CommandMenu } from './command';
import { DevStatusBar } from './DevStatusBar';
+import { GithubReauthenticationPrompt } from './GithubReauthenticationPrompt';
import GlobalShortcuts from './GlobalHotkeys';
import { GlobalShareModal } from './global-share-modal/GlobalShareModal';
import { ItemDndProvider } from './ItemDragAndDrop';
@@ -136,6 +137,9 @@ function LayoutInner(props: RouteSectionProps) {
<BundleUpdateProgressBar />
<Suspense>
<Show when={isAuthenticated()}>
+ <Show when={!AUTH_URLS.includes(location.pathname)}>
+ <GithubReauthenticationPrompt />
+ </Show>
<GlobalShortcuts />
<Show when={!isMobile()}>
<Suspense>
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsx
index bfd1770c60..8dd4b72466 100644
--- a/js/app/packages/app/component/settings/Account.tsx
+++ b/js/app/packages/app/component/settings/Account.tsx
@@ -73,6 +73,8 @@ false && fileSelector;
// 16 megabytes
const MAX_PROFILE_PICTURE_SIZE = 16 * 1000 * 1000;
+type GithubLinkStatus = 'linked' | 'unlinked' | 'reauthentication_required';
+
async function uploadProfilePicture(
file: File
): Promise<{ id: string; url: string } | void> {
@@ -230,10 +232,21 @@ export function Account() {
);
};
- const [githubLinkExists, { refetch: refetchGithubLink }] = createResource(async () => {
- const response = await authServiceClient.checkLinkExists({ idp_name: 'github' });
- return response.isOk() ? response.value.link_exists : false;
- });
+ const [githubLinkStatus, { refetch: refetchGithubLinkStatus }] =
+ createResource(async (): Promise<GithubLinkStatus> => {
+ const response = await authServiceClient.checkGithubLinkStatus();
+
+ if (response.isOk()) {
+ return response.value.reauthentication_required
+ ? 'reauthentication_required'
+ : 'linked';
+ }
+
+ const needsReauthentication = response.error.some(
+ (error) => error.code === 'REAUTHENTICATION_REQUIRED'
+ );
+ return needsReauthentication ? 'reauthentication_required' : 'unlinked';
+ });
const handleGithubEnable = async () => {
const url = await authServiceClient.initGithubLink(window.location.href);
@@ -244,7 +257,18 @@ export function Account() {
const handleGithubDisable = async () => {
await authServiceClient.deleteGithubLink();
- refetchGithubLink();
+ refetchGithubLinkStatus();
+ };
+
+ const handleGithubReconnect = async () => {
+ const url = await authServiceClient.reauthenticateGithub(
+ window.location.href
+ );
+ if (url.isOk()) {
+ window.location.href = url.value;
+ } else {
+ toast.failure('Failed to start GitHub reconnect flow');
+ }
};
const firstName = () => {
@@ -530,33 +554,46 @@ export function Account() {
<Row label="GitHub">
<Show
- when={!githubLinkExists.loading}
+ when={!githubLinkStatus.loading}
fallback={
<span class="text-sm text-ink-muted">Loading…</span>
}
>
- <Show
- when={!githubLinkExists()}
+ <Switch
fallback={
<Button
variant="base"
size="sm"
depth={3}
- onClick={handleGithubDisable}
+ onClick={handleGithubEnable}
>
- Disable
+ Enable
</Button>
}
>
- <Button
- variant="base"
- size="sm"
- depth={3}
- onClick={handleGithubEnable}
+ <Match
+ when={githubLinkStatus() === 'reauthentication_required'}
>
- Enable
- </Button>
- </Show>
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ onClick={handleGithubReconnect}
+ >
+ Reconnect
+ </Button>
+ </Match>
+ <Match when={githubLinkStatus() === 'linked'}>
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ onClick={handleGithubDisable}
+ >
+ Disable
+ </Button>
+ </Match>
+ </Switch>
</Show>
</Row>
diff --git a/js/app/packages/core/component/Toast/Toast.tsx b/js/app/packages/core/component/Toast/Toast.tsx
index 416f960045..d57df2339d 100644
--- a/js/app/packages/core/component/Toast/Toast.tsx
+++ b/js/app/packages/core/component/Toast/Toast.tsx
@@ -679,6 +679,7 @@ function custom(
duration?: number;
region?: string;
mobile?: boolean;
+ onDismiss?: () => void;
}
): number {
const useMobile = options?.mobile && isMobile();
@@ -692,6 +693,7 @@ function custom(
persistent={options?.persistent}
duration={options?.duration}
mobile={useMobile}
+ onDismiss={options?.onDismiss}
/>
),
{ region }
diff --git a/js/app/packages/core/util/fetchWithToken.ts b/js/app/packages/core/util/fetchWithToken.ts
index 61bbfac8a9..de92596c5c 100644
--- a/js/app/packages/core/util/fetchWithToken.ts
+++ b/js/app/packages/core/util/fetchWithToken.ts
@@ -6,20 +6,47 @@ import { err, ok, type Result } from 'neverthrow';
import type { ObjectLike, ResultError } from './result';
import {
type BaseFetchErrorCode,
+ type ErrorResponseHandler,
type SafeFetchInit,
safeFetch,
} from './safeFetch';
export type FetchWithTokenErrorCode = BaseFetchErrorCode;
-function fetchWithCredentials<T extends ObjectLike>(
+export type FetchWithTokenInit<CustomErrorCode extends string = never> =
+ SafeFetchInit & {
+ errorResponseHandler?: ErrorResponseHandler<CustomErrorCode>;
+ };
+
+function fetchWithCredentials<
+ T extends ObjectLike,
+ CustomErrorCode extends string = never,
+>(
input: RequestInfo,
- init?: SafeFetchInit
-): Promise<Result<T, ResultError<BaseFetchErrorCode>[]>> {
- return safeFetch<T>(input, {
- ...init,
- credentials: 'include',
- });
+ init?: FetchWithTokenInit<CustomErrorCode>
+): Promise<Result<T, ResultError<BaseFetchErrorCode | CustomErrorCode>[]>> {
+ const { errorResponseHandler, ...fetchInit } = init ?? {};
+ let safeFetchErrorHandler: ErrorResponseHandler<CustomErrorCode> | undefined;
+ if (errorResponseHandler) {
+ safeFetchErrorHandler = async function handleFetchWithCredentialsError(
+ response
+ ) {
+ if (response.status === 401) {
+ return { code: 'UNAUTHORIZED', message: 'Unauthorized access' };
+ }
+
+ return errorResponseHandler(response);
+ };
+ }
+
+ return safeFetch<T, CustomErrorCode>(
+ input,
+ {
+ ...fetchInit,
+ credentials: 'include',
+ },
+ safeFetchErrorHandler
+ );
}
let tokenPromise: Promise<
@@ -61,9 +88,10 @@ export async function fetchToken(): Promise<
* Performs a fetch request with automatic token refresh on unauthorized errors.
*
* @template T - The expected response data type.
+ * @template CustomErrorCode - Additional error codes from a custom error response handler.
* @param {RequestInfo} input - The resource that you wish to fetch.
- * @param {SafeFetchInit} [init] - An options object containing any custom settings you want to apply to the request, including retry configuration.
- * @returns {Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>} A promise that resolves to a Result containing either the response data or an error.
+ * @param {FetchWithTokenInit<CustomErrorCode>} [init] - An options object containing any custom settings you want to apply to the request, including retry configuration and custom error response handling.
+ * @returns {Promise<Result<T, ResultError<BaseFetchErrorCode | CustomErrorCode>[]>>} A promise that resolves to a Result containing either the response data or an error.
*
* @example
* const result = await fetchWithToken<UserData>(
@@ -80,12 +108,15 @@ export async function fetchToken(): Promise<
* console.log('User data:', result.value);
* }
*/
-export async function fetchWithToken<T extends ObjectLike>(
+export async function fetchWithToken<
+ T extends ObjectLike,
+ CustomErrorCode extends string = never,
+>(
input: RequestInfo,
- init?: SafeFetchInit
-): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>> {
+ init?: FetchWithTokenInit<CustomErrorCode>
+): Promise<Result<T, ResultError<BaseFetchErrorCode | CustomErrorCode>[]>> {
if (ENABLE_BEARER_TOKEN_AUTH) {
- const result = await fetchWithAuth<T>(input, init);
+ const result = await fetchWithAuth<T, CustomErrorCode>(input, init);
if (result.isErr()) {
logger.error('fetchWithToken: fetchWithAuth failed', {
input,
@@ -97,7 +128,7 @@ export async function fetchWithToken<T extends ObjectLike>(
return result;
}
- let result = await fetchWithCredentials<T>(input, init);
+ let result = await fetchWithCredentials<T, CustomErrorCode>(input, init);
if (
result.isErr() &&
@@ -116,7 +147,7 @@ export async function fetchWithToken<T extends ObjectLike>(
}
// Retry the original request
- result = await fetchWithCredentials<T>(input, init);
+ result = await fetchWithCredentials<T, CustomErrorCode>(input, init);
}
return result;
diff --git a/js/app/packages/queries/storage/github-pull-requests.test.ts b/js/app/packages/queries/storage/github-pull-requests.test.ts
new file mode 100644
index 0000000000..818fd50340
--- /dev/null
+++ b/js/app/packages/queries/storage/github-pull-requests.test.ts
@@ -0,0 +1,97 @@
+import { err as resultErr, ok as resultOk } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ enrichGithubPullRequests: vi.fn(),
+ getDocumentGithubPullRequests: vi.fn(),
+}));
+
+vi.mock('@service-auth/client', () => ({
+ authServiceClient: {
+ enrichGithubPullRequests: mocks.enrichGithubPullRequests,
+ },
+}));
+
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: {
+ getDocumentGithubPullRequests: mocks.getDocumentGithubPullRequests,
+ },
+}));
+
+import type { ResultError } from '@core/util/result';
+import type { EnrichedGithubPullRequest } from '@service-auth/generated/schemas';
+import type { GithubPullRequest } from '@service-storage/generated/schemas';
+import { fetchDocumentGithubPullRequests } from './github-pull-requests';
+
+const rawPullRequest: GithubPullRequest = {
+ displayName: 'macro/macro#42',
+ githubKey: 'macro/macro/pull/42',
+ number: 42,
+ owner: 'macro',
+ repo: 'macro',
+ url: 'https://github.com/macro/macro/pull/42',
+};
+
+const rawResponse = { pullRequests: [rawPullRequest] };
+
+function createError(code: string): ResultError<string> {
+ return { code, message: code };
+}
+
+beforeEach(() => {
+ mocks.enrichGithubPullRequests.mockReset();
+ mocks.getDocumentGithubPullRequests.mockReset();
+
+ mocks.getDocumentGithubPullRequests.mockResolvedValue(resultOk(rawResponse));
+});
+
+describe('fetchDocumentGithubPullRequests', () => {
+ it('keeps the raw PR fallback for GitHub reauthentication enrichment errors', async () => {
+ mocks.enrichGithubPullRequests.mockResolvedValue(
+ resultErr([createError('REAUTHENTICATION_REQUIRED')])
+ );
+
+ const response = await fetchDocumentGithubPullRequests('document-1');
+
+ expect(response).toEqual(rawResponse);
+ expect(mocks.enrichGithubPullRequests).toHaveBeenCalledWith({
+ pullRequests: [
+ {
+ displayName: rawPullRequest.displayName,
+ githubKey: rawPullRequest.githubKey,
+ number: rawPullRequest.number,
+ owner: rawPullRequest.owner,
+ repo: rawPullRequest.repo,
+ url: rawPullRequest.url,
+ },
+ ],
+ });
+ });
+
+ it('keeps the raw PR fallback for unrelated enrichment errors', async () => {
+ mocks.enrichGithubPullRequests.mockResolvedValue(
+ resultErr([createError('SERVER_ERROR')])
+ );
+
+ const response = await fetchDocumentGithubPullRequests('document-1');
+
+ expect(response).toEqual(rawResponse);
+ });
+
+ it('returns enriched PRs when enrichment succeeds', async () => {
+ const enrichedPullRequest: EnrichedGithubPullRequest = {
+ ...rawPullRequest,
+ additions: 10,
+ deletions: 2,
+ name: 'Improve GitHub auth',
+ status: 'open',
+ };
+ mocks.enrichGithubPullRequests.mockResolvedValue(
+ resultOk({ pullRequests: [enrichedPullRequest] })
+ );
+
+ const response = await fetchDocumentGithubPullRequests('document-1');
+
+ expect(response).toEqual({ pullRequests: [enrichedPullRequest] });
+ });
+});
diff --git a/js/app/packages/queries/storage/github-pull-requests.ts b/js/app/packages/queries/storage/github-pull-requests.ts
index d98b8baa8c..547b9f2afb 100644
--- a/js/app/packages/queries/storage/github-pull-requests.ts
+++ b/js/app/packages/queries/storage/github-pull-requests.ts
@@ -14,7 +14,6 @@ import type { Accessor } from 'solid-js';
import { documentGithubPullRequestsKeys } from './keys';
const DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME = 60 * 1000;
-
type DocumentIdInput =
| string
| null
@@ -65,7 +64,7 @@ function toStorageGithubPullRequest(
};
}
-async function fetchDocumentGithubPullRequests(
+export async function fetchDocumentGithubPullRequests(
documentId: string
): Promise<GithubPullRequestsResponse> {
const rawResponse = await throwOnErr(() =>
diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.ts
index 34710906ab..7ed082d330 100644
--- a/js/app/packages/service-clients/service-auth/client.ts
+++ b/js/app/packages/service-clients/service-auth/client.ts
@@ -3,15 +3,20 @@ import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import { registerClient } from '@core/util/mockClient';
import type { ObjectLike } from '@core/util/result';
-import { type SafeFetchInit, safeFetch } from '@core/util/safeFetch';
+import {
+ type ErrorResponseHandler,
+ type SafeFetchInit,
+ safeFetch,
+} from '@core/util/safeFetch';
import { logger } from '@observability';
import { makePersisted } from '@solid-primitives/storage';
-import { ok } from 'neverthrow';
+import { err, ok } from 'neverthrow';
import { createSignal } from 'solid-js';
import { fetchWithAuth as _fetchWithAuth } from './fetch';
import type {
EnrichGithubPullRequestsProxyRequest,
EnrichGithubPullRequestsResponse,
+ GithubLinkStatusResponse,
InitGithubLinkResponse,
InitGmailLinkResponse,
PatchSubscriptionTierRequest,
@@ -137,6 +142,36 @@ export type PatchSubscriptionTierErrorCode =
| 'NO_SUBSCRIPTION'
| 'UPDATE_IN_PROGRESS';
+export type GithubReauthenticationErrorCode = 'REAUTHENTICATION_REQUIRED';
+
+const githubErrorResponseHandler: ErrorResponseHandler<GithubReauthenticationErrorCode> =
+ async function handleGithubErrorResponse(response) {
+ switch (response.status) {
+ case 428:
+ return {
+ code: 'REAUTHENTICATION_REQUIRED',
+ message: 'GitHub reauthentication required',
+ };
+ case 401:
+ return { code: 'UNAUTHORIZED', message: 'Unauthorized access' };
+ case 403:
+ return { code: 'FORBIDDEN', message: 'Forbidden' };
+ case 404:
+ return { code: 'NOT_FOUND', message: 'Resource not found' };
+ case 409:
+ return { code: 'CONFLICT', message: 'Resource conflict' };
+ case 410:
+ return { code: 'GONE', message: 'Resource deleted' };
+ case 500:
+ return { code: 'SERVER_ERROR', message: 'Internal server error' };
+ default:
+ return {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ };
+ }
+ };
+
export const authServiceClient = {
async logout() {
setAccessTokenData(null);
@@ -323,13 +358,14 @@ export const authServiceClient = {
async enrichGithubPullRequests(args: EnrichGithubPullRequestsProxyRequest) {
return (
- await fetchWithAuth<EnrichGithubPullRequestsResponse>(
- `${authHost}/github_pull_requests/enrich`,
- {
- method: 'POST',
- body: JSON.stringify(args),
- }
- )
+ await fetchWithAuth<
+ EnrichGithubPullRequestsResponse,
+ GithubReauthenticationErrorCode
+ >(`${authHost}/github_pull_requests/enrich`, {
+ method: 'POST',
+ body: JSON.stringify(args),
+ errorResponseHandler: githubErrorResponseHandler,
+ })
).map((result) => result);
},
async patchUserTutorial(args: PatchUserTutorialRequest) {
@@ -545,6 +581,18 @@ export const authServiceClient = {
);
},
+ async checkGithubLinkStatus() {
+ return (
+ await fetchWithAuth<
+ GithubLinkStatusResponse,
+ GithubReauthenticationErrorCode
+ >(`${authHost}/link/github/status`, {
+ method: 'GET',
+ errorResponseHandler: githubErrorResponseHandler,
+ })
+ ).map((result) => result);
+ },
+
/**
* Initializes the github account link for the user.
* Returns the url you need to redirect user to to start the link.
@@ -589,6 +637,15 @@ export const authServiceClient = {
).map((_result) => {});
},
+ async reauthenticateGithub(originalUrl?: string) {
+ const deleteResult = await authServiceClient.deleteGithubLink();
+ if (deleteResult.isErr()) {
+ return err(deleteResult.error);
+ }
+
+ return authServiceClient.initGithubLink(originalUrl);
+ },
+
async sendMobileWelcomeEmail(email: string) {
return safeFetch<
SendMobileWelcomeEmailResponse,