How to write a condition for allowing the access to the current loggedIn user, user array which consist of teams array with set of permissions array.current loggedIn user details
{
path: "/administration",
name: "Administration",
component: PageAdministration,
meta: { requiresAuth: true,
haveAccess:true,
hasPermissions:[1,2,3,4,5,6,7,8,9,10,11]
},
router.beforeEach(()=>{
const currentUser=store.getters["auth/isCurrentUser"]
console.log(currentUser.teams);
currentUser.teams.forEach(element => {
element.permissions.forEach((p)=>{
console.log('print permissions',p.permissionType);
// How to acccess the 'hasPermissions' from route and compare with p.permissionType??
})
});
})
Related
I have navigation guards to prevent visitors from viewing protected pages without being logged in. One of the pages I want them to see without login is a dynamic route e.g. example.com/dynamic_part. Below is my vuejs code:
router.beforeEach((to, from, next) => {
let token = window.sessionStorage.getItem("local_token");
let whitelist = [
"/",
"/register",
"/login",
"/dynamic_part/",
];
below works but it doesn't allow for the dynamic route "/dynamic_part/"
if (whitelist.includes(to.path)) {
below works for the dynamic route but breaks other route guards i.e. can't move to Products after logging in. I get this error: Error: Redirected when going from "/login" to "/Products" via a navigation guard.
whitelist.some(item => console.log(to.path.includes(item), item))
if (whitelist.some(item => to.path.includes(item))) {
The rest of the navigation guard:
if (token) {
next({
name: "Products",
});
} else {
next();
}
} else {
if (token) {
next();
} else {
next({
name: "Login",
});
}
}
});
What am I doing wrong and how can get all urls to work?
The problem here is all routes will match to.path.includes("/").
You need to separate the routes you want to match fully, with the ones you match with contains (you might want startsWith()?).
const whitelist = [
"/",
"/register",
"/login",
];
const dynamicWhitelist = [
"/dynamic_part/",
];
if (whitelist.includes(to.path) || dynamicWhitelist.some(item => to.path.includes(item))) {
/// etc
}
The more 'Vue-router-like' way of doing this is defining a meta object in your routes and testing against those.
//routes:
const routes = [
{
path: '/login',
component: Login,
meta: { allowAnon: true }
}
...
router.beforeEach((to, from, next) => {
let token = window.sessionStorage.getItem("local_token");
if(to.meta.allowAnon) {
//etc
See the docs here for more details.
I am using nuxt-auth with google oauth2 config, here is my nuxt.config.js config:
auth: {
scopeKey: 'scope',
strategies: {
google: {
client_id: process.env.GOOGLE_KEY,
codeChallengeMethod: '',
scope: ['profile', 'email'],
responseType: 'token id_token'
}
},
redirect: {
login: '/login',
logout: '/logout',
home: '/',
callback: '/welcome'
}
},
router: {
middleware: ['auth']
},
I use this code to login
this.$auth.loginWith('google')
I want to setup a role for user (visit app database) after successful login, so I added this code to my welcome.vue (oauth2 callback page)
<script>
export default {
mounted () {
const user = this.$auth.user
user['scope'] = 'some_role_from_db'
this.$auth.setUser(user)
}
}
</script>
but this code is never called, because application is immediately redirected to the page that user has selected before visiting login page (welcome.vue html markup is shown for 1 sec).
What is the correct way to set some attributes to this.$auth.user immediately after login? Is there some easy way to set role to user after OAUTH2 authentication?
user roles must came from server and it wrong to define it from client side ,
but if that is importent you can do it like that :
this.$auth.loginWith('google').then(() => {
const user = this.$auth.user
user['scope'] = 'some_role_from_db'
this.$auth.setUser(user)
})
I've added this section to my auth object in nuxt.config.js
rewriteRedirects: false
and so my app always redirects me to home url, and on home page I can access auth object like
<script>
export default {
mounted () {
const user = this.$auth.user
user['scope'] = 'some_role_from_db'
this.$auth.setUser(user)
}
}
</script>
I have this route which loads a component and makes some validations
{
path: "/sso/:id/:atex/:entityId/:ip",
name: "SSO",
component: () => import("./views/account/sso"),
meta: {
beforeResolve(to, routeFrom, next) {
if (localStorage.getItem('userDetails') || localStorage.getItem('user')) {
next({ path: "/" + to.params.entityId })
}
next();
}
},
}
In the component and if user is valid
this.$router.replace("/" + this.$route.params.entityId);
And here's the route of /
{
path: "/:entityId?",
name: "Companies",
meta: {
authRequired: true,
beforeResolve(routeTo, routeFrom, next) {
next();
},
},
component: () => import("./views/dashboards/CompaniesGrid"),
},
And in the component I search for a table cell that contains the entityId value and click it to naرigate to /dashboard
var len = document.querySelectorAll('td').length;
for (var i=0; i < len; i++){
if ( document.querySelectorAll('td')[i].innerText == (this.$route.params.entityId).toUpperCase()){
document.querySelectorAll('td')[i].setAttribute('id', this.$route.params.entityId);
document.getElementById(this.$route.params.entityId).click();
}
}
The URL changes successfully but it doesn't really navigate. The component of dashboard isn't loaded and when I click it manually I get
Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/dashboard".
How to solve this issue and why did it happen?
In my application User wants the ability to create a role from the interface, and assign the pages to the role. Which Means both roles and routes are dynamic.
Here in the example the routes to the roles are defined in the client. Where we have to assume that the user must be in the certain roles to be allowed to access that page. But I don't know which role needs to be assigned to that pages?
Currently what I know is that we can check the whether the user is authenticated or not before accessing the page, but I am obstructing in the logic to check whether the pages are not accessible to the user with the particular roles.
As i know that i can validate the routes logic using
router.beforeEach((to, from, next) => {
//how to validate
})
Currently, my pages look like below
items: [
{
name: 'Dashboard',
url: '/dashboard',
icon: 'icon-speedometer'
},
{
name: 'Base',
url: '/base',
icon: 'icon-puzzle',
children: [
{
name: 'Cards',
url: '/base/cards',
icon: 'icon-puzzle'
},
{
name: 'Forms',
url: '/base/forms',
icon: 'icon-puzzle'
}
]
}
]
I also have other information on the client side.
DisplayPicture
FullName
Role
RoleHierarchy
RoleId
UserId
Can you guide me to the logic on how to verify whether the pages are accessible to the roles or not?
This is the code I am using to check whether the page is accessible to current user or not.
router.beforeEach((to, from, next) => {
// Permission based routing
if (to.matched.some(record => record.meta.conditionalRoute)) {
if (to.name === 'Administration') {
if (hasRole('Admin')) {
next()
}
}
next(false)
} else {
next()
}
})
In above example if name of the to.name is "Administration" then check if current user's role is "Admin" or redirect him back to previous page.
You also need to add meta: {conditionalRoute: true} to your routes where you need to apply conditional routing.
I'm having a really hard time to figure out how to load a particular route when the activate event is fired. I'm creating an Electron application using the Electron-Vue framework and I've these following routes:
export default [
{
path: '/',
name: 'login-page',
component: require('components/LoginPageView')
},
{
path: '/tracker',
name: 'tracker-page',
component: require('components/TrackerPageView')
},
{
path: '*',
redirect: '/'
}
]
Now, I'd like to load the /tracker route once the app.on('activate') is fired on the following:
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
The main reason behind this is I'm creating a two window Electron application. The first window would be the login and the second window would be user profiles. When the user already logged in and closed the app using the system close button, the app stays in the Dock bar and when the app is clicked, the Electron activate event is fired and the login screen shows again. Since the user is already logged in, I don't want the user to show the login window again. Any suggestion would be must appreciated.
I was finally able to achieve this by using the Vue-Router Per-Route Guard beforeEnter method. Here's my draft:
let auth = true
export default [
{
path: '/',
name: 'login-page',
component: require('components/LoginPageView'),
meta: {
auth: false
},
beforeEnter: (to, from, next) => {
if (auth) {
next('/tracker')
} else {
next()
}
}
},
{
path: '/tracker',
name: 'tracker-page',
component: require('components/TrackerPageView'),
meta: {
auth: true
}
},
{
path: '*',
redirect: '/'
}
]
Any feedbacks are most welcome to improve this even better :)