Skip to content

Commit

Permalink
refactor: replace cookie storage with a store (pinia) (#69)
Browse files Browse the repository at this point in the history
* Add pinia store

* Basic store

* Use store. Replace cookie storage and checkAuth
  • Loading branch information
raphodn authored Dec 26, 2023
1 parent 8aa6c05 commit 39ffc25
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 48 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"compressorjs": "^1.2.1",
"html5-qrcode": "^2.3.8",
"leaflet": "^1.9.4",
"pinia": "^2.1.7",
"universal-cookie": "^6.1.1",
"vue": "^3.3.9",
"vue-router": "^4.2.5",
Expand Down
8 changes: 5 additions & 3 deletions src/components/Header.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
</template>

<script>
import api from '../services/api'
import { mapStores } from 'pinia'
import { useAppStore } from '../store'
export default {
data() {
Expand All @@ -34,8 +35,9 @@ export default {
}
},
computed: {
...mapStores(useAppStore),
username() {
return api.getUsername()
return this.appStore.user.username
},
getDrawerMenuItems() {
return this.$router.options.routes
Expand All @@ -46,7 +48,7 @@ export default {
},
methods: {
signOut() {
api.signOut()
this.appStore.signOut()
this.$router.push({ path: '/' })
}
},
Expand Down
5 changes: 4 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import './assets/main.css'
import App from './App.vue'
import router from './router.js'
import { vuetify } from './plugins/vuetify.js'

let app = createApp(App)
const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)
app.use(vuetify)
app.mount('#app')
20 changes: 6 additions & 14 deletions src/router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createRouter, createWebHistory } from 'vue-router'
import api from './services/api';
import { useAppStore } from './store'
import Home from './views/Home.vue'
import SignIn from './views/SignIn.vue'
import UserDashboard from './views/UserDashboard.vue'
Expand Down Expand Up @@ -30,23 +30,15 @@ const router = createRouter({
routes: routes,
})

/**
* Method to check if the user is authenticated
*/
const checkAuth = async () => {
if (api.getToken()) return true
}

/**
* On each page change, check if it needs authentication.
* If required, but the user is not authenticated (cookie not present), then redirect to 'sign-in'
* If required, but the user is not authenticated (token unknown), then redirect to 'sign-in'
*/
router.beforeEach(async (to, from, next) => {
if(to.meta.requiresAuth) {
if(!(await checkAuth())) {
console.log("checkAuth")
return next({ name: 'sign-in' })
}
const store = useAppStore()
if(to.meta.requiresAuth && !store.user.token) {
console.log("checkAuth")
return next({ name: 'sign-in' })
}
next()
})
Expand Down
31 changes: 5 additions & 26 deletions src/services/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { useCookies } from '@vueuse/integrations/useCookies'
import { useAppStore } from '../store'

const NOMINATIM_SEARCH_URL = 'https://nominatim.openstreetmap.org/search'
const NOMINATIM_RESULT_TYPE_EXCLUDE_LIST = ['fuel', 'gas', 'casino']
const USERNAME_COOKIE_KEY = 'username'
const TOKEN_COOKIE_KEY = 'access_token'
const RECENT_LOCATIONS_LOCAL_STORAGE_KEY = 'recent_locations'
const LAST_CURRENCY_USED_LOCAL_STORAGE_KEY = 'last_currency_used'

Expand Down Expand Up @@ -57,47 +55,28 @@ export default {
.then((response) => response.json())
},

signOut() {
useCookies().remove(USERNAME_COOKIE_KEY)
useCookies().remove(TOKEN_COOKIE_KEY)
},

setUsernameCookie(username) {
useCookies().set(USERNAME_COOKIE_KEY, username)
},

setTokenCookie(token) {
useCookies().set(TOKEN_COOKIE_KEY, token)
},

getUsername() {
return useCookies().get(USERNAME_COOKIE_KEY)
},

getToken() {
return useCookies().get(TOKEN_COOKIE_KEY)
},

createProof(proofImage) {
const store = useAppStore()
let formData = new FormData()
formData.append('file', proofImage, proofImage.name)
formData.append('type', 'PRICE_TAG')
return fetch(`${import.meta.env.VITE_OPEN_PRICES_API_URL}/proofs/upload`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.getToken()}`
'Authorization': `Bearer ${store.user.token}`
},
body: formData,
})
.then((response) => response.json())
},

createPrice(priceData) {
const store = useAppStore()
return fetch(`${import.meta.env.VITE_OPEN_PRICES_API_URL}/prices`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.getToken()}`
'Authorization': `Bearer ${store.user.token}`
},
body: JSON.stringify(priceData),
})
Expand Down
21 changes: 21 additions & 0 deletions src/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
state: () => ({
user: {
username: null,
token: null,
},
}),
getters: {},
actions: {
signIn(username, token) {
this.user.username = username
this.user.token = token
},
signOut() {
this.user.username = null
this.user.token = null
}
}
})
6 changes: 4 additions & 2 deletions src/views/SignIn.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
</template>

<script>
import { mapStores } from 'pinia'
import { useAppStore } from '../store'
import api from '../services/api'
export default {
Expand All @@ -41,6 +43,7 @@ export default {
};
},
computed: {
...mapStores(useAppStore),
formFilled() {
return Object.values(this.signinForm).every(x => !!x)
}
Expand All @@ -52,8 +55,7 @@ export default {
.signIn(this.signinForm.username, this.signinForm.password)
.then((data) => {
if (data['access_token']) {
api.setUsernameCookie(this.signinForm.username)
api.setTokenCookie(data['access_token'])
this.appStore.signIn(this.signinForm.username, data['access_token'])
this.$router.push({ path: '/add', query: { signinSuccess: 'true' } })
} else {
alert('Error: wrong credentials')
Expand Down
5 changes: 4 additions & 1 deletion src/views/UserDashboard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
</template>

<script>
import { mapStores } from 'pinia'
import { useAppStore } from '../store'
import api from '../services/api'
import PriceCard from '../components/PriceCard.vue'
Expand All @@ -40,8 +42,9 @@ export default {
}
},
computed: {
...mapStores(useAppStore),
username() {
return api.getUsername()
return this.appStore.user.username
},
},
mounted() {
Expand Down
10 changes: 9 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,14 @@ picocolors@^1.0.0:
resolved "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz"
integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==

pinia@^2.1.7:
version "2.1.7"
resolved "https://registry.yarnpkg.com/pinia/-/pinia-2.1.7.tgz#4cf5420d9324ca00b7b4984d3fbf693222115bbc"
integrity sha512-+C2AHFtcFqjPih0zpYuvof37SFxMQ7OEG2zV9jRI12i9BOy3YQVAHwdKtyyc8pDcDyIc33WCIsZaCFWU7WWxGQ==
dependencies:
"@vue/devtools-api" "^6.5.0"
vue-demi ">=0.14.5"

postcss-value-parser@^4.2.0:
version "4.2.0"
resolved "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz"
Expand Down Expand Up @@ -616,7 +624,7 @@ vite@^4.5.0:
optionalDependencies:
fsevents "~2.3.2"

vue-demi@>=0.14.6:
vue-demi@>=0.14.5, vue-demi@>=0.14.6:
version "0.14.6"
resolved "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.6.tgz"
integrity sha512-8QA7wrYSHKaYgUxDA5ZC24w+eHm3sYCbp0EzcDwKqN3p6HqtTCGR/GVsPyZW92unff4UlcSh++lmqDWN3ZIq4w==
Expand Down

0 comments on commit 39ffc25

Please sign in to comment.