Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

- Mise en place du store pour l'utilisateur #84

Merged
merged 3 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"dependencies": {
"@mdi/font": "7.0.96",
"moment": "^2.30.1",
"pinia": "^2.1.7",
"roboto-fontface": "*",
"vue": "^3.4.26",
"vue-i18n": "^9.13.1",
Expand Down
45 changes: 6 additions & 39 deletions src/App.vue
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
<template>
<v-app>
<Header :authenticated="authenticated" @logout-success="onLogout" @toggle-drawer="toggleDrawer"/>
<Navbar :authenticated="authenticated" :drawer="drawer" v-if="authenticated" @close="drawer = false"/>
<Header @logout-success="onLogout" @toggle-drawer="toggleDrawer"/>
<Navbar :drawer="drawer" @close="drawer = false"/>
<Footer />
<v-main>
<v-alert color="red" :title="backendErrorMessage" variant='outlined' density='compact' type='warning' :text='backendErrorDescription' closable v-if="backendError"></v-alert>
<router-view v-slot="{ Component }">
<component
:is="Component"
@backendError="setBackendError"
@backendSuccess="liftErrors"
@login-success="onLoginSuccess"
@backendSuccess="liftBackendError"
/>
</router-view>
</v-main>
Expand All @@ -23,26 +22,16 @@ import Header from '@/components/Structure/Header.vue'
import Navbar from '@/components/Structure/Navbar.vue'
import Footer from '@/components/Structure/Footer.vue'
import router from '@/router/index'
import { HttpStatusCode } from 'axios';
import DemandesService from '@/service/DemandesService'
import {HttpStatusCode} from 'axios'
import {useTheme} from 'vuetify'

const backendError = ref(false)
const backendErrorMessage = ref('')
const backendErrorDescription = ref('')
const authenticated = ref(false)
const drawer = ref(false)

const theme = useTheme()

onMounted(() => {
checkAuthentication();
const savedTheme = localStorage.getItem('theme')
if (savedTheme) {
theme.global.name.value = savedTheme
}
});

function setBackendError(error) {
backendError.value = true
let titleMessage = ''
Expand Down Expand Up @@ -80,35 +69,13 @@ function setBackendError(error) {
}
}

function liftErrors() {
function liftBackendError() {
backendError.value = false
}
function onLoginSuccess(userData) {
authenticated.value = true;
if (!userData.email) {
router.push('premiere-connexion');
} else {
router.push('accueil');
}
}

function onLogout(){
authenticated.value = false
router.push('identification')
}
function checkAuthentication() {
const user = sessionStorage.getItem('user');
authenticated.value = !!user;
if (authenticated.value) {
DemandesService.checkToken()
.then(() => {
console.log('Token valide');
})
.catch((error) => {
console.error('Erreur de vérification du token:', error);
onLogout();
});
}
}
function toggleDrawer() {
drawer.value = !drawer.value;
}
Expand Down
1 change: 0 additions & 1 deletion src/components/Simulation.vue
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ const isLoading = ref(true);
onMounted(() => {
demandesService.getNbLigneFichier(props.demande.id, props.demande.type)
.then(response => {
console.log(response.data);
nbNotice.value.nbTotalNotice = response.data;
});
demandesService.simulerLigne(props.demande.id, 0, props.demande.type)
Expand Down
14 changes: 8 additions & 6 deletions src/components/Structure/Header.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,19 @@

<script setup>
import DemandesService from '@/service/DemandesService'
import {useAuthStore} from '@/store/authStore'
import {computed} from 'vue'

const emit = defineEmits(['logout-success', 'toggle-drawer'])

defineProps({
authenticated: {
type: Boolean,
required: true,
},
const authStore = useAuthStore()

const authenticated = computed(() => {
return authStore.isAuthenticated
})

function logout () {
function logout() {
authStore.logout()
DemandesService.logout()
emit('logout-success')
}
Expand Down
9 changes: 5 additions & 4 deletions src/components/Structure/Navbar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,11 @@ defineProps({
type: Boolean,
required: true,
},
authenticated: {
type: Boolean,
required: true,
},
})

const authenticated = computed(() => {
const user = JSON.parse(sessionStorage.getItem('user'))
return !!user;
})

const theme = useTheme()
Expand Down
5 changes: 4 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { createApp } from 'vue'
import { createVuetify } from 'vuetify'
import router from '@/router'
import { en, fr } from 'vuetify/locale'
import { createPinia } from 'pinia'

const app = createApp(App)
app.config.productionTip = false
Expand All @@ -21,7 +22,9 @@ const vuetify = createVuetify({
},
})

const pinia = createPinia()

registerPlugins(app)

app.use(router).use(vuetify)
app.use(router).use(vuetify).use(pinia)
app.mount('#app')
25 changes: 11 additions & 14 deletions src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import ModificationEmail from '@/views/Utilisateur/ModificationEmail.vue';
import DemandesService from '@/service/DemandesService'
import RecouvSteps from '@/views/Recouvrement/RecouvSteps.vue';
import ExempSteps from '@/views/Exemplarisation/ExempSteps.vue';

const service = DemandesService;
import {useAuthStore} from '@/store/authStore'

const routes = [
{
Expand Down Expand Up @@ -149,25 +148,23 @@ const router = createRouter({
})

router.beforeEach(async (to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const authStore = useAuthStore();

if (requiresAuth) {
const user = JSON.parse(sessionStorage.getItem('user'))
const isAuthenticated = user && user.token

if (isAuthenticated) {
if (authStore.isAuthenticated) {
try {
const valid = await service.checkToken();
const valid = await DemandesService.checkToken();
if (valid.data) {
next();
} else {
console.error('Token invalide auprès du serveur')
service.logout()
next('/identification')
console.error('Token invalide auprès du serveur');
DemandesService.logout();
next('/identification');
}
} catch (error) {
console.error(error)
service.logout()
console.error(error);
DemandesService.logout();
next('/identification');
}
} else {
Expand All @@ -176,6 +173,6 @@ router.beforeEach(async (to, from, next) => {
} else {
next();
}
})
});

export default router
24 changes: 13 additions & 11 deletions src/service/DemandesService.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import axios from 'axios'
import { useAuthStore } from '@/store/authStore'

export class DemandesService {
//todo: renommer le service
constructor() {
this.client = axios.create({
baseURL: import.meta.env.VITE_API_URL
Expand All @@ -10,9 +10,9 @@ export class DemandesService {
// Ajout de l'intercepteur
this.client.interceptors.request.use(
(config) => {
const user = JSON.parse(sessionStorage.getItem('user'));
if (user && user.token) {
config.headers.Authorization = user.token;
const authStore = useAuthStore();
if (authStore.isAuthenticated && authStore.getToken) {
config.headers.Authorization = authStore.getToken;
}
return config;
},
Expand All @@ -31,26 +31,26 @@ export class DemandesService {
const userData = {
login: login,
shortname: response.data.shortname,
token: `Bearer ${response.data.accessToken}`,
userNum: response.data.userNum,
iln: response.data.iln,
role: response.data.role,
email: response.data.email
};
sessionStorage.setItem('user', JSON.stringify(userData));
const token = `Bearer ${response.data.accessToken}`
this.client.defaults.headers.common.Authorization = `Bearer ${response.data.accessToken}`;
const authStore = useAuthStore()
authStore.login(userData, token)
return userData;
})
.catch(error => {
console.error(error);
sessionStorage.clear();
throw error;
return Promise.reject(error);
});
}

logout() {
sessionStorage.removeItem('user');
sessionStorage.clear()
const authStore = useAuthStore();
authStore.logout();
delete this.client.defaults.headers.common.Authorization;
}

Expand All @@ -70,10 +70,12 @@ export class DemandesService {
return this.client.get(url)
}

//TODO MAJ STORE
modifierEmail(id, email){
const config = { headers: {'Content-Type': 'text/plain'} };
return this.client.patch(`utilisateurs/${id}`, email, config);
}
//TODO MAJ STORE
creerEmail(id, email){
const config = { headers: {'Content-Type': 'text/plain'} };
return this.client.post(`utilisateurs/${id}`, email, config);
Expand Down
30 changes: 30 additions & 0 deletions src/store/authStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
state: () => ({
authenticated: false,
user: null,
token: null
}),
getters: {
getUser: (state) => state.user,
isAuthenticated: (state) => state.authenticated,
getToken: (state) => state.token
},
actions: {
login(user, token) {
this.authenticated = true;
this.user = user;
this.token = token;
},
logout() {
this.authenticated = false;
this.user = null;
this.token = null;
},
setToken(token) {
this.token = token;
}
},
persist: true // This will persist the store to localStorage
});
1 change: 0 additions & 1 deletion src/views/Exemplarisation/ExempSteps.vue
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ onMounted(()=>{
if(props.id){
DemandesService.getDemande(props.id, "EXEMP")
.then(response => {
console.log(response.data);
demande.value = response.data;
switch (demande.value.etatDemande) {
case 'En préparation':
Expand Down
Loading