Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,7 +1,7 @@
import { Permission, Role, RolePermission, UserRole } from "@hivegrid/db/prisma-browser";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { db } from "../../db.server";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { cachePermissionNames, getCachedPermissionNames, invalidateUserPermissionCache, invalidateUserPermissionCacheScopes } from "./permission-cache.server";
export type UserRoleWithPermission = UserRole & {
role: Role & { permissions: (RolePermission & { permission: Permission })[] };
@@ -21,8 +21,8 @@ function getUserRoleAssignmentKey(assignment: UserRoleAssignment): string {
return `${assignment.userId}:${assignment.roleId}:${normalizeTenantId(assignment.tenantId)}`;
}
function clearUserRoleCache(userId: string, tenantId: string | null): void {
clearCacheKey(`userRoles:${userId}:${tenantId}`);
async function clearUserRoleCache(userId: string, tenantId: string | null): Promise<void> {
await invalidateUserPermissionCache(userId, tenantId);
}
function isUniqueConstraintError(error: unknown): boolean {
@@ -57,6 +57,7 @@ export async function getUserRoleInAdmin(userId: string, roleName: string) {
userId,
role: {
name: roleName,
type: "admin",
},
tenantId: null,
},
@@ -89,33 +90,42 @@ export async function getUserRoles(userId: string, tenantId?: string | null): Pr
}
export async function getPermissionsByUser(userId: string, tenantId: string | null): Promise<string[]> {
const userRoles = await cachified({
key: `userRoles:${userId}:${tenantId}`,
ttl: 1000 * 60 * 60 * 24,
getFreshValue: () =>
db.userRole.findMany({
where: { userId, tenantId },
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
}),
});
const roles: string[] = [];
const names: string[] = [];
userRoles.forEach((userRoles) => {
if (!roles.includes(userRoles.role.name)) {
roles.push(userRoles.role.name);
}
userRoles.role.permissions.forEach((permission) => {
if (!names.includes(permission.permission.name)) {
names.push(permission.permission.name);
}
const cached = await getCachedPermissionNames(userId, tenantId);
if (cached !== null) {
return cached;
}
const readPermissionNames = async (): Promise<string[]> => {
const userRoles = await db.userRole.findMany({
where: { userId, tenantId },
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
});
});
// console.log({
// userId,
// tenantId,
// roles,
// permissions: names,
// });
const names: string[] = [];
userRoles.forEach((userRole) => {
userRole.role.permissions.forEach((permission) => {
if (!names.includes(permission.permission.name)) {
names.push(permission.permission.name);
}
});
});
return names;
};
const names = await readPermissionNames();
const cachedSuccessfully = await cachePermissionNames(userId, tenantId, names);
if (!cachedSuccessfully) {
return names;
}
// Close the cache-aside race: a revocation can commit and publish between
// the database read and cache write. Re-read after populating; a later
// revocation necessarily publishes after our write and purges it normally.
const confirmedNames = await readPermissionNames();
if (confirmedNames.length !== names.length || confirmedNames.some((name) => !names.includes(name))) {
await invalidateUserPermissionCache(userId, tenantId);
await cachePermissionNames(userId, tenantId, confirmedNames);
return confirmedNames;
}
return names;
}
@@ -235,7 +245,7 @@ export async function ensureTenantUserAppRoles({
missingRoles.map((role) => ({ id: role.id, tenantId }))
);
} else {
clearCacheKey(`userRoles:${userId}:${tenantId}`);
await clearUserRoleCache(userId, tenantId);
}
return { created: missingRoles.length, roleCount: roles.length };
@@ -254,7 +264,7 @@ export async function createUserRole(userId: string, roleId: string, tenantId: s
tenantId,
},
});
clearCacheKey(`userRoles:${userId}:${tenantId}`);
await clearUserRoleCache(userId, tenantId);
return item;
} catch (error) {
if (!isUniqueConstraintError(error)) {
@@ -272,18 +282,44 @@ export async function createUserRole(userId: string, roleId: string, tenantId: s
* Grants an admin-scoped RBAC role (e.g. "SuperAdmin") to a user by role name,
* idempotently. Used by the Admin-SSO callback to wire the JIT-provisioned
* `super_admin` identity to its concrete permission set. `createUserRole`
* invalidates the `userRoles:<userId>:null` cache, so the granted permissions
* are visible on the very next request — independent of the cache TTL.
* publishes through the shared permission cache, so every replica observes
* the grant or revocation on the next request.
*/
export async function ensureAdminUserRoleByName(userId: string, roleName: string): Promise<void> {
await reconcileAdminUserRoleByName(userId, roleName, true);
}
export type AdminRoleReconciliationResult = "granted" | "revoked" | "unchanged";
export async function reconcileAdminUserRoleByName(userId: string, roleName: string, shouldHaveRole: boolean): Promise<AdminRoleReconciliationResult> {
const role = await db.role.findFirst({
where: { name: roleName, type: "admin" },
select: { id: true },
});
if (!role) {
return;
await clearUserRoleCache(userId, null);
if (shouldHaveRole) {
throw new Error(`Required admin role is not configured: ${roleName}`);
}
return "unchanged";
}
await createUserRole(userId, role.id, null);
if (shouldHaveRole) {
const existing = await getUserRole(userId, role.id, null);
if (existing) {
await clearUserRoleCache(userId, null);
return "unchanged";
}
await createUserRole(userId, role.id, null);
await clearUserRoleCache(userId, null);
return "granted";
}
const revoked = await db.userRole.deleteMany({
where: { userId, roleId: role.id, tenantId: null },
});
await clearUserRoleCache(userId, null);
return revoked.count > 0 ? "revoked" : "unchanged";
}
export async function createUserRoles(userId: string, roles: { id: string; tenantId: string | null }[]) {
@@ -336,29 +372,28 @@ export async function createUserRoleAssignments(assignments: UserRoleAssignment[
})
: { count: 0 };
cacheScopes.forEach((scope) => {
clearUserRoleCache(scope.userId, scope.tenantId);
});
await invalidateUserPermissionCacheScopes(cacheScopes.map((scope) => ({ userId: scope.userId, tenantId: scope.tenantId })));
return result;
}
export async function deleteUserRole(userId: string, roleId: string, tenantId: string | null = null) {
return await db.userRole
.deleteMany({
where: {
userId,
roleId,
tenantId,
},
})
.then((item) => {
clearCacheKey(`userRoles:${userId}:${tenantId}`);
return item;
});
const item = await db.userRole.deleteMany({
where: {
userId,
roleId,
tenantId,
},
});
await clearUserRoleCache(userId, tenantId);
return item;
}
export async function deleteAllUserRoles(userId: string, type: string) {
return await db.userRole.deleteMany({
const assignments = await db.userRole.findMany({
where: { userId, role: { type } },
select: { tenantId: true },
});
const result = await db.userRole.deleteMany({
where: {
userId,
role: {
@@ -366,4 +401,6 @@ export async function deleteAllUserRoles(userId: string, type: string) {
},
},
});
await invalidateUserPermissionCacheScopes(assignments.map((assignment) => ({ userId, tenantId: assignment.tenantId })));
return result;
}