55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
|
|
import { prisma } from "@/lib/prisma";
|
||
|
|
|
||
|
|
export async function getFreshAccessToken(userId: string) {
|
||
|
|
// 1. Find the account in PostgreSQL
|
||
|
|
const account = await prisma.account.findFirst({
|
||
|
|
where: { userId },
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!account || !account.refresh_token) {
|
||
|
|
throw new Error("No refresh token available. User might need to re-login.");
|
||
|
|
}
|
||
|
|
|
||
|
|
// 2. Check if the token is expired (with a 1-minute buffer)
|
||
|
|
// account.expires_at is usually in seconds, so we multiply by 1000
|
||
|
|
const isExpired = (account.expires_at ?? 0) * 1000 < Date.now() + 60000;
|
||
|
|
|
||
|
|
if (!isExpired && account.access_token) {
|
||
|
|
return account.access_token;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 3. If expired, request a new one from Microsoft
|
||
|
|
console.log("🔄 Access token expired. Refreshing for user:", userId);
|
||
|
|
|
||
|
|
try {
|
||
|
|
const response = await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
|
||
|
|
method: "POST",
|
||
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||
|
|
body: new URLSearchParams({
|
||
|
|
client_id: process.env.AUTH_MICROSOFT_ENTRA_ID_ID!,
|
||
|
|
client_secret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET!,
|
||
|
|
grant_type: "refresh_token",
|
||
|
|
refresh_token: account.refresh_token,
|
||
|
|
}),
|
||
|
|
});
|
||
|
|
|
||
|
|
const tokens = await response.json();
|
||
|
|
|
||
|
|
if (!response.ok) throw tokens;
|
||
|
|
|
||
|
|
// 4. Update the Account table with the new tokens
|
||
|
|
await prisma.account.update({
|
||
|
|
where: { id: account.id },
|
||
|
|
data: {
|
||
|
|
access_token: tokens.access_token,
|
||
|
|
expires_at: Math.floor(Date.now() / 1000 + tokens.expires_in),
|
||
|
|
refresh_token: tokens.refresh_token ?? account.refresh_token,
|
||
|
|
},
|
||
|
|
});
|
||
|
|
|
||
|
|
return tokens.access_token;
|
||
|
|
} catch (error) {
|
||
|
|
console.error("❌ Failed to refresh Microsoft token:", error);
|
||
|
|
throw new Error("RefreshAccessTokenError");
|
||
|
|
}
|
||
|
|
}
|