fix: github access_token refresh

This commit is contained in:
Elie Baier 2024-03-24 11:29:02 +01:00
parent df54fb164c
commit 8d6bbe13de
1 changed files with 11 additions and 9 deletions

View File

@ -15,7 +15,7 @@ export const authOptions: NextAuthOptions = {
name: profile.name, name: profile.name,
email: profile.email, email: profile.email,
image: profile.avatar_url, image: profile.avatar_url,
username: profile.username, username: profile.login,
} as User; } as User;
}, },
}), }),
@ -35,25 +35,28 @@ export const authOptions: NextAuthOptions = {
if ((github.expires_at || 0) * 1000 < Date.now()) { if ((github.expires_at || 0) * 1000 < Date.now()) {
// If the access token has expired, try to refresh it // If the access token has expired, try to refresh it
try { try {
const response = await fetch("https://github.com/login/oauth/access_token", {
headers: { "Content-Type": "application/json" }, const params = new URLSearchParams({
body: JSON.stringify({
client_id: process.env.GITHUB_ID as string, client_id: process.env.GITHUB_ID as string,
client_secret: process.env.GITHUB_SECRET as string, client_secret: process.env.GITHUB_SECRET as string,
grant_type: "refresh_token", grant_type: "refresh_token",
refresh_token: github.refresh_token as string, refresh_token: github.refresh_token as string,
}), });
const response = await fetch("https://github.com/login/oauth/access_token?" + params, {
headers: { "Accept": "application/json" },
method: "POST", method: "POST",
}) })
const tokens: TokenSet = await response.json() const tok = await response.json()
const tokens: TokenSet = tok;
if (!response.ok) throw tokens if (!response.ok) throw tokens
await prisma.account.update({ await prisma.account.update({
data: { data: {
access_token: tokens.access_token, access_token: tokens.access_token,
expires_at: Math.floor(Date.now() / 1000 + (tokens.expires_at as number)), expires_at: Math.floor(Date.now() / 1000 + (tokens.expires_in as number)),
refresh_token: tokens.refresh_token ?? github.refresh_token, refresh_token: tokens.refresh_token ?? github.refresh_token,
}, },
where: { where: {
@ -87,7 +90,6 @@ export const authOptions: NextAuthOptions = {
username: u.username, username: u.username,
}; };
} }
console.log(token);
return { ...token, username: token.username }; return { ...token, username: token.username };
}, },
}, },