fix authentification

This commit is contained in:
Saadani-Malek92 2024-05-17 17:10:37 +01:00
parent e1436f1eff
commit b785227d74
3 changed files with 116 additions and 49 deletions

View File

@ -28,6 +28,9 @@ import ElTypography from "../layouts/sections/elements/typography/TypographyView
import UserLoginView from "../views/Auth/UserLogin.vue"; import UserLoginView from "../views/Auth/UserLogin.vue";
// import AdminView from "../views/LandingPages/Author/AuthorView.vue"; // import AdminView from "../views/LandingPages/Author/AuthorView.vue";
import { Role } from './constants'; import { Role } from './constants';
import { useStore } from '@/stores'
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@ -174,43 +177,58 @@ const router = createRouter({
}); });
function isAuthenticated() {
// Check if the user is authenticated, e.g., by verifying the presence of a valid token or logged-in state
// Return true if authenticated, false otherwise
// Example: return localStorage.getItem('token') !== null;
return true;
}
function getCurrentUserRole() {
// Retrieve the current user's role from your authentication system or state management
// Return the role of the current user
// Example: return localStorage.getItem('userRole');
return "guest";
}
// Route guard
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) { const store = useStore()
// Check if the user is authenticated, e.g., by checking the presence of a valid token or logged-in state console.log(store.isAuthenticated,store.user,"store")
if (isAuthenticated()) { //console.log(store.isAuthenticated,"store")
// Check if the user has the required role if (to.meta.requiresAuth && !store.isAuthenticated) {
if (to.meta.requiredRole && getCurrentUserRole() !== to.meta.requiredRole) { next('/admin/auth')
// Redirect to a different route or show an error message } else if (to.meta.requiresVisitor && store.isAuthenticated) {
next({ path: '/unauthorized' }); next('/sections/elements/progress-bars')
} else { } else {
// Proceed to the requested route next()
next();
} }
} else { })
// Redirect to the login page or a suitable route for unauthenticated users
next({ path: '/logout' });
}
} else { // function isAuthenticated() {
// No authentication required for the route // // Check if the user is authenticated, e.g., by verifying the presence of a valid token or logged-in state
next(); // // Return true if authenticated, false otherwise
} // // Example: return localStorage.getItem('token') !== null;
});
// return true;
// }
// function getCurrentUserRole() {
// // Retrieve the current user's role from your authentication system or state management
// // Return the role of the current user
// // Example: return localStorage.getItem('userRole');
// return "guest";
// }
// // Route guard
// router.beforeEach((to, from, next) => {
// if (to.meta.requiresAuth) {
// // Check if the user is authenticated, e.g., by checking the presence of a valid token or logged-in state
// if (isAuthenticated()) {
// // Check if the user has the required role
// if (to.meta.requiredRole && getCurrentUserRole() !== to.meta.requiredRole) {
// // Redirect to a different route or show an error message
// next({ path: '/unauthorized' });
// } else {
// // Proceed to the requested route
// next();
// }
// } else {
// // Redirect to the login page or a suitable route for unauthenticated users
// next({ path: '/logout' });
// }
// } else {
// // No authentication required for the route
// next();
// }
// });
export default router; export default router;

View File

@ -1,7 +1,27 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import bootstrap from "bootstrap/dist/js/bootstrap.min.js"; import bootstrap from "bootstrap/dist/js/bootstrap.min.js";
export const useAppStore = defineStore("storeId", { export const useAppStore = defineStore("storeId", {
state: () => ({ state: () => ({
bootstrap, bootstrap,
}), }),
}); });
export const useStore = defineStore({
id: 'main',
state: () => ({
isAuthenticated: false,
user: null,
}),
actions: {
login(user) {
this.isAuthenticated = true
this.user = user
},
logout() {
this.isAuthenticated = false
this.user = null
},
},
})

View File

@ -5,22 +5,47 @@ import MaterialInput from "@/components/MaterialInput.vue";
import MaterialButton from "@/components/MaterialButton.vue"; import MaterialButton from "@/components/MaterialButton.vue";
import setMaterialInput from "@/assets/js/material-input"; import setMaterialInput from "@/assets/js/material-input";
import axios from "axios"; import axios from "axios";
import { ref } from 'vue'
import { useStore } from '@/stores'
import router from '@/router'
onMounted(() => { onMounted(() => {
setMaterialInput(); setMaterialInput();
}); });
const store = useStore()
const email = ref('')
const password = ref('')
const handleLogin = async () => { const handleLogin = async () => {
try { try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts?userId=1'); // Send a POST request to the login endpoint
console.log(response.data); const response = await axios.get('https://dummyjson.com/products/1', {
email: email.value,
password: password.value
})
// Redirect the user to the admin dashboard // Check if the login was successful
// router.push('/admin/dashboard'); console.log(response && response.status===200);
if (response && response.status===200) {
// Save the user to the store
store.login({
name: response.data.name,
email: response.data.email
})
// Navigate the user to the admin dashboard
router.push('/')
} else {
// Display an error message if the login failed
alert('Invalid email or password')
}
} catch (err) { } catch (err) {
console.log('Error:', err); console.log('Error:', err);
} }
}; };
</script> </script>
<template> <template>
<Header> <Header>
<div <div
@ -57,22 +82,26 @@ const handleLogin = async () => {
class="input-group-outline my-3" class="input-group-outline my-3"
:label="{ text: 'Email', class: 'form-label' }" :label="{ text: 'Email', class: 'form-label' }"
type="email" type="email"
v-model="email"
/> />
<MaterialInput <MaterialInput
id="password" id="password"
class="input-group-outline mb-3" class="input-group-outline mb-3"
:label="{ text: 'Password', class: 'form-label' }" :label="{ text: 'Password', class: 'form-label' }"
type="password" type="password"
v-model="password"
/> />
<button type="submit">login</button>
<div class="text-center"> <div class="text-center">
<MaterialButton <MaterialButton
class="my-4 mb-2" class="my-4 mb-2"
variant="gradient" variant="gradient"
color="info" color="info"
fullWidth fullWidth
>Sign in</MaterialButton @click="handleLogin"
> >
Sign in
</MaterialButton>
</div> </div>
</form> </form>
</div> </div>