-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathpermissionUtils.ts
More file actions
69 lines (60 loc) · 2.39 KB
/
permissionUtils.ts
File metadata and controls
69 lines (60 loc) · 2.39 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"use server";
import { prisma } from "@/prisma";
import { CachedPermittedExternalAccounts, cachedPermittedExternalAccountsSchema, createLogger } from "@sourcebot/shared";
const logger = createLogger('permission-utils');
/**
* Rebuilds the AccountToRepoPermission join table for a given account
* based on the cached external account IDs stored in repos.
*
* This is useful when a new account is created and we want to grant
* access to repos without waiting for a full permission sync.
*
* @param accountId - The internal account ID
* @param provider - The OAuth provider (e.g., 'github', 'gitlab')
* @param providerAccountId - The external account ID from the provider
*/
export async function rebuildPermissionsFromCache(
accountId: string,
provider: string,
providerAccountId: string
): Promise<void> {
logger.info(`Rebuilding permissions from cache for account ${accountId} (${provider}:${providerAccountId})`);
// Find all repos that have this external account ID in their cached permissions
const repos = await prisma.repo.findMany({
where: {
cachedPermittedExternalAccounts: {
not: null,
},
},
select: {
id: true,
cachedPermittedExternalAccounts: true,
},
});
// Filter repos that include this specific external account ID for this provider
const reposWithAccess = repos.filter(repo => {
try {
const cached = cachedPermittedExternalAccountsSchema.parse(
repo.cachedPermittedExternalAccounts
);
const providerAccountIds = cached[provider as keyof CachedPermittedExternalAccounts];
return providerAccountIds?.includes(providerAccountId) ?? false;
} catch (error) {
logger.warn(`Failed to parse cachedPermittedExternalAccounts for repo ${repo.id}:`, error);
return false;
}
});
if (reposWithAccess.length === 0) {
logger.info(`No repos found with cached permissions for account ${accountId}`);
return;
}
// Create AccountToRepoPermission entries
await prisma.accountToRepoPermission.createMany({
data: reposWithAccess.map(repo => ({
accountId,
repoId: repo.id,
})),
skipDuplicates: true,
});
logger.info(`Rebuilt permissions for ${reposWithAccess.length} repos for account ${accountId}`);
}