Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
Denys Dinkevych authored Nov 17, 2024
1 parent 2dd9761 commit e62e73b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
52 changes: 51 additions & 1 deletion src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ interface AuthContextType {
error: string | null;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);
const githubOAuthConfig = {
clientId: import.meta.env.VITE_GITHUB_CLIENT_ID,
clientSecret: import.meta.env.VITE_GITHUB_CLIENT_SECRET,
redirectUri: import.meta.env.VITE_GITHUB_REDIRECT_URI,
};

export const AuthContext = createContext<AuthContextType>({} as AuthContextType);

export function AuthProvider({ children }: { children: React.ReactNode }) {
const [accessToken, setAccessToken] = useState<string | null>(() => {
Expand Down Expand Up @@ -71,6 +77,50 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
localStorage.removeItem('github_access_token');
};

const handleGithubSignIn = async () => {
try {
const authUrl = `https://github.com/login/oauth/authorize?client_id=${
githubOAuthConfig.clientId
}&redirect_uri=${encodeURIComponent(githubOAuthConfig.redirectUri)}`;

window.location.href = authUrl;
} catch (error) {
console.error('GitHub authentication error:', error);
// Handle error appropriately
}
};

const handleOAuthCallback = async (code: string) => {
try {
// Exchange code for access token
const response = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
client_id: githubOAuthConfig.clientId,
client_secret: githubOAuthConfig.clientSecret,
code,
}),
});

const data = await response.json();

if (data.error) {
throw new Error(data.error_description || 'Authentication failed');
}

// Store the access token securely
const { access_token } = data;
// ... handle successful authentication
} catch (error) {
console.error('Error exchanging code for token:', error);
// Handle error appropriately
}
};

return (
<AuthContext.Provider value={{ isAuthenticated, accessToken, login, logout, error }}>
{children}
Expand Down
3 changes: 2 additions & 1 deletion src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/// <reference types="vite/client" />

interface ImportMetaEnv {
readonly VITE_GITHUB_TOKEN: string
readonly VITE_GITHUB_CLIENT_ID: string
readonly VITE_GITHUB_CLIENT_SECRET: string
readonly VITE_GITHUB_REDIRECT_URI: string
}

interface ImportMeta {
Expand Down

0 comments on commit e62e73b

Please sign in to comment.