(discord: Account)
| 750 | } |
| 751 | |
| 752 | export async function refreshAccessToken(discord: Account) { |
| 753 | if (!discord.refresh_token) { |
| 754 | throw new Error('No refresh token'); |
| 755 | } |
| 756 | const params = new URLSearchParams(); |
| 757 | params.append('client_id', sharedEnvs.DISCORD_CLIENT_ID!); |
| 758 | params.append('client_secret', sharedEnvs.DISCORD_CLIENT_SECRET!); |
| 759 | params.append('grant_type', 'refresh_token'); |
| 760 | params.append('refresh_token', discord.refresh_token ?? ''); |
| 761 | try { |
| 762 | console.log('Fetching new token'); |
| 763 | const inUse = await isRefreshTokenBeingUsed(discord.refresh_token); |
| 764 | if (inUse) { |
| 765 | console.log('Token is being used'); |
| 766 | return; |
| 767 | } |
| 768 | await setRefreshTokenBeingUsed(discord.refresh_token, true); |
| 769 | const body = { |
| 770 | client_id: sharedEnvs.DISCORD_CLIENT_ID!, |
| 771 | client_secret: sharedEnvs.DISCORD_CLIENT_SECRET!, |
| 772 | grant_type: 'refresh_token', |
| 773 | refresh_token: discord.refresh_token ?? '', |
| 774 | }; |
| 775 | const res = await fetch('https://discord.com/api/v10/oauth2/token', { |
| 776 | method: 'POST', |
| 777 | body: JSON.stringify(body), |
| 778 | headers: { |
| 779 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 780 | }, |
| 781 | }); |
| 782 | |
| 783 | const zAccessTokenResponse = z.object({ |
| 784 | token_type: z.string(), |
| 785 | access_token: z.string(), |
| 786 | expires_in: z.number(), |
| 787 | refresh_token: z.string(), |
| 788 | scope: z.string(), |
| 789 | }); |
| 790 | const accessTokenResponse = zAccessTokenResponse.parse(await res.json()); |
| 791 | console.log('Updating token'); |
| 792 | await updateProviderAuthToken({ |
| 793 | provider: 'discord', |
| 794 | providerAccountId: discord.providerAccountId, |
| 795 | access_token: accessTokenResponse.access_token, |
| 796 | expires_at: |
| 797 | Math.floor(Date.now() / 1000) + accessTokenResponse.expires_in, |
| 798 | refresh_token: accessTokenResponse.refresh_token, |
| 799 | scope: accessTokenResponse.scope, |
| 800 | token_type: accessTokenResponse.token_type, |
| 801 | }); |
| 802 | await setRefreshTokenBeingUsed(discord.refresh_token, false); |
| 803 | } catch (error) { |
| 804 | await setRefreshTokenBeingUsed(discord.refresh_token, false); |
| 805 | // We're in a bad state so just prompt a re-auth |
| 806 | await db.delete(dbSessions).where(eq(dbSessions.userId, discord.userId)); |
| 807 | } |
| 808 | } |
| 809 | } |
no test coverage detected