Skip to content

Commit

Permalink
Update AuthContext.tsx
Browse files Browse the repository at this point in the history
  • Loading branch information
Denys Dinkevych authored Nov 18, 2024
1 parent 3390919 commit b9037ce
Showing 1 changed file with 82 additions and 35 deletions.
117 changes: 82 additions & 35 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,51 +13,98 @@ const githubOAuthConfig = {
redirectUri: `${window.location.origin}/auth/callback`,
};

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

export function AuthProvider({ children }: { children: React.ReactNode }) {
const [accessToken, setAccessToken] = useState<string | null>(() => {
return localStorage.getItem('github_access_token');
});
const [error, setError] = useState<string | null>(null);

const isAuthenticated = !!accessToken;
const [user, setUser] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);

useEffect(() => {
const handleCallback = async () => {
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
try {
const response = await fetch('/.netlify/functions/auth', {
method: 'POST',
const token = localStorage.getItem('github_access_token');
if (token) {
fetch('https://api.github.com/user', {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => response.json())
.then((userData) => {
setUser(userData);
setIsAuthenticated(true);
})
.catch((error) => {
console.error('Error fetching user data:', error);
localStorage.removeItem('github_access_token'); // Clear invalid token
});
}
}, []);

const login = () => {
const clientId = import.meta.env.VITE_GITHUB_CLIENT_ID;
const redirectUri = `${window.location.origin}/auth/callback`;
const scope = 'read:user';

window.location.href = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(
redirectUri
)}&scope=${scope}`;
};

const logout = () => {
localStorage.removeItem('github_access_token');
setUser(null);
setIsAuthenticated(false);
};

return (
<AuthContext.Provider value={{ user, isAuthenticated, login, logout }}>
{children}
</AuthContext.Provider>
);
}

useEffect(() => {
const handleCallback = async () => {
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
try {
const response = await fetch('/.netlify/functions/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});

if (!response.ok) {
throw new Error('Failed to authenticate with GitHub');
}

const data = await response.json();

if (data.access_token) {
localStorage.setItem('github_access_token', data.access_token);

// Fetch user information
const userResponse = await fetch('https://api.github.com/user', {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${data.access_token}`,
},
body: JSON.stringify({ code }),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(`Failed to authenticate with GitHub: ${errorMessage}`);
}

const data = await response.json();
if (data.access_token) {
setAccessToken(data.access_token);
localStorage.setItem('github_access_token', data.access_token);
window.history.replaceState({}, document.title, window.location.pathname);
} else if (data.error) {
setError(data.error_description || 'Authentication failed');
}
} catch (error) {
console.error('Authentication error:', error);
setError(error instanceof Error ? error.message : 'Authentication failed');
const user = await userResponse.json();
console.log('Authenticated user:', user);

// Redirect to the home screen after successful authentication
window.history.replaceState({}, document.title, '/'); // Remove `code` from the URL
} else if (data.error) {
console.error('Authentication error:', data.error_description || 'Authentication failed');
}
} catch (error) {
console.error('Authentication error:', error);
}
};
}
};

handleCallback();
}, []);
handleCallback();
}, []);

const login = () => {
const clientId = githubOAuthConfig.clientId;
Expand Down

0 comments on commit b9037ce

Please sign in to comment.