Skip to content

Commit b9037ce

Browse files
author
Denys Dinkevych
authored
Update AuthContext.tsx
1 parent 3390919 commit b9037ce

File tree

1 file changed

+82
-35
lines changed

1 file changed

+82
-35
lines changed

src/contexts/AuthContext.tsx

+82-35
Original file line numberDiff line numberDiff line change
@@ -13,51 +13,98 @@ const githubOAuthConfig = {
1313
redirectUri: `${window.location.origin}/auth/callback`,
1414
};
1515

16-
export const AuthContext = createContext<AuthContextType>({} as AuthContextType);
17-
1816
export function AuthProvider({ children }: { children: React.ReactNode }) {
19-
const [accessToken, setAccessToken] = useState<string | null>(() => {
20-
return localStorage.getItem('github_access_token');
21-
});
22-
const [error, setError] = useState<string | null>(null);
23-
24-
const isAuthenticated = !!accessToken;
17+
const [user, setUser] = useState(null);
18+
const [isAuthenticated, setIsAuthenticated] = useState(false);
2519

2620
useEffect(() => {
27-
const handleCallback = async () => {
28-
const code = new URLSearchParams(window.location.search).get('code');
29-
if (code) {
30-
try {
31-
const response = await fetch('/.netlify/functions/auth', {
32-
method: 'POST',
21+
const token = localStorage.getItem('github_access_token');
22+
if (token) {
23+
fetch('https://api.github.com/user', {
24+
headers: {
25+
Authorization: `Bearer ${token}`,
26+
},
27+
})
28+
.then((response) => response.json())
29+
.then((userData) => {
30+
setUser(userData);
31+
setIsAuthenticated(true);
32+
})
33+
.catch((error) => {
34+
console.error('Error fetching user data:', error);
35+
localStorage.removeItem('github_access_token'); // Clear invalid token
36+
});
37+
}
38+
}, []);
39+
40+
const login = () => {
41+
const clientId = import.meta.env.VITE_GITHUB_CLIENT_ID;
42+
const redirectUri = `${window.location.origin}/auth/callback`;
43+
const scope = 'read:user';
44+
45+
window.location.href = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(
46+
redirectUri
47+
)}&scope=${scope}`;
48+
};
49+
50+
const logout = () => {
51+
localStorage.removeItem('github_access_token');
52+
setUser(null);
53+
setIsAuthenticated(false);
54+
};
55+
56+
return (
57+
<AuthContext.Provider value={{ user, isAuthenticated, login, logout }}>
58+
{children}
59+
</AuthContext.Provider>
60+
);
61+
}
62+
63+
useEffect(() => {
64+
const handleCallback = async () => {
65+
const code = new URLSearchParams(window.location.search).get('code');
66+
if (code) {
67+
try {
68+
const response = await fetch('/.netlify/functions/auth', {
69+
method: 'POST',
70+
headers: {
71+
'Content-Type': 'application/json',
72+
},
73+
body: JSON.stringify({ code }),
74+
});
75+
76+
if (!response.ok) {
77+
throw new Error('Failed to authenticate with GitHub');
78+
}
79+
80+
const data = await response.json();
81+
82+
if (data.access_token) {
83+
localStorage.setItem('github_access_token', data.access_token);
84+
85+
// Fetch user information
86+
const userResponse = await fetch('https://api.github.com/user', {
3387
headers: {
34-
'Content-Type': 'application/json',
88+
Authorization: `Bearer ${data.access_token}`,
3589
},
36-
body: JSON.stringify({ code }),
3790
});
3891

39-
if (!response.ok) {
40-
const errorMessage = await response.text();
41-
throw new Error(`Failed to authenticate with GitHub: ${errorMessage}`);
42-
}
43-
44-
const data = await response.json();
45-
if (data.access_token) {
46-
setAccessToken(data.access_token);
47-
localStorage.setItem('github_access_token', data.access_token);
48-
window.history.replaceState({}, document.title, window.location.pathname);
49-
} else if (data.error) {
50-
setError(data.error_description || 'Authentication failed');
51-
}
52-
} catch (error) {
53-
console.error('Authentication error:', error);
54-
setError(error instanceof Error ? error.message : 'Authentication failed');
92+
const user = await userResponse.json();
93+
console.log('Authenticated user:', user);
94+
95+
// Redirect to the home screen after successful authentication
96+
window.history.replaceState({}, document.title, '/'); // Remove `code` from the URL
97+
} else if (data.error) {
98+
console.error('Authentication error:', data.error_description || 'Authentication failed');
5599
}
100+
} catch (error) {
101+
console.error('Authentication error:', error);
56102
}
57-
};
103+
}
104+
};
58105

59-
handleCallback();
60-
}, []);
106+
handleCallback();
107+
}, []);
61108

62109
const login = () => {
63110
const clientId = githubOAuthConfig.clientId;

0 commit comments

Comments
 (0)