forked from Gerome-Elassaad/CodingIT
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgithub-oauth.ts
More file actions
291 lines (263 loc) · 7.87 KB
/
Copy pathgithub-oauth.ts
File metadata and controls
291 lines (263 loc) · 7.87 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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import { nanoid } from 'nanoid'
export interface GitHubOAuthConfig {
clientId: string
redirectUri: string
scopes: string[]
}
export interface GitHubRepository {
id: number
name: string
full_name: string
description: string | null
html_url: string
clone_url: string
ssh_url: string
private: boolean
fork: boolean
archived: boolean
disabled: boolean
owner: {
login: string
avatar_url: string
type: string
}
created_at: string
updated_at: string
pushed_at: string
language: string | null
stargazers_count: number
watchers_count: number
forks_count: number
open_issues_count: number
size: number
default_branch: string
topics: string[]
has_issues: boolean
has_projects: boolean
has_wiki: boolean
has_pages: boolean
has_downloads: boolean
license: {
key: string
name: string
spdx_id: string
} | null
}
export interface GitHubUserIntegration {
access_token: string
refresh_token?: string
token_type: string
scope: string
github_user_id: number
username: string
avatar_url: string
connected_at: string
last_webhook_event?: {
type: string
repository?: string
branch?: string
commits?: number
action?: string
pr_number?: number
pr_title?: string
issue_number?: number
issue_title?: string
timestamp: string
author?: string
pusher?: string
}
}
export function generateGitHubOAuthUrl(config: GitHubOAuthConfig): string {
const state = nanoid()
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
scope: config.scopes.join(' '),
state,
allow_signup: 'true',
})
if (typeof window !== 'undefined') {
sessionStorage.setItem('github_oauth_state', state)
}
return `https://github.com/login/oauth/authorize?${params.toString()}`
}
export function getGitHubScopes(): string[] {
return [
'user:email',
'repo',
'write:repo_hook',
'read:org',
]
}
export async function revokeGitHubToken(accessToken: string): Promise<boolean> {
try {
const response = await fetch('/api/auth/github/revoke', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
access_token: accessToken,
}),
})
return response.ok
} catch (error) {
console.error('Error revoking GitHub token:', error)
return false
}
}
export async function fetchGitHubRepositories(options?: {
page?: number
per_page?: number
sort?: 'created' | 'updated' | 'pushed' | 'full_name'
type?: 'all' | 'owner' | 'public' | 'private' | 'member'
}): Promise<{ repositories: GitHubRepository[]; total_count: number; has_more: boolean } | null> {
try {
// First get the current user to know whose repos to fetch
const userResponse = await fetch('/api/github/user')
if (!userResponse.ok) {
throw new Error('Failed to fetch GitHub user')
}
const userData = await userResponse.json()
// Get user's repositories
const reposResponse = await fetch(`/api/github/repos?owner=${userData.login}`)
if (!reposResponse.ok) {
throw new Error('Failed to fetch repositories')
}
const userRepos = await reposResponse.json()
// Get user's organizations and their repos if type allows
let orgRepos: any[] = []
if (!options?.type || options.type === 'all' || options.type === 'member') {
const orgsResponse = await fetch('/api/github/orgs')
if (orgsResponse.ok) {
const orgs = await orgsResponse.json()
for (const org of orgs) {
try {
const orgReposResponse = await fetch(`/api/github/repos?owner=${org.login}`)
if (orgReposResponse.ok) {
const repos = await orgReposResponse.json()
orgRepos.push(...repos)
}
} catch (error) {
console.warn(`Failed to fetch repos for org ${org.login}:`, error)
}
}
}
}
// Filter repositories based on type
let allRepos = [...userRepos, ...orgRepos]
if (options?.type === 'owner') {
allRepos = userRepos // Only user's own repos
}
// Convert to expected format
const repositories: GitHubRepository[] = allRepos.map((repo: any) => ({
id: repo.id || Math.random(),
name: repo.name,
full_name: repo.full_name,
description: repo.description,
html_url: `https://github.com/${repo.full_name}`,
clone_url: repo.clone_url,
ssh_url: `git@github.com:${repo.full_name}.git`,
private: repo.private,
fork: false,
archived: false,
disabled: false,
owner: {
login: repo.full_name.split('/')[0],
avatar_url: userData.avatar_url,
type: 'User'
},
created_at: new Date().toISOString(),
updated_at: repo.updated_at,
pushed_at: repo.updated_at,
language: repo.language,
stargazers_count: 0,
watchers_count: 0,
forks_count: 0,
open_issues_count: 0,
size: 0,
default_branch: 'main',
topics: [],
has_issues: true,
has_projects: true,
has_wiki: true,
has_pages: false,
has_downloads: true,
license: null
}))
// Apply sorting if specified
if (options?.sort) {
repositories.sort((a, b) => {
switch (options.sort) {
case 'full_name':
return a.full_name.localeCompare(b.full_name)
case 'updated':
return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
default:
return 0
}
})
}
// Apply pagination
const page = options?.page || 1
const perPage = options?.per_page || 30
const startIndex = (page - 1) * perPage
const endIndex = startIndex + perPage
const paginatedRepos = repositories.slice(startIndex, endIndex)
return {
repositories: paginatedRepos,
total_count: repositories.length,
has_more: endIndex < repositories.length
}
} catch (error) {
console.error('Error fetching GitHub repositories:', error)
return null
}
}
export function isGitHubIntegrationHealthy(integration: any): boolean {
if (!integration?.is_connected) return false
if (!integration?.connection_data?.access_token) return false
if (integration.last_sync_at) {
const lastSync = new Date(integration.last_sync_at)
const now = new Date()
const hoursSinceSync = (now.getTime() - lastSync.getTime()) / (1000 * 60 * 60)
if (hoursSinceSync > 24) {
return false
}
}
return true
}
export function formatGitHubWebhookEvent(event: any): string {
if (!event) return 'No recent activity'
switch (event.type) {
case 'push':
return `${event.commits} commit(s) pushed to ${event.branch} in ${event.repository}`
case 'pull_request':
return `Pull request #${event.pr_number} ${event.action} in ${event.repository}`
case 'issues':
return `Issue #${event.issue_number} ${event.action} in ${event.repository}`
default:
return `${event.type} event in ${event.repository || 'repository'}`
}
}
export function getGitHubEventIcon(eventType: string): string {
switch (eventType) {
case 'push':
return '📤'
case 'pull_request':
return '🔀'
case 'issues':
return '❗'
default:
return '📋'
}
}
export function validateGitHubWebhookSignature(body: string, signature: string, secret: string): boolean {
if (!signature || !secret) return false
const crypto = require('crypto')
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(body)
.digest('hex')
return signature === `sha256=${expectedSignature}`
}