Fix localStorage usage

This commit is contained in:
Andrew Bastin
2021-06-21 00:27:45 -04:00
parent 257e2db651
commit f4f29b8520
10 changed files with 81 additions and 38 deletions

View File

@@ -1,3 +1,9 @@
import {
getLocalConfig,
setLocalConfig,
removeLocalConfig,
} from "~/newstore/localpersistence"
const redirectUri = `${window.location.origin}/`
// GENERAL HELPER FUNCTIONS
@@ -155,16 +161,16 @@ const tokenRequest = async ({
}
// Store oauth information
localStorage.setItem("tokenEndpoint", accessTokenUrl)
localStorage.setItem("client_id", clientId)
setLocalConfig("tokenEndpoint", accessTokenUrl)
setLocalConfig("client_id", clientId)
// Create and store a random state value
const state = generateRandomString()
localStorage.setItem("pkce_state", state)
setLocalConfig("pkce_state", state)
// Create and store a new PKCE codeVerifier (the plaintext random secret)
const codeVerifier = generateRandomString()
localStorage.setItem("pkce_codeVerifier", codeVerifier)
setLocalConfig("pkce_codeVerifier", codeVerifier)
// Hash and base64-urlencode the secret to use as the challenge
const codeChallenge = await pkceChallengeFromVerifier(codeVerifier)
@@ -194,7 +200,7 @@ const tokenRequest = async ({
* @returns {Object}
*/
const oauthRedirect = async () => {
const oauthRedirect = () => {
let tokenResponse = ""
const q = parseQueryString(window.location.search.substring(1))
// Check if the server returned an error string
@@ -204,30 +210,27 @@ const oauthRedirect = async () => {
// If the server returned an authorization code, attempt to exchange it for an access token
if (q.code) {
// Verify state matches what we set at the beginning
if (localStorage.getItem("pkce_state") !== q.state) {
if (getLocalConfig("pkce_state") !== q.state) {
alert("Invalid state")
} else {
try {
// Exchange the authorization code for an access token
tokenResponse = await sendPostRequest(
localStorage.getItem("tokenEndpoint"),
{
grant_type: "authorization_code",
code: q.code,
client_id: localStorage.getItem("client_id"),
redirect_uri: redirectUri,
codeVerifier: localStorage.getItem("pkce_codeVerifier"),
}
)
tokenResponse = sendPostRequest(getLocalConfig("tokenEndpoint"), {
grant_type: "authorization_code",
code: q.code,
client_id: getLocalConfig("client_id"),
redirect_uri: redirectUri,
codeVerifier: getLocalConfig("pkce_codeVerifier"),
})
} catch (err) {
console.log(`${error.error}\n\n${error.error_description}`)
}
}
// Clean these up since we don't need them anymore
localStorage.removeItem("pkce_state")
localStorage.removeItem("pkce_codeVerifier")
localStorage.removeItem("tokenEndpoint")
localStorage.removeItem("client_id")
removeLocalConfig("pkce_state")
removeLocalConfig("pkce_codeVerifier")
removeLocalConfig("tokenEndpoint")
removeLocalConfig("client_id")
return tokenResponse
}
return tokenResponse