Skip to content
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
8 changes: 5 additions & 3 deletions apps/web/app/(app)/[emailAccountId]/PermissionsCheck.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ export function PermissionsCheck() {
permissionsChecked[emailAccountId] = true;

checkPermissionsAction(emailAccountId).then((result) => {
if (result?.data?.hasAllPermissions === false)
router.replace(prefixPath(emailAccountId, "/permissions/error"));
if (result?.data?.hasRefreshToken === false)
if (
result?.data?.hasAllPermissions === false ||
result?.data?.hasRefreshToken === false
) {
router.replace(prefixPath(emailAccountId, "/permissions/consent"));
}
});
}, [router, emailAccountId, isAccountOwner]);

Expand Down
34 changes: 30 additions & 4 deletions apps/web/app/(app)/[emailAccountId]/permissions/consent/page.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,39 @@
"use client";

import { useState } from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { logOut } from "@/utils/user";
import { PageHeading, TypographyP } from "@/components/Typography";
import { useAccount } from "@/providers/EmailAccountProvider";
import { toastError } from "@/components/Toast";
import { getAccountLinkingUrl } from "@/utils/account-linking";

export default function PermissionsConsentPage() {
const { provider, isLoading: accountLoading } = useAccount();
const [isReconnecting, setIsReconnecting] = useState(false);

const handleReconnect = async () => {
setIsReconnecting(true);

try {
const accountProvider = provider === "microsoft" ? "microsoft" : "google";
const url = await getAccountLinkingUrl(accountProvider);
window.location.href = url;
} catch (error) {
console.error("Error initiating reconnection:", error);
toastError({
title: "Error initiating reconnection",
description: "Please try again or contact support",
});
} finally {
setIsReconnecting(false);
}
};

return (
<div className="flex flex-col items-center justify-center sm:p-20 md:p-32">
<PageHeading className="text-center">
We are missing consent 😔
We are missing permissions 😔
</PageHeading>

<TypographyP className="mx-auto mt-4 max-w-prose text-center">
Expand All @@ -19,9 +43,11 @@ export default function PermissionsConsentPage() {

<Button
className="mt-4"
onClick={() => logOut("/login?error=RequiresReconsent")}
onClick={handleReconnect}
loading={isReconnecting}
disabled={isReconnecting || accountLoading}
>
Sign in again
Reconnect account
</Button>

<div className="mt-8">
Expand Down
39 changes: 0 additions & 39 deletions apps/web/app/(app)/[emailAccountId]/permissions/error/page.tsx

This file was deleted.

27 changes: 5 additions & 22 deletions apps/web/app/(app)/accounts/AddAccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,21 @@ import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { toastError } from "@/components/Toast";
import Image from "next/image";
import type { GetAuthLinkUrlResponse } from "@/app/api/google/linking/auth-url/route";
import type { GetOutlookAuthLinkUrlResponse } from "@/app/api/outlook/linking/auth-url/route";
import { TypographyP } from "@/components/Typography";
import { getAccountLinkingUrl } from "@/utils/account-linking";

export function AddAccount() {
const [isLoadingGoogle, setIsLoadingGoogle] = useState(false);
const [isLoadingMicrosoft, setIsLoadingMicrosoft] = useState(false);

const handleAddAccount = async (provider: "google" | "outlook") => {
const handleAddAccount = async (provider: "google" | "microsoft") => {
const setLoading =
provider === "google" ? setIsLoadingGoogle : setIsLoadingMicrosoft;
setLoading(true);

try {
const response = await fetch(`/api/${provider}/linking/auth-url`, {
method: "GET",
headers: { "Content-Type": "application/json" },
});

if (!response.ok) {
toastError({
title: `Error initiating ${provider === "google" ? "Google" : "Microsoft"} link`,
description: "Please try again or contact support",
});
setLoading(false);
return;
}

const data: GetAuthLinkUrlResponse | GetOutlookAuthLinkUrlResponse =
await response.json();

window.location.href = data.url;
const url = await getAccountLinkingUrl(provider);
window.location.href = url;
} catch (error) {
console.error(`Error initiating ${provider} link:`, error);
toastError({
Expand Down Expand Up @@ -69,7 +52,7 @@ export function AddAccount() {
<Button
variant="outline"
className="w-full"
onClick={() => handleAddAccount("outlook")}
onClick={() => handleAddAccount("microsoft")}
loading={isLoadingMicrosoft}
disabled={isLoadingGoogle || isLoadingMicrosoft}
>
Expand Down
46 changes: 31 additions & 15 deletions apps/web/app/(landing)/login/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,51 @@ import {
} from "@/components/ui/dialog";
import { signIn } from "@/utils/auth-client";
import { WELCOME_PATH } from "@/utils/config";
import { toastError } from "@/components/Toast";

export function LoginForm() {
const searchParams = useSearchParams();
const next = searchParams?.get("next");
const error = searchParams?.get("error");

const [loadingGoogle, setLoadingGoogle] = useState(false);
const [loadingMicrosoft, setLoadingMicrosoft] = useState(false);

const handleGoogleSignIn = async () => {
setLoadingGoogle(true);
await signIn.social({
provider: "google",
errorCallbackURL: "/login/error",
callbackURL: next && next.length > 0 ? next : WELCOME_PATH,
...(error === "RequiresReconsent" ? { consent: true } : {}),
});
setLoadingGoogle(false);
try {
await signIn.social({
provider: "google",
errorCallbackURL: "/login/error",
callbackURL: next && next.length > 0 ? next : WELCOME_PATH,
});
} catch (error) {
console.error("Error signing in with Google:", error);
toastError({
title: "Error signing in with Google",
description: "Please try again or contact support",
});
} finally {
setLoadingGoogle(false);
}
};

const handleMicrosoftSignIn = async () => {
setLoadingMicrosoft(true);
await signIn.social({
provider: "microsoft",
errorCallbackURL: "/login/error",
callbackURL: next && next.length > 0 ? next : WELCOME_PATH,
...(error === "RequiresReconsent" ? { consent: true } : {}),
});
setLoadingMicrosoft(false);
try {
await signIn.social({
provider: "microsoft",
errorCallbackURL: "/login/error",
callbackURL: next && next.length > 0 ? next : WELCOME_PATH,
});
} catch (error) {
console.error("Error signing in with Microsoft:", error);
toastError({
title: "Error signing in with Microsoft",
description: "Please try again or contact support",
});
} finally {
setLoadingMicrosoft(false);
}
};

return (
Expand Down
35 changes: 35 additions & 0 deletions apps/web/app/api/google/linking/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,41 @@ export const GET = withError("google/linking/callback", async (request) => {
return successResponse;
}

if (linkingResult.type === "update_tokens") {
logger.info("Updating tokens for existing Google account", {
email: providerEmail,
targetUserId,
accountId: linkingResult.existingAccountId,
});

await prisma.account.update({
where: { id: linkingResult.existingAccountId },
data: {
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
expires_at: tokens.expiry_date ? new Date(tokens.expiry_date) : null,
scope: tokens.scope,
token_type: tokens.token_type,
id_token: tokens.id_token,
},
});

logger.info("Successfully updated tokens for Google account", {
email: providerEmail,
targetUserId,
accountId: linkingResult.existingAccountId,
});

await setOAuthCodeResult(code, { success: "tokens_updated" });

const successUrl = new URL("/accounts", env.NEXT_PUBLIC_BASE_URL);
successUrl.searchParams.set("success", "tokens_updated");
const successResponse = NextResponse.redirect(successUrl);
successResponse.cookies.delete(GOOGLE_LINKING_STATE_COOKIE_NAME);

return successResponse;
}

logger.info("Merging Google account (user confirmed).", {
email: providerEmail,
providerAccountId,
Expand Down
45 changes: 45 additions & 0 deletions apps/web/app/api/outlook/linking/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,51 @@ export const GET = withError("outlook/linking/callback", async (request) => {
return successResponse;
}

if (linkingResult.type === "update_tokens") {
logger.info("Updating tokens for existing Microsoft account", {
email: providerEmail,
targetUserId,
accountId: linkingResult.existingAccountId,
});

let expiresAt: Date | null = null;
if (tokens.expires_at) {
expiresAt = new Date(tokens.expires_at * 1000);
} else if (tokens.expires_in) {
const expiresInSeconds =
typeof tokens.expires_in === "string"
? Number.parseInt(tokens.expires_in, 10)
: tokens.expires_in;
expiresAt = new Date(Date.now() + expiresInSeconds * 1000);
}

await prisma.account.update({
where: { id: linkingResult.existingAccountId },
data: {
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
expires_at: expiresAt,
scope: tokens.scope,
token_type: tokens.token_type,
},
});

logger.info("Successfully updated tokens for Microsoft account", {
email: providerEmail,
targetUserId,
accountId: linkingResult.existingAccountId,
});

await setOAuthCodeResult(code, { success: "tokens_updated" });

const successUrl = new URL("/accounts", env.NEXT_PUBLIC_BASE_URL);
successUrl.searchParams.set("success", "tokens_updated");
const successResponse = NextResponse.redirect(successUrl);
successResponse.cookies.delete(OUTLOOK_LINKING_STATE_COOKIE_NAME);

return successResponse;
}

logger.info("Merging Microsoft account (user confirmed).", {
email: providerEmail,
targetUserId,
Expand Down
29 changes: 29 additions & 0 deletions apps/web/utils/account-linking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { GetAuthLinkUrlResponse } from "@/app/api/google/linking/auth-url/route";
import type { GetOutlookAuthLinkUrlResponse } from "@/app/api/outlook/linking/auth-url/route";

/**
* Initiates the OAuth account linking flow for Google or Microsoft.
* Returns the OAuth URL to redirect the user to.
* @throws Error if the request fails
*/
export async function getAccountLinkingUrl(
provider: "google" | "microsoft",
): Promise<string> {
const apiProvider = provider === "microsoft" ? "outlook" : "google";

const response = await fetch(`/api/${apiProvider}/linking/auth-url`, {
method: "GET",
headers: { "Content-Type": "application/json" },
});

if (!response.ok) {
throw new Error(
`Failed to initiate ${provider === "google" ? "Google" : "Microsoft"} account linking`,
);
}

const data: GetAuthLinkUrlResponse | GetOutlookAuthLinkUrlResponse =
await response.json();

return data.url;
}
Loading
Loading