Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
Fix localStorage usage
Andrew Bastinf4f29b8520c8
diff --git a/.eslintrc.js b/.eslintrc.jsindex 260788273..3269a9c94 100644--- a/.eslintrc.js+++ b/.eslintrc.js@@ -49,14 +49,14 @@ module.exports = {name: "localStorage",message:"Do not use 'localStorage' directly. Please use localpersistence.ts functions or stores",- }+ },],// window.localStorage block"no-restricted-syntax": ["error",{selector: "CallExpression[callee.object.property.name='localStorage']",- message:+ message:"Do not use 'localStorage' directly. Please use localpersistence.ts functions or stores",},],diff --git a/components/app/Header.vue b/components/app/Header.vueindex 3c4a21340..add6669e1 100644--- a/components/app/Header.vue+++ b/components/app/Header.vue@@ -167,6 +167,7 @@<script>import intializePwa from "~/helpers/pwa"import { currentUser$ } from "~/helpers/fb/auth"+import { getLocalConfig, setLocalConfig } from "~/newstore/localpersistence"// import { hasExtensionInstalled } from "~/helpers/strategies/ExtensionStrategy"export default {@@ -192,7 +193,7 @@ export default {// Initializes the PWA code - checks if the app is installed,// etc.this.showInstallPrompt = await intializePwa()- const cookiesAllowed = localStorage.getItem("cookiesAllowed") === "yes"+ const cookiesAllowed = getLocalConfig("cookiesAllowed") === "yes"if (!cookiesAllowed) {this.$toast.show(this.$t("we_use_cookies"), {icon: "info",@@ -202,7 +203,7 @@ export default {{text: this.$t("dismiss"),onClick: (_, toastObject) => {- localStorage.setItem("cookiesAllowed", "yes")+ setLocalConfig("cookiesAllowed", "yes")toastObject.goAway(0)},},diff --git a/components/firebase/Email.vue b/components/firebase/Email.vueindex a84b6095c..730dd4a4c 100644--- a/components/firebase/Email.vue+++ b/components/firebase/Email.vue@@ -70,6 +70,7 @@<script>import { currentUser$, signInWithEmail } from "~/helpers/fb/auth"+import { setLocalConfig } from "~/newstore/localpersistence"export default {props: {@@ -101,7 +102,7 @@ export default {await signInWithEmail(this.form.email, actionCodeSettings).then(() => {this.mode = "email"- window.localStorage.setItem("emailForSignIn", this.form.email)+ setLocalConfig("emailForSignIn", this.form.email)}).catch((error) => {this.$toast.error(error.message, {diff --git a/components/smart/AccentModePicker.vue b/components/smart/AccentModePicker.vueindex f05c0ce6c..a296c11b6 100644--- a/components/smart/AccentModePicker.vue+++ b/components/smart/AccentModePicker.vue@@ -39,10 +39,12 @@</template><script>+import { getLocalConfig, setLocalConfig } from "~/newstore/localpersistence"+export default {data() {return {- active: localStorage.getItem("THEME_COLOR") || "green",+ active: getLocalConfig("THEME_COLOR") || "green",accentColors: ["blue","green",@@ -58,7 +60,7 @@ export default {},watch: {active(color) {- localStorage.setItem("THEME_COLOR", color)+ setLocalConfig("THEME_COLOR", color)},},diff --git a/helpers/oauth.js b/helpers/oauth.jsindex f85c314c0..c60ce5524 100644--- a/helpers/oauth.js+++ b/helpers/oauth.js@@ -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 valueconst 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 challengeconst 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 tokenif (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 tokenResponsediff --git a/helpers/pwa.js b/helpers/pwa.jsindex a03561ba6..60d580592 100644--- a/helpers/pwa.js+++ b/helpers/pwa.js@@ -1,21 +1,23 @@+import { getLocalConfig, setLocalConfig } from "~/newstore/localpersistence"+export default () => {//* ** Determine whether or not the PWA has been installed. ***//// Step 1: Check local storage- let pwaInstalled = localStorage.getItem("pwaInstalled") === "yes"+ let pwaInstalled = getLocalConfig("pwaInstalled") === "yes"// Step 2: Check if the display-mode is standalone. (Only permitted for PWAs.)if (!pwaInstalled &&window.matchMedia("(display-mode: standalone)").matches) {- localStorage.setItem("pwaInstalled", "yes")+ setLocalConfig("pwaInstalled", "yes")pwaInstalled = true}// Step 3: Check if the navigator is in standalone mode. (Again, only permitted for PWAs.)if (!pwaInstalled && window.navigator.standalone === true) {- localStorage.setItem("pwaInstalled", "yes")+ setLocalConfig("pwaInstalled", "yes")pwaInstalled = true}@@ -32,7 +34,7 @@ export default () => {// When the app is installed, remove install prompts.window.addEventListener("appinstalled", () => {- localStorage.setItem("pwaInstalled", "yes")+ setLocalConfig("pwaInstalled", "yes")pwaInstalled = truedocument.getElementById("installPWA").style.display = "none"})diff --git a/layouts/default.vue b/layouts/default.vueindex 6913f3891..3d0c747a5 100644--- a/layouts/default.vue+++ b/layouts/default.vue@@ -14,7 +14,10 @@</template><script>-import { setupLocalPersistence } from "~/newstore/localpersistence"+import {+ setupLocalPersistence,+ getLocalConfig,+} from "~/newstore/localpersistence"import { performMigrations } from "~/helpers/migrations"import { initUserInfo } from "~/helpers/teams/BackendUserInfo"import { registerApolloAuthUpdate } from "~/helpers/apollo"@@ -24,7 +27,7 @@ export default {beforeMount() {registerApolloAuthUpdate()- const color = localStorage.getItem("THEME_COLOR") || "green"+ const color = getLocalConfig("THEME_COLOR") || "green"document.documentElement.setAttribute("data-accent", color)},async mounted() {diff --git a/layouts/error.vue b/layouts/error.vueindex 9d2518194..61d003e62 100644--- a/layouts/error.vue+++ b/layouts/error.vue@@ -39,9 +39,6 @@ export default {},}},- beforeMount() {- initializeFirebase()- },computed: {statusCode() {return (this.error && this.error.statusCode) || 500@@ -50,6 +47,9 @@ export default {return this.error.message || this.$t("something_went_wrong")},},+ beforeMount() {+ initializeFirebase()+ },methods: {reloadApplication() {diff --git a/newstore/localpersistence.ts b/newstore/localpersistence.tsindex ea7436ce4..f915763e7 100644--- a/newstore/localpersistence.ts+++ b/newstore/localpersistence.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-globals, no-restricted-syntax */+import clone from "lodash/clone"import assign from "lodash/assign"import eq from "lodash/eq"@@ -131,3 +133,31 @@ export function setupLocalPersistence() {setupCollectionsPersistence()setupEnvironmentsPersistence()}++/**+ * Gets a value in LocalStorage.+ *+ * NOTE: Use LocalStorage to only store non-reactive simple data+ * For more complex data, use stores and connect it to localpersistence+ */+export function getLocalConfig(name: string) {+ return window.localStorage.getItem(name)+}++/**+ * Sets a value in LocalStorage.+ *+ * NOTE: Use LocalStorage to only store non-reactive simple data+ * For more complex data, use stores and connect it to localpersistence+ */+export function setLocalConfig(key: string, value: string) {+ window.localStorage.setItem(key, value)+}++/**+ * Clear config value in LocalStorage.+ * @param key Key to be cleared+ */+export function removeLocalConfig(key: string) {+ window.localStorage.removeItem(key)+}diff --git a/pages/enter.vue b/pages/enter.vueindex 301c16e60..2c954d5eb 100644--- a/pages/enter.vue+++ b/pages/enter.vue@@ -10,6 +10,7 @@import Vue from "vue"import { initializeFirebase } from "~/helpers/fb"import { isSignInWithEmailLink, signInWithEmailLink } from "~/helpers/fb/auth"+import { getLocalConfig, removeLocalConfig } from "~/newstore/localpersistence"export default Vue.extend({data() {@@ -25,7 +26,7 @@ export default Vue.extend({if (isSignInWithEmailLink(window.location.href)) {this.signingInWithEmail = true- let email = window.localStorage.getItem("emailForSignIn")+ let email = getLocalConfig("emailForSignIn")if (!email) {email = window.prompt(@@ -35,7 +36,7 @@ export default Vue.extend({await signInWithEmailLink(email, window.location.href).then(() => {- window.localStorage.removeItem("emailForSignIn")+ removeLocalConfig("emailForSignIn")this.$router.push({ path: "/" })}).catch((error) => {