auth.global.ts
1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { FORBIDDEN_PATH, LOGIN_PATH, canAccessPageByRoles, isPublicPath, normalizePagePath } from '~/utils/permission'
import { resolvePostLoginPath } from '~/utils/post-login'
function withRedirect(path: string) {
return `${LOGIN_PATH}?redirect=${encodeURIComponent(path)}`
}
function withForbiddenRedirect(path: string) {
return `${FORBIDDEN_PATH}?from=${encodeURIComponent(path)}`
}
export default defineNuxtRouteMiddleware(async (to) => {
const { token, user, fetchCurrentUser } = useAuth()
const normalizedPath = normalizePagePath(to.path)
const isLoginPage = normalizedPath === LOGIN_PATH
if (isLoginPage) {
if (!token.value) {
return
}
if (!user.value) {
await fetchCurrentUser()
}
if (token.value) {
const roles = Array.isArray(user.value?.roles) ? user.value.roles : []
return navigateTo(resolvePostLoginPath(to.query.redirect, roles))
}
return
}
if (!token.value) {
return navigateTo(withRedirect(to.fullPath))
}
if (!user.value) {
const currentUser = await fetchCurrentUser()
if (!currentUser) {
return navigateTo(withRedirect(to.fullPath))
}
}
if (isPublicPath(normalizedPath)) {
return
}
const roles = Array.isArray(user.value?.roles) ? user.value.roles : []
if (!canAccessPageByRoles(roles, normalizedPath)) {
return navigateTo(withForbiddenRedirect(to.fullPath))
}
})