-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathgithub.ts
195 lines (166 loc) · 6.28 KB
/
github.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import core, {
buildSocialIdString,
DOMAIN_MODEL_TX,
systemAccountUuid,
TxProcessor,
type BackupClient,
type Client,
type Doc,
type Ref,
type TxCUD,
type WorkspaceUuid
} from '@hcengineering/core'
import { getAccountsFromTxes, getSocialKeyByOldEmail } from '@hcengineering/model-core'
import { createClient, getAccountClient, getTransactorEndpoint } from '@hcengineering/server-client'
import { generateToken } from '@hcengineering/server-token'
import type { Db } from 'mongodb'
/**
* @public
*/
export interface GithubIntegrationRecord {
installationId: number
workspace: string
accountId: string // Ref<Account>
}
/**
* @public
*/
export interface GithubUserRecord {
_id: string // login
code?: string | null
token?: string
expiresIn?: number | null // seconds
refreshToken?: string | null
refreshTokenExpiresIn?: number | null
authorized?: boolean
state?: string
scope?: string
error?: string | null
accounts: Record<string, string /* Ref<Account> */>
}
export async function performGithubAccountMigrations (db: Db, region: string | null): Promise<void> {
const token = generateToken(systemAccountUuid, '' as WorkspaceUuid, { service: 'admin', admin: 'true' })
const githubToken = generateToken(systemAccountUuid, '' as WorkspaceUuid, { service: 'github' })
const accountClient = getAccountClient(token)
const githubAccountClient = getAccountClient(githubToken)
const usersCollection = db.collection<GithubUserRecord>('users')
const integrationCollection = db.collection<GithubIntegrationRecord>('installations')
const integrations = await integrationCollection.find({}).toArray()
// Check and apply migrations
// We need to update all workspace information accordingly
const allWorkpaces = await accountClient.listWorkspaces(region)
const byId = new Map(allWorkpaces.map((it) => [it.uuid, it]))
const oldNewIds = new Map(allWorkpaces.map((it) => [it.dataId ?? it.uuid, it]))
const allAuthorizations = await usersCollection.find({}).toArray()
const wsToAuth = new Map<WorkspaceUuid, GithubUserRecord[]>()
for (const it of allAuthorizations) {
for (const ws of Object.keys(it.accounts)) {
const wsId = oldNewIds.get(ws as WorkspaceUuid) ?? byId.get(ws as WorkspaceUuid)
if (wsId !== undefined) {
wsToAuth.set(wsId.uuid, (wsToAuth.get(wsId.uuid) ?? []).concat(it))
}
}
}
const processed = new Set<string>()
const replaces = new Map<string, WorkspaceUuid>()
for (const it of integrations) {
const ws = oldNewIds.get(it.workspace as any) ?? byId.get(it.workspace as any)
if (ws != null) {
// Need to connect to workspace to get account mapping
it.workspace = ws.uuid
replaces.set(it.workspace, ws.uuid)
const wsToken = generateToken(systemAccountUuid, ws.uuid, { service: 'github', mode: 'backup' })
const endpoint = await getTransactorEndpoint(wsToken, 'external')
const client = (await createClient(endpoint, wsToken)) as BackupClient & Client
const systemAccounts = [core.account.System, core.account.ConfigUser]
const accountsTxes: TxCUD<Doc>[] = []
let idx: number | undefined
while (true) {
const info = await client.loadChunk(DOMAIN_MODEL_TX, idx)
idx = info.idx
const ids = Array.from(info.docs.map((it) => it.id as Ref<Doc>))
const docs = (await client.loadDocs(DOMAIN_MODEL_TX, ids)).filter((it) =>
TxProcessor.isExtendsCUD(it._class)
) as TxCUD<Doc>[]
accountsTxes.push(...docs)
if (info.finished && idx !== undefined) {
await client.closeChunk(info.idx)
break
}
}
await client.close()
// await client.loadChunk(DOMAIN_MODEL_TX, {
// objectClass: { $in: ['core:class:Account', 'contact:class:PersonAccount'] as Ref<Class<Doc>>[] }
// })
const accounts: (Doc & { email?: string })[] = getAccountsFromTxes(accountsTxes)
const socialKeyByAccount: Record<string, string> = {}
for (const account of accounts) {
if (account.email === undefined) {
continue
}
if (systemAccounts.includes(account._id as any)) {
;(socialKeyByAccount as any)[account._id] = account._id
} else {
socialKeyByAccount[account._id] = buildSocialIdString(getSocialKeyByOldEmail(account.email)) as any
}
}
const sid = socialKeyByAccount[it.accountId]
const person = sid !== undefined ? await accountClient.findSocialIdBySocialKey(sid) : undefined
if (person !== undefined) {
// Check/create integeration in account
const existing = await githubAccountClient.getIntegration({
kind: 'github',
workspaceUuid: ws?.uuid,
socialId: person
})
if (existing == null) {
await githubAccountClient.createIntegration({
kind: 'github',
workspaceUuid: ws?.uuid,
socialId: person,
data: {
installationId: it.installationId
}
})
}
}
const users = wsToAuth.get(ws.uuid)
for (const u of users ?? []) {
if (processed.has(u._id)) {
continue
}
processed.add(u._id)
const sid = socialKeyByAccount[u.accounts[ws.dataId ?? ws.uuid]]
if (sid !== undefined) {
const person = await accountClient.findSocialIdBySocialKey(sid)
if (person !== undefined) {
const { _id, accounts, ...data } = u
const existing = await githubAccountClient.getIntegration({
kind: 'github-user',
workspaceUuid: null,
socialId: person
})
if (existing == null) {
await githubAccountClient.createIntegration({
kind: 'github-user',
workspaceUuid: null,
socialId: person,
data: {
login: u._id
}
})
// Check/create integeration in account
await githubAccountClient.addIntegrationSecret({
kind: 'github-user',
workspaceUuid: null,
socialId: person,
key: u._id, // github login
secret: JSON.stringify(data)
})
}
}
}
}
}
}
}