124_webcalibre2/src/lib/auth-utils.ts

62 lines
2.2 KiB
TypeScript
Raw Normal View History

2026-01-21 01:34:02 +00:00
// src/lib/auth-utils.ts
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)
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,
2026-01-21 01:34:02 +00:00
// CRITICAL: Re-declare scopes to ensure the new access_token has OneDrive permissions
scope: "openid profile offline_access Files.ReadWrite Files.Read",
}),
});
const tokens = await response.json();
2026-01-21 01:34:02 +00:00
if (!response.ok) {
console.error("❌ Microsoft Token Refresh Response Error:", tokens);
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),
2026-01-21 01:34:02 +00:00
// Microsoft sometimes rotates the refresh_token; save it if they provide a new one
refresh_token: tokens.refresh_token ?? account.refresh_token,
},
});
return tokens.access_token;
} catch (error) {
console.error("❌ Failed to refresh Microsoft token:", error);
2026-01-21 01:34:02 +00:00
// Returning a specific error string helps Auth.js or your components handle re-auth
throw new Error("RefreshAccessTokenError");
}
}