Fix code sample for getting a token (#18)

The code sample had multiple problems. The most important one was that
it did not run because the call to `checkIfUpdated` was incorrect and
the code didn't take into account that a DOMException is thrown when
trying to read `popup.location.href` before the redirect happened. Apart from
that I added url encoding of the query parameters and some simple sanity
checks on the received `token` and `assertion` values in order to make
the sample a bit more robust.
This commit is contained in:
Async10 2023-09-11 16:14:31 +02:00 committed by GitHub
parent 77ddb1cd17
commit df7194b914
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,19 +20,41 @@ The root URL for these APIs is `https://play.pokemonshowdown.com/api`.
Here's a simple functionality example for getting a token for a user. Here's a simple functionality example for getting a token for a user.
```ts ```ts
const url = `https://play.pokemonshowdown.com/api/oauth/authorize?redirect_uri=https://mysite.com/oauth-demo&client_id=${clientId}`; const authorizeUrl = new URL('https://play.pokemonshowdown.com/api/oauth/authorize');
const nWindow = window.n = open(url, null, 'popup=1'); authorizeUrl.searchParams.append('redirect_uri', 'https://mysite.com/oauth-demo');
authorizeUrl.searchParams.append('client_id', clientId);
authorizeUrl.searchParams.append('challenge', challenge);
const popup = window.open(authorizeUrl, undefined, 'popup=1');
const checkIfUpdated = () => { const checkIfUpdated = () => {
if (nWindow.location.host === 'mysite.com') { try {
const url = new URL(nWindow.location.href); if (popup?.location?.href?.startsWith(redirectUri)) {
runLoginWithAssertion(url.searchParams.get('assertion')); const url = new URL(popup.location.href);
localStorage.setItem('ps-token', url.searchParams.get('token')); const assertion = url.searchParams.get('assertion');
nWindow.close(); if (!assertion) {
} else { console.error('Received no assertion');
setTimeout(checkIfUpdated(1000)); return;
} }
runLoginWithAssertion(url.searchParams.get('assertion'));
const token = url.searchParams.get('token');
if (!token) {
console.error('Received no token')
return;
}
localStorage.setItem('ps-token', token);
popup.close();
} else {
setTimeout(checkIfUpdated, 500);
}
} catch (DOMException) {
setTimeout(checkIfUpdated, 500);
}
}; };
setTimeout(checkIfUpdated, 1500);
checkIfUpdated();
``` ```
This opens the OAuth authorization page in a new window, waits for the user to click the button in the new window, then once the window's URL has changed, extracts the assertion and token from the new querystring, caches the token, and uses the assertion to log in. This opens the OAuth authorization page in a new window, waits for the user to click the button in the new window, then once the window's URL has changed, extracts the assertion and token from the new querystring, caches the token, and uses the assertion to log in.