51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
export type CurrentAdminLike = {
|
|
id?: string;
|
|
email?: string;
|
|
name?: string;
|
|
role?: string;
|
|
appPermissions?: string[];
|
|
};
|
|
|
|
export function readCurrentAdmin(): CurrentAdminLike | null {
|
|
try {
|
|
const raw = window.localStorage.getItem('studio-admin');
|
|
if (!raw) return null;
|
|
const admin = JSON.parse(raw) as CurrentAdminLike;
|
|
return admin?.id || admin?.email ? admin : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function isOwnerAdmin(admin?: CurrentAdminLike | null) {
|
|
return admin?.role === 'OWNER';
|
|
}
|
|
|
|
export function getAdminAppPermissions(admin: CurrentAdminLike) {
|
|
return Array.isArray(admin.appPermissions) ? admin.appPermissions : [];
|
|
}
|
|
|
|
export function setAdminAppPermissions(admin: CurrentAdminLike, appIds: string[]) {
|
|
const current = readCurrentAdmin();
|
|
if (!current || !admin.id || current.id !== admin.id) return;
|
|
|
|
const nextAppIds = [...new Set(appIds.filter(Boolean))];
|
|
window.localStorage.setItem('studio-admin', JSON.stringify({ ...current, appPermissions: nextAppIds }));
|
|
window.dispatchEvent(new CustomEvent('studio-admin-app-permissions-change'));
|
|
}
|
|
|
|
export function grantAppPermissionToCurrentAdmin(appId: string) {
|
|
const admin = readCurrentAdmin();
|
|
if (!admin || isOwnerAdmin(admin)) return;
|
|
|
|
setAdminAppPermissions(admin, [...getAdminAppPermissions(admin), appId]);
|
|
}
|
|
|
|
export function filterAppsByCurrentAdmin<T extends { id: string }>(apps: T[]) {
|
|
const admin = readCurrentAdmin();
|
|
if (!admin || isOwnerAdmin(admin)) return apps;
|
|
|
|
const allowedAppIds = new Set(getAdminAppPermissions(admin));
|
|
return apps.filter((app) => allowedAppIds.has(app.id));
|
|
}
|