main
ts 83 lines 2.69 KB
Raw
1 import type { RouteLocationNormalized } from "vue-router"
2 import type { RouteMetaAuth } from "@/types/auth"
3 import { decodeJwt } from "jose"
4 import _castArray from "lodash/castArray"
5 import _toNumber from "lodash/toNumber"
6 import { useAuthStore } from "@/stores/auth"
7 import { AuthUserRole } from "@/types/auth"
8
9 /**
10 * Checks if the debounce time has elapsed since the last check
11 * @param lastCheck - Date of the last check or null if never performed
12 * @returns true if the debounce time has expired or if there was no previous check
13 */
14 export function isDebounceTimeOver(lastCheck: Date | null) {
15 const debounceTime = useAuthStore().tokenDebounceTime
16 return !lastCheck || lastCheck.getTime() + _toNumber(debounceTime) * 1000 < Date.now()
17 }
18
19 /**
20 * Checks if a JWT token is about to expire within a specified time threshold
21 * @param token - JWT token to verify
22 * @param threshold - Time threshold in seconds before expiration
23 * @returns true if the token is expiring or already expired, false on decoding error
24 */
25 export function isJwtExpiring(token: string, threshold: number): boolean {
26 try {
27 const { exp } = decodeJwt(token) || {}
28 return exp ? Date.now() / 1000 > exp - threshold : true
29 } catch {
30 return false
31 }
32 }
33
34 /**
35 * Verifies user authentication and permissions for a given route
36 * Handles logout, checks if the user is authenticated and has the required roles
37 * @param route - Vue Router route to verify
38 * @returns The redirect path if necessary, otherwise undefined
39 */
40 export function authCheck(route: RouteLocationNormalized) {
41 const { checkAuth, authRedirect, auth, roles }: RouteMetaAuth = route.meta
42 const authStore = useAuthStore()
43
44 // Logout handling
45 if (route?.redirectedFrom?.name === "Logout") authStore.setLogout()
46
47 if (authStore.isLogged && !authStore.userRole) authStore.setLogout()
48
49 // Auth check: if not logged or role not granted
50 const loginPath = `/login${window.location.search}`
51
52 if (auth && !authStore.isLogged) {
53 return loginPath
54 }
55
56 if (auth && roles && !authStore.isRoleGranted(roles)) {
57 return loginPath
58 }
59
60 if (checkAuth && authStore.isLogged) {
61 return roles && !authStore.isRoleGranted(roles) ? route.path : authRedirect || "/"
62 }
63 }
64
65 /**
66 * Converts a JWT role to an application user role
67 * @param scope - Role name or array of role names from the JWT token
68 * @returns The corresponding user role (Admin, Analyst or Unknown)
69 */
70 export function jwtRoleToUserRole(scope: string | string[]): AuthUserRole | string | null {
71 const role = _castArray(scope)[0]?.toLowerCase()
72
73 switch (role) {
74 case "admin":
75 return AuthUserRole.Admin
76 case "superuser":
77 return AuthUserRole.Superuser
78 case "analyst":
79 return AuthUserRole.Analyst
80 default:
81 return role || null
82 }
83 }