Skip to content

Commit

Permalink
Move token fetching to its own function
Browse files Browse the repository at this point in the history
  • Loading branch information
Lifeismana committed Oct 17, 2024
1 parent cdd1c9d commit b284d5c
Showing 1 changed file with 59 additions and 17 deletions.
76 changes: 59 additions & 17 deletions scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ let checkoutSessionId;
let userDataCache = null;
let userFamilyDataCache = null;
let userFamilySemaphore = null;
let tokenSemaphore = null;
let nextAllowedRequest = 0;

/** @type {browser} ExtensionApi */
Expand Down Expand Up @@ -196,24 +197,9 @@ async function FetchSteamUserFamilyData( callback )

try
{
const tokenResponseFetch = await fetch(
`https://store.steampowered.com/pointssummary/ajaxgetasyncconfig`,
{
credentials: 'include',
headers: {
Accept: 'application/json',
},
}
);
const token = await tokenResponseFetch.json();

if( !token || !token.success || !token.data || !token.data.webapi_token )
{
throw new Error( 'Are you logged on the Steam Store in this browser?' );
}

const token = await GetStoreToken();
const paramsSharedLibrary = new URLSearchParams();
paramsSharedLibrary.set( 'access_token', token.data.webapi_token );
paramsSharedLibrary.set( 'access_token', token );
paramsSharedLibrary.set( 'family_groupid', '0' ); // family_groupid is ignored
paramsSharedLibrary.set( 'include_excluded', 'true' );
paramsSharedLibrary.set( 'include_free', 'true' );
Expand Down Expand Up @@ -402,6 +388,62 @@ function GetAchievementsGroups( appid, callback )
.catch( ( error ) => callback( { success: false, error: error.message } ) );
}

/**
* @return {Promise<String>}
*/
async function GetStoreToken()
{
if( tokenSemaphore !== null )
{
return await tokenSemaphore ;
}
let token = null;
let semaphoreResolve = null;
tokenSemaphore = new Promise( resolve =>
{
semaphoreResolve = resolve;
} );

try
{
token = await GetLocalOption( { storetoken: false } ).then( data => data.storetoken );
if( token )
{
const jwt = token.split( '.' );
const payload = JSON.parse( atob( jwt[ 1 ] ) );
const expiration = payload.exp * 1000;
if( Date.now() < expiration )
{
return token;
}
}

token = await fetch(
`https://store.steampowered.com/pointssummary/ajaxgetasyncconfig`,
{
credentials: 'include',
headers: {
Accept: 'application/json',
},
}
).then( response =>response.json() );

if( !token || !token.success || !token.data || !token.data.webapi_token )
{
throw new Error( 'Are you logged on the Steam Store in this browser?' );
}

await SetLocalOption( 'storetoken', token.data.webapi_token );

return token.data.webapi_token;
}
finally
{
semaphoreResolve( token );
tokenSemaphore = null;
};
}

/**
* @param {Function} callback
*/
Expand Down

0 comments on commit b284d5c

Please sign in to comment.