feat(Roles): Added Role Functionality

main
Flycro 2023-11-11 16:32:21 +01:00
parent d9955a64d4
commit 02a6bb6025
3 changed files with 39 additions and 4 deletions

View File

@ -5,10 +5,15 @@ export interface User {
email_verified_at: string | null
password?: string
remember_token?: string | null
roles: Role[]
created_at: string | null
updated_at: string | null
}
export interface Role {
name: string
}
export interface LoginCredentials {
email: string
password: string
@ -50,7 +55,9 @@ export function useAuth<T = User>() {
}
async function login(credentials: LoginCredentials) {
if (isLoggedIn.value) { return }
if (isLoggedIn.value) {
return
}
await $larafetch('/login', { method: 'post', body: credentials })
await refresh()
@ -71,7 +78,9 @@ export function useAuth<T = User>() {
}
async function logout() {
if (!isLoggedIn.value) { return }
if (!isLoggedIn.value) {
return
}
await $larafetch('/logout', { method: 'post' })
user.value = null
@ -114,8 +123,12 @@ export async function fetchCurrentUser<T = User>() {
return await $larafetch<T>('/api/user')
}
catch (error: any) {
if ([401, 419].includes(error?.response?.status)) { return null }
if (error?.response?.status === undefined) { return null }
if ([401, 419].includes(error?.response?.status)) {
return null
}
if (error?.response?.status === undefined) {
return null
}
throw error
}
}

11
composables/useRoles.ts Normal file
View File

@ -0,0 +1,11 @@
export function useRoles() {
const user = useUser()
function hasRole(roleName: string) {
return user.value?.roles?.some(role => role.name === roleName) ?? false
}
return {
hasRole,
}
}

11
middleware/admin.ts Normal file
View File

@ -0,0 +1,11 @@
export default defineNuxtRouteMiddleware(async () => {
const { hasRole } = useRoles()
const requiredRole = 'super-admin1' // Define the role required for this route
if (!hasRole(requiredRole)) {
return abortNavigation({
message: 'You are not authorized to access this page',
statusCode: 403,
})
}
})