2021-05-04 09:59:42 +02:00
|
|
|
import { FC } from 'react';
|
2021-04-20 19:13:31 +02:00
|
|
|
|
2021-10-19 13:08:25 +02:00
|
|
|
import AccessContext from '../../../contexts/AccessContext';
|
2022-01-14 15:50:02 +01:00
|
|
|
import useUser from '../../../hooks/api/getters/useUser/useUser';
|
2021-05-04 09:59:42 +02:00
|
|
|
import { ADMIN } from './permissions';
|
2021-04-20 19:13:31 +02:00
|
|
|
|
|
|
|
// TODO: Type up redux store
|
|
|
|
interface IAccessProvider {
|
|
|
|
store: any;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface IPermission {
|
2021-05-04 09:59:42 +02:00
|
|
|
permission: string;
|
2022-01-14 15:50:02 +01:00
|
|
|
project?: string | null;
|
|
|
|
environment: string | null;
|
2021-04-20 19:13:31 +02:00
|
|
|
}
|
|
|
|
|
2021-05-04 09:59:42 +02:00
|
|
|
const AccessProvider: FC<IAccessProvider> = ({ store, children }) => {
|
2022-01-14 15:50:02 +01:00
|
|
|
const { permissions } = useUser();
|
2021-07-16 15:41:54 +02:00
|
|
|
const isAdminHigherOrder = () => {
|
|
|
|
let called = false;
|
|
|
|
let result = false;
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
if (called) return result;
|
|
|
|
const permissions = store.getState().user.get('permissions') || [];
|
|
|
|
result = permissions.some(
|
|
|
|
(p: IPermission) => p.permission === ADMIN
|
|
|
|
);
|
|
|
|
|
|
|
|
if (permissions.length > 0) {
|
|
|
|
called = true;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
const isAdmin = isAdminHigherOrder();
|
|
|
|
|
2022-01-14 15:50:02 +01:00
|
|
|
const hasAccess = (
|
|
|
|
permission: string,
|
|
|
|
project: string,
|
|
|
|
environment?: string
|
|
|
|
) => {
|
2021-05-04 09:59:42 +02:00
|
|
|
const result = permissions.some((p: IPermission) => {
|
|
|
|
if (p.permission === ADMIN) {
|
|
|
|
return true;
|
|
|
|
}
|
2021-05-04 21:25:35 +02:00
|
|
|
|
2022-01-14 15:50:02 +01:00
|
|
|
if (
|
|
|
|
p.permission === permission &&
|
|
|
|
(p.project === project || p.project === '*') &&
|
|
|
|
(p.environment === environment || p.environment === '*')
|
|
|
|
) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (
|
|
|
|
p.permission === permission &&
|
|
|
|
(p.project === project || p.project === '*') &&
|
|
|
|
p.environment === null
|
|
|
|
) {
|
2021-05-04 09:59:42 +02:00
|
|
|
return true;
|
|
|
|
}
|
2021-05-04 21:25:35 +02:00
|
|
|
|
2022-01-14 15:50:02 +01:00
|
|
|
if (
|
|
|
|
p.permission === permission &&
|
|
|
|
p.project === undefined &&
|
|
|
|
p.environment === null
|
|
|
|
) {
|
2021-05-04 21:25:35 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2021-05-04 09:59:42 +02:00
|
|
|
return false;
|
|
|
|
});
|
|
|
|
|
|
|
|
return result;
|
|
|
|
};
|
|
|
|
|
2021-07-16 15:41:54 +02:00
|
|
|
const context = { hasAccess, isAdmin };
|
2021-05-04 09:59:42 +02:00
|
|
|
|
|
|
|
return (
|
|
|
|
<AccessContext.Provider value={context}>
|
|
|
|
{children}
|
|
|
|
</AccessContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default AccessProvider;
|