forked from prepguides/prepguides.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-auth.js
More file actions
660 lines (558 loc) · 23.1 KB
/
github-auth.js
File metadata and controls
660 lines (558 loc) · 23.1 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/**
* GitHub Authentication and Content Submission System
* Handles OAuth login and automated PR creation for content submission
*/
class GitHubAuth {
constructor() {
console.log('GitHubAuth constructor called');
// Get configuration from window object
this.clientId = window.GITHUB_CONFIG?.clientId || null;
this.redirectUri = this.getRedirectUri();
this.scope = 'repo,user:email';
this.accessToken = localStorage.getItem('github_access_token');
this.user = JSON.parse(localStorage.getItem('github_user') || 'null');
this.isConfigured = window.GITHUB_CONFIG?.isConfigured || false;
console.log('GitHubAuth initialized:', {
clientId: this.clientId,
isConfigured: this.isConfigured,
accessToken: !!this.accessToken,
user: !!this.user
});
// Check if we're returning from OAuth
this.checkOAuthReturn();
// Dispatch event immediately since we have the configuration
console.log('Dispatching githubAuthReady event');
window.dispatchEvent(new CustomEvent('githubAuthReady', {
detail: { isConfigured: this.isConfigured, clientId: this.clientId }
}));
}
/**
* Check if we're returning from OAuth flow
*/
checkOAuthReturn() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
const error = urlParams.get('error');
console.log('Checking OAuth return:', { code, state, error, oauthInProgress: localStorage.getItem('oauth_in_progress') });
// Check if we have an authorization code (regardless of oauth_in_progress flag)
if (code) {
console.log('Found authorization code, processing...');
this.processOAuthCode(code, state);
} else if (error) {
// OAuth error
console.log('OAuth error:', error);
alert('Authentication failed: ' + error);
localStorage.removeItem('oauth_in_progress');
} else if (localStorage.getItem('oauth_in_progress') === 'true') {
// No code, might be a fresh page load
console.log('No code found, clearing oauth_in_progress flag');
localStorage.removeItem('oauth_in_progress');
}
}
/**
* Process OAuth authorization code
*/
async processOAuthCode(code, state) {
try {
console.log('Processing OAuth code:', code);
// Process the OAuth callback
const response = await fetch('/api/auth/github', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
code: code,
state: state
})
});
console.log('OAuth response status:', response.status);
if (!response.ok) {
const errorData = await response.json();
console.error('OAuth error response:', errorData);
throw new Error(errorData.message || 'Authentication failed');
}
const tokenData = await response.json();
console.log('OAuth token received:', !!tokenData.access_token);
// Store the access token
this.accessToken = tokenData.access_token;
localStorage.setItem('github_access_token', this.accessToken);
// Get user info
const userResponse = await fetch('https://api.github.com/user', {
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (userResponse.ok) {
this.user = await userResponse.json();
localStorage.setItem('github_user', JSON.stringify(this.user));
console.log('User info received:', this.user.login);
}
// Clear OAuth in progress flag
localStorage.removeItem('oauth_in_progress');
// Clean up URL
window.history.replaceState({}, document.title, window.location.pathname);
console.log('OAuth processing complete, reloading page...');
// Force a page reload to ensure UI updates
window.location.reload();
} catch (error) {
console.error('OAuth processing error:', error);
alert('Authentication failed: ' + error.message);
localStorage.removeItem('oauth_in_progress');
}
}
/**
* Get the appropriate redirect URI based on the current environment
*/
getRedirectUri() {
const currentOrigin = window.location.origin;
// For production domain
if (currentOrigin === 'https://prepguides.dev') {
return 'https://prepguides.dev/auth/callback';
}
// For any Vercel preview deployment (includes PR previews)
if (currentOrigin.includes('.vercel.app')) {
return currentOrigin + '/auth/callback';
}
// For local development
if (currentOrigin.includes('localhost') || currentOrigin.includes('127.0.0.1')) {
return currentOrigin + '/auth/callback';
}
// Fallback to current origin
return currentOrigin + '/auth/callback';
}
/**
* Check if GitHub OAuth is properly configured
*/
async checkConfiguration() {
// Use the client ID from window configuration if available
if (window.GITHUB_CONFIG?.clientId && window.GITHUB_CONFIG?.isConfigured) {
this.clientId = window.GITHUB_CONFIG.clientId;
this.isConfigured = true;
return;
}
// Try to get the actual client ID from the config endpoint
try {
const configResponse = await fetch('/api/config');
if (configResponse.ok) {
const config = await configResponse.json();
if (config.client_id) {
this.clientId = config.client_id;
this.isConfigured = true;
} else {
this.isConfigured = false;
}
return;
}
} catch (error) {
console.log('Config endpoint not available, using fallback');
}
// Fallback: try the auth endpoint
try {
const response = await fetch('/api/auth/github', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: 'test' })
});
// If we get a 503, it means OAuth is not configured
this.isConfigured = response.status !== 503;
} catch (error) {
console.log('Auth endpoint not available, using fallback configuration');
// For now, assume configured since env vars are set in Vercel
this.isConfigured = true;
}
}
/**
* Initiate GitHub OAuth flow using popup
*/
login() {
if (!this.isConfigured) {
alert('GitHub OAuth is not configured. Please contact the administrator to set up GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET environment variables.');
return;
}
// For now, let's use a simple approach - redirect to GitHub and handle the callback manually
const authUrl = `https://github.com/login/oauth/authorize?` +
`client_id=${this.clientId}&` +
`scope=${this.scope}&` +
`state=${this.generateState()}`;
// Store that we're in the middle of OAuth
localStorage.setItem('oauth_in_progress', 'true');
window.location.href = authUrl;
}
/**
* Get the callback URI for OAuth (handles preview deployment issue)
*/
getCallbackUri() {
const currentOrigin = window.location.origin;
// For production, use the current origin
if (currentOrigin === 'https://prepguides-dev.vercel.app') {
return currentOrigin + '/auth/callback';
}
// For preview deployments, use production callback URL
// This works because the callback page can handle the redirect
return 'https://prepguides-dev.vercel.app/auth/callback';
}
/**
* Handle OAuth callback
*/
async handleCallback() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
if (!code) {
console.error('No authorization code received');
return false;
}
try {
const tokenResponse = await this.exchangeCodeForToken(code);
this.accessToken = tokenResponse.access_token;
localStorage.setItem('github_access_token', this.accessToken);
const userResponse = await this.getUserInfo();
this.user = userResponse;
localStorage.setItem('github_user', JSON.stringify(this.user));
// Clean up URL
window.history.replaceState({}, document.title, window.location.pathname);
return true;
} catch (error) {
console.error('Authentication failed:', error);
return false;
}
}
/**
* Exchange authorization code for access token
*/
async exchangeCodeForToken(code) {
const response = await fetch('/api/auth/github', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code })
});
if (!response.ok) {
throw new Error('Failed to exchange code for token');
}
return await response.json();
}
/**
* Get authenticated user information
*/
async getUserInfo() {
const response = await fetch('https://api.github.com/user', {
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (!response.ok) {
throw new Error('Failed to get user info');
}
return await response.json();
}
/**
* Logout user
*/
logout() {
this.accessToken = null;
this.user = null;
localStorage.removeItem('github_access_token');
localStorage.removeItem('github_user');
}
/**
* Check if user is authenticated
*/
isAuthenticated() {
return !!this.accessToken && !!this.user;
}
/**
* Generate random state for OAuth security
*/
generateState() {
return Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);
}
/**
* Create a pull request with submitted content
*/
async createPullRequest(contentData) {
if (!this.isAuthenticated()) {
throw new Error('User not authenticated');
}
const branchName = `content-submission-${Date.now()}`;
// Validate branch name (GitHub branch names must be valid ref names)
if (!/^[a-zA-Z0-9._-]+$/.test(branchName)) {
throw new Error('Invalid branch name format');
}
try {
console.log('Starting PR creation process...');
// First, ensure user has a fork of the repository
const forkRepo = await this.ensureFork();
console.log(`✅ Using fork repository: ${forkRepo.full_name}`);
// Create a new branch in fork
console.log('Creating branch:', branchName);
await this.createBranch(branchName);
console.log('Branch created successfully');
// Create/update the content file in fork
console.log('Creating content submission file');
await this.createContentFile(branchName, contentData, forkRepo);
console.log('Content file created successfully');
// Create pull request from fork to main repository
const prData = {
title: `Content Submission: ${contentData.title}`,
body: this.generatePRDescription(contentData),
head: `${this.user.login}:${branchName}`, // From user's fork
base: 'main'
};
console.log('Creating PR with data:', prData);
const response = await fetch('https://api.github.com/repos/prepguides/prepguides.dev/pulls', {
method: 'POST',
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
},
body: JSON.stringify(prData)
});
console.log('PR creation response status:', response.status);
if (!response.ok) {
const errorText = await response.text();
console.error('PR creation failed:', errorText);
// Parse the error to provide better messaging
let errorMessage = `Failed to create pull request: ${response.status}`;
try {
const errorData = JSON.parse(errorText);
if (errorData.message) {
errorMessage = errorData.message;
// Provide specific guidance for common errors
if (errorData.message.includes('Validation Failed')) {
errorMessage += '\n\nThis usually means the branch reference is invalid. Please ensure you have write access to the repository or try again.';
}
}
} catch (e) {
// If we can't parse the error, use the raw text
errorMessage = errorText;
}
throw new Error(errorMessage);
}
const result = await response.json();
console.log('PR created successfully:', result);
return result;
} catch (error) {
console.error('Failed to create pull request:', error);
throw error;
}
}
/**
* Ensure user has a fork of the repository
*/
async ensureFork() {
const forkRepoName = `${this.user.login}/prepguides.dev`;
// Check if fork already exists
const forkResponse = await fetch(`https://api.github.com/repos/${forkRepoName}`, {
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (forkResponse.ok) {
console.log(`Fork already exists: ${forkRepoName}`);
return await forkResponse.json();
}
// Create fork if it doesn't exist
console.log(`Creating fork: ${forkRepoName}`);
const createForkResponse = await fetch('https://api.github.com/repos/prepguides/prepguides.dev/forks', {
method: 'POST',
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (!createForkResponse.ok) {
const errorText = await createForkResponse.text();
console.error('Fork creation failed:', {
status: createForkResponse.status,
statusText: createForkResponse.statusText,
error: errorText
});
throw new Error(`Failed to create fork: ${createForkResponse.status} ${createForkResponse.statusText}`);
}
const forkRepo = await createForkResponse.json();
console.log(`Fork created successfully: ${forkRepo.full_name}`);
return forkRepo;
}
/**
* Create a new branch
*/
async createBranch(branchName) {
console.log(`Creating branch: ${branchName}`);
console.log(`Using access token: ${this.accessToken ? 'Present' : 'Missing'}`);
console.log(`User: ${this.user ? this.user.login : 'Unknown'}`);
console.log(`Fork-based workflow: Enabled`);
// First, ensure user has a fork of the repository
const forkRepo = await this.ensureFork();
console.log(`Using fork repository: ${forkRepo.full_name}`);
// Get the latest commit SHA from main branch of the fork
const mainBranchResponse = await fetch(`https://api.github.com/repos/${forkRepo.full_name}/git/refs/heads/main`, {
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (!mainBranchResponse.ok) {
const errorText = await mainBranchResponse.text();
console.error('Main branch fetch failed:', {
status: mainBranchResponse.status,
statusText: mainBranchResponse.statusText,
error: errorText
});
throw new Error(`Failed to get main branch reference: ${mainBranchResponse.status} ${mainBranchResponse.statusText}`);
}
const mainBranch = await mainBranchResponse.json();
const mainSha = mainBranch.object.sha;
// Create new branch in the fork
const branchResponse = await fetch(`https://api.github.com/repos/${forkRepo.full_name}/git/refs`, {
method: 'POST',
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
ref: `refs/heads/${branchName}`,
sha: mainSha
})
});
if (!branchResponse.ok) {
const errorText = await branchResponse.text();
console.error('Branch creation failed:', {
status: branchResponse.status,
statusText: branchResponse.statusText,
error: errorText
});
throw new Error(`Failed to create branch: ${branchResponse.status} ${branchResponse.statusText}`);
}
return await branchResponse.json();
}
/**
* Create content file in the repository
*/
async createContentFile(branchName, contentData, forkRepo) {
// Debug: Log content data to identify issues
console.log('Creating content file with data:', contentData);
// Validate required fields
if (!contentData.id) {
throw new Error('Content ID is missing or undefined');
}
// Create content payload JSON file in .github/content-payloads/ folder
const contentJson = this.formatContentAsJson(contentData);
const encodedContent = btoa(unescape(encodeURIComponent(contentJson)));
// Use the correct path for content payloads
const submissionPath = `.github/content-payloads/${contentData.id}-payload.json`;
console.log('Creating payload file at:', submissionPath);
const response = await fetch(`https://api.github.com/repos/${forkRepo.full_name}/contents/${submissionPath}`, {
method: 'PUT',
headers: {
'Authorization': `token ${this.accessToken}`,
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: `Add content submission: ${contentData.title}`,
content: encodedContent,
branch: branchName
})
});
if (!response.ok) {
throw new Error('Failed to create content submission file');
}
return await response.json();
}
/**
* Generate filename for content
*/
generateFileName(contentData) {
const sanitized = contentData.title
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.substring(0, 50);
return `${sanitized}.html`;
}
/**
* Get file path based on category
*/
getFilePath(contentData) {
const category = contentData.category.toLowerCase();
return `${category}/${this.generateFileName(contentData)}`;
}
/**
* Format content as HTML
*/
formatContentAsJson(contentData) {
// Create a JSON structure that matches the payload template format
const payloadJson = {
version: "1.0.0",
type: "content-addition",
metadata: {
title: contentData.title,
description: contentData.description,
author: this.user.login,
submissionDate: new Date().toISOString().split('T')[0],
category: contentData.category,
subtopic: contentData.subtopic || 'general'
},
content: {
id: contentData.id,
title: contentData.title,
description: contentData.description,
type: contentData.type || 'guide',
status: contentData.status || 'pending',
repo: contentData.repo || '',
path: contentData.path || ''
},
validation: {
repoAccessible: true,
fileExists: true,
contentValid: true,
categoryValid: true
}
};
// Add type-specific fields to content
if (contentData.features && contentData.features.length > 0) {
payloadJson.content.features = contentData.features;
}
if (contentData.jsFile) {
payloadJson.content.jsFile = contentData.jsFile;
}
return JSON.stringify(payloadJson, null, 2);
}
/**
* Generate PR description
*/
generatePRDescription(contentData) {
return `## Content Submission
**Title:** ${contentData.title}
**Category:** ${contentData.category}
**Submitted by:** @${this.user.login}
### Description
${contentData.description}
### Content Preview
${(contentData.content || contentData.description || '').substring(0, 200)}${(contentData.content || contentData.description || '').length > 200 ? '...' : ''}
### Review Checklist
- [ ] Content is technically accurate
- [ ] Formatting follows site standards
- [ ] No sensitive information included
- [ ] Appropriate category placement
### Notes
This content was submitted via the PrepGuides.dev content submission form.`;
}
}
// Initialize GitHub Auth when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
console.log('DOMContentLoaded - initializing GitHub auth');
window.githubAuth = new GitHubAuth();
});