All files / src/guards authorizationGuard.js

100% Statements 25/25
100% Branches 11/11
100% Functions 5/5
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      2x 2x 2x   2x 2x       21x       20x 2x 2x         14x 1x 1x     13x   13x 5x 5x     8x   8x 9x   8x 3x     3x 3x     5x    
import { ROUTE_PERMISSIONS } from '../constants/roles';
import { AUTH_FQ } from '../store/types';
 
let storeInstance = null;
let authReadyPromise = null;
let resolveAuthReady = null;
 
authReadyPromise = new Promise((resolve) => {
  resolveAuthReady = resolve;
});
 
export function setStoreForAuthorizationGuard(store) {
  storeInstance = store;
}
 
export function markAuthReady() {
  if (resolveAuthReady) {
    resolveAuthReady();
    resolveAuthReady = null;
  }
}
 
export async function authorizationGuard(to, from, next) {
  if (typeof window === 'undefined') {
    next();
    return;
  }
 
  const requiredRoles = to.meta?.roles || ROUTE_PERMISSIONS[to.path] || [];
 
  if (requiredRoles.length === 0) {
    next();
    return;
  }
 
  await authReadyPromise;
 
  const hasRole = storeInstance.getters[AUTH_FQ.getters.hasRole];
  const hasPermission = requiredRoles.some((role) => hasRole(role));
 
  if (!hasPermission) {
    const errorMessage = encodeURIComponent(
      'You do not have permission to access this page',
    );
    next(`/error?type=unauthorized&message=${errorMessage}`);
    return;
  }
 
  next();
}