Skip to content

Commit

Permalink
Merge pull request #146 from Brendonovich/REFRESH_CHANGES
Browse files Browse the repository at this point in the history
Moved expiry check into refresh token function in auth.
  • Loading branch information
jdudetv authored Jul 4, 2023
2 parents 962ea7e + acc4ae5 commit 3fdb19c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
12 changes: 8 additions & 4 deletions packages/src/twitch/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,17 +93,21 @@ class MacroGraphAuthProvider {
async refreshAccessTokenForUser(user: string): Promise<User> {
const userId = user;

const { userName, refreshToken } = Maybe(this.tokens.get(userId)).expect(
const token = Maybe(this.tokens.get(userId)).expect(
"refreshAccessTokenForUser missing token"
);

Maybe(refreshToken).expect("Refresh token is null!");
if (Date.now() < token.obtainmentTimestamp + token.expiresIn * 1000) {
return token;
}

Maybe(token.refreshToken).expect("Refresh token is null!");

const res = await fetch("https://macrograph.brendonovich.dev/auth/twitch", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
refreshToken,
refreshToken: token.refreshToken,
}),
});

Expand All @@ -115,7 +119,7 @@ class MacroGraphAuthProvider {
expiresIn: data.expires_in ?? null,
obtainmentTimestamp: Date.now(),
userId,
userName,
userName: token.userName,
};

this.tokens.set(userId, returnData);
Expand Down
5 changes: 1 addition & 4 deletions packages/src/twitch/helix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ export const { client, userId, setUserId } = createRoot(() => {
fetchFn: async (url, args) => {
const user = await auth.getAccessTokenForUser(userId().unwrap());
const token = auth.tokens.get(userId().unwrap());
if (Date.now() > token?.obtainmentTimestamp + token?.expiresIn * 1000) {
await auth.refreshAccessTokenForUser(token?.userId);
console.log("refreshing");
}
await auth.refreshAccessTokenForUser(token?.userId);
if (args.body instanceof URLSearchParams) {
url = `${url}?${args.body.toString()}`;
}
Expand Down

0 comments on commit 3fdb19c

Please sign in to comment.