Files
SDS-CRM/public/js/core/auth-guard.js

60 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { authFetchStatus, isAuthRedirectError } from '../api.js';
import { updateNav } from './layout.js';
window.addEventListener('unhandledrejection', (ev) => {
if (isAuthRedirectError(ev.reason)) {
ev.preventDefault();
}
});
/** @param {object|null|undefined} user aus /auth/status */
export function canEditCrm(user) {
return user?.canEditCrm === true;
}
/** @param {object|null|undefined} user aus /auth/status */
export function canAdmin(user) {
return user?.canAdmin === true;
}
/**
* @param {{ needsAdmin?: boolean, activeNav?: string }} opts
* @returns {Promise<object|null>} Session-Status oder null bei Redirect
*/
export async function guard(opts = {}) {
const { needsAdmin = false, activeNav = '' } = opts;
let st;
try {
st = await authFetchStatus();
} catch {
st = { needsBootstrap: false, loggedIn: false, user: null };
}
if (st.needsBootstrap) {
if (!location.pathname.endsWith('/bootstrap.html')) {
location.href = '/bootstrap.html';
return null;
}
return st;
}
if (!st.loggedIn) {
if (!location.pathname.endsWith('/login.html')) {
location.href = '/login.html';
return null;
}
return st;
}
if (
location.pathname.endsWith('/login.html') ||
location.pathname.endsWith('/bootstrap.html')
) {
location.href = '/start.html';
return null;
}
if (needsAdmin && !canAdmin(st.user)) {
location.href = '/start.html';
return null;
}
updateNav(st, activeNav);
return st;
}