I am trying to test if the logged in user has the appropriate role to see certain items in the dashboard.
I have an array of objects. These are the items that the user may or may not see:
items: [
{ title: 'Guide', icon: '$guide', component: 'Guide', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Courses', icon: '$courses', component: 'Course', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Sections', icon: '$sections', component: 'Sections', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Units', icon: '$units', component: 'Units', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Groups', icon: '$groups', component: 'Groups', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Users', icon: '$users', component: 'Users', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'FAQ', icon: '$faq', component: 'FAG', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
]
and an admin object. This is the user and their permission roles:
cid: (...)
email: (...)
emailVerified: (...)
fullPath: (...)
id: undefined
roles: Array(2)
0: "member"
1: "pastor"
Here is my code:
const hasRole = this.items.filter(val => this.admin.roles.includes(val.roles))
return hasRole
This code no longer works because the items.roles used to only be a string but I have now made it an array of roles.
I have tried multiple combinations but am struggling to figure this out.
Use Array.some()
to test if any element in an array satisfies a condition. In this case, the condition would be if the element is found in another array.
const hasRole = this.items.filter(val =>
this.admin.roles.some(role => val.roles.includes(role))
)
return hasRole
Change to Array.every()
instead if all roles in the this.admin
object should be included to result in a positive result.