mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add one-click GitHub connect
This commit is contained in:
5 files changed
+258
-27
No files matched your search
@@ -0,0 +1,2 @@
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
@@ -0,0 +1,134 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
|
||||
interface GitHubOAuthState {
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface GitHubTokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
export function useGitHubOAuth() {
|
||||
const [state, setState] = useState<GitHubOAuthState>({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { addCredential } = useGitSettings();
|
||||
|
||||
// Check if OAuth is configured
|
||||
const isOAuthConfigured = !!(
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID &&
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
|
||||
);
|
||||
|
||||
const initiateOAuth = useCallback(() => {
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
|
||||
if (!clientId) {
|
||||
setState(prev => ({ ...prev, error: 'GitHub OAuth client ID not configured' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
localStorage.setItem('github_oauth_state', state);
|
||||
|
||||
// Redirect to GitHub OAuth
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: window.location.origin + '/',
|
||||
scope: 'repo',
|
||||
state: state,
|
||||
});
|
||||
|
||||
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
|
||||
}, []);
|
||||
|
||||
const handleCallback = useCallback(async (code: string, state: string) => {
|
||||
setState(prev => ({ ...prev, isLoading: true, error: null }));
|
||||
|
||||
try {
|
||||
// Verify state parameter
|
||||
const storedState = localStorage.getItem('github_oauth_state');
|
||||
if (!storedState || storedState !== state) {
|
||||
throw new Error('Invalid OAuth state parameter');
|
||||
}
|
||||
|
||||
// Clean up stored state
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
|
||||
|
||||
if (!clientId || !clientSecret) {
|
||||
throw new Error('GitHub OAuth credentials not configured');
|
||||
}
|
||||
|
||||
// Exchange code for access token
|
||||
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code: code,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
throw new Error(`GitHub OAuth token exchange failed: ${tokenResponse.statusText}`);
|
||||
}
|
||||
|
||||
const tokenData: GitHubTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.access_token) {
|
||||
throw new Error('No access token received from GitHub');
|
||||
}
|
||||
|
||||
// Get user info to verify the token works
|
||||
const userResponse = await fetch('https://corsproxy.io/?url=https://api.github.com/user', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${tokenData.access_token}`,
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Failed to verify GitHub token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData = await userResponse.json();
|
||||
|
||||
// Store the credentials
|
||||
addCredential('https://github.com', {
|
||||
username: userData.login || 'git',
|
||||
password: tokenData.access_token,
|
||||
});
|
||||
|
||||
setState(prev => ({ ...prev, isLoading: false }));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('GitHub OAuth error:', error);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'OAuth authentication failed'
|
||||
}));
|
||||
return false;
|
||||
}
|
||||
}, [addCredential]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
};
|
||||
}
|
||||
+86
-26
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { Check, GitBranch, ArrowLeft } from 'lucide-react';
|
||||
import { Check, GitBranch, ArrowLeft, Github } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -7,6 +7,7 @@ import { Separator } from '@/components/ui/separator';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
@@ -38,6 +39,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
|
||||
export function GitSettings() {
|
||||
const { settings, addCredential, removeCredential, updateCredential } = useGitSettings();
|
||||
const { initiateOAuth, isLoading: isOAuthLoading, error: oauthError, isOAuthConfigured } = useGitHubOAuth();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const [customOrigin, setCustomOrigin] = useState('');
|
||||
@@ -217,7 +219,7 @@ export function GitSettings() {
|
||||
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
{preset.tokenURL && (
|
||||
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground"
|
||||
@@ -227,30 +229,88 @@ export function GitSettings() {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Enter your token"
|
||||
type="password"
|
||||
className="flex-1"
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => setPresetTokens(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!presetTokens[preset.id]?.trim()}
|
||||
size="sm"
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{preset.id === 'github' ? (
|
||||
// Special rendering for GitHub - OAuth button if configured, otherwise token input
|
||||
isOAuthConfigured ? (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={initiateOAuth}
|
||||
disabled={isOAuthLoading}
|
||||
className="w-full gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Github className="h-4 w-4" />
|
||||
Connect to GitHub
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{oauthError && (
|
||||
<p className="text-sm text-destructive">
|
||||
{oauthError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Enter your token"
|
||||
type="password"
|
||||
className="flex-1"
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => setPresetTokens(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!presetTokens[preset.id]?.trim()}
|
||||
size="sm"
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
// Standard rendering for other providers
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Enter your token"
|
||||
type="password"
|
||||
className="flex-1"
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => setPresetTokens(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!presetTokens[preset.id]?.trim()}
|
||||
size="sm"
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
+27
-1
@@ -1,11 +1,13 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useAIProjectId } from '@/hooks/useAIProjectId';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
@@ -20,11 +22,14 @@ export default function Index() {
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { fs } = useFS();
|
||||
const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId();
|
||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||
const { handleCallback: handleGitHubCallback } = useGitHubOAuth();
|
||||
const { toast } = useToast();
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
@@ -36,6 +41,27 @@ export default function Index() {
|
||||
description: 'Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment.',
|
||||
});
|
||||
|
||||
// Handle GitHub OAuth callback
|
||||
useEffect(() => {
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
|
||||
if (code && state) {
|
||||
// Handle GitHub OAuth callback
|
||||
handleGitHubCallback(code, state).then((success) => {
|
||||
if (success) {
|
||||
// Clean up URL parameters
|
||||
setSearchParams({});
|
||||
// Show success toast
|
||||
toast({
|
||||
title: "GitHub Connected",
|
||||
description: "Successfully connected to GitHub. You can now push and pull from GitHub repositories.",
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [searchParams, setSearchParams, handleGitHubCallback, toast]);
|
||||
|
||||
// Restore prompt from local storage on mount
|
||||
useEffect(() => {
|
||||
if (storedPrompt) {
|
||||
|
||||
Vendored
+9
@@ -1 +1,10 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_GITHUB_OAUTH_CLIENT_ID?: string;
|
||||
readonly VITE_GITHUB_OAUTH_CLIENT_SECRET?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
Reference in new issue
Block a user