Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement GitHub Authentication necessary changes (Server has the OAuth flow using passport.js) #12

Merged
merged 1 commit into from
Apr 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Implemented github auth (this changes are related with the client app)
  • Loading branch information
foyzulkarim committed Apr 28, 2024
commit b712bea9ebaf9601e0dd6990a3ac881dd960e67b
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_URL=http://localhost:4000/api
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ web_modules/
.env.test.local
.env.production.local
.env.local
.env.development
.env.production

# parcel-bundler cache (https://parceljs.org/)
.cache
Expand Down
12 changes: 8 additions & 4 deletions src/app.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/* eslint-disable perfectionist/sort-imports */
import 'src/global.css';
/* eslint-disable import/no-unresolved */
import Router from 'src/routes/sections';

import { useScrollToTop } from 'src/hooks/use-scroll-to-top';

import Router from 'src/routes/sections';
import 'src/global.css';
import ThemeProvider from 'src/theme';
import { AuthProvider } from 'src/contexts/AuthContext';


// ----------------------------------------------------------------------

Expand All @@ -13,7 +15,9 @@ export default function App() {

return (
<ThemeProvider>
<Router />
<AuthProvider>
<Router />
</AuthProvider>
</ThemeProvider>
);
}
66 changes: 66 additions & 0 deletions src/contexts/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import PropTypes from 'prop-types';
import { useNavigate } from 'react-router-dom';
import React, { useState, useEffect, createContext } from 'react';

const AuthContext = createContext({
isAuthenticated: false,
userProfile: null,
setAuthState: () => { },
});
const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [userProfile, setUserProfile] = useState(null);
const navigate = useNavigate();
const apiUrl = import.meta.env.VITE_API_URL;


useEffect(() => {
const fetchUserProfile = async () => {
try {
const response = await fetch(`${apiUrl}/user`, {
credentials: 'include' // Crucial setting
});

if (!response.ok) {
throw new Error('Profile fetch failed');
}

const data = await response.json();
setAuthState(data);
navigate('/');
} catch (error) {
console.error('Error fetching profile:', error);
clearAuthState();
navigate('/', { replace: true });
}
};
console.log('fetchUserProfile:');
fetchUserProfile();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);


const setAuthState = (authData) => {
setIsAuthenticated(true);
setUserProfile(authData);
};

const clearAuthState = () => {
console.log('clearAuthState');
setIsAuthenticated(false);
setUserProfile(null);
};

return (
// eslint-disable-next-line react/jsx-no-constructed-context-values
<AuthContext.Provider value={{ isAuthenticated, userProfile, setAuthState, clearAuthState }}>
{children}
</AuthContext.Provider>
);
};

AuthProvider.propTypes = {
children: PropTypes.node.isRequired,
};

export { AuthContext, AuthProvider };
30 changes: 28 additions & 2 deletions src/layouts/dashboard/common/account-popover.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState } from 'react';
import { useState, useContext } from 'react';
import { useNavigate } from 'react-router-dom';

import Box from '@mui/material/Box';
import Avatar from '@mui/material/Avatar';
Expand All @@ -10,6 +11,7 @@ import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';

import { account } from 'src/_mock/account';
import { AuthContext } from 'src/contexts/AuthContext';

// ----------------------------------------------------------------------

Expand All @@ -32,6 +34,10 @@ const MENU_OPTIONS = [

export default function AccountPopover() {
const [open, setOpen] = useState(null);
const navigate = useNavigate();
const { clearAuthState } = useContext(AuthContext);

const apiUrl = import.meta.env.VITE_API_URL;

const handleOpen = (event) => {
setOpen(event.currentTarget);
Expand All @@ -41,6 +47,26 @@ export default function AccountPopover() {
setOpen(null);
};

const handleLogout = async () => {
console.log('logout');
try {
const response = await fetch(`${apiUrl}/logout`, {
method: 'POST', // Or appropriate method for your endpoint
credentials: 'include',
});

const res = await response.json();
console.log('logout response:', res);

// Clear any additional user data
clearAuthState();
navigate('/login', { replace: true })
} catch (error) {
console.error('Logout error:', error);
}
setOpen(null);
}

return (
<>
<IconButton
Expand Down Expand Up @@ -105,7 +131,7 @@ export default function AccountPopover() {
<MenuItem
disableRipple
disableTouchRipple
onClick={handleClose}
onClick={handleLogout}
sx={{ typography: 'body2', color: 'error.main', py: 1.5 }}
>
Logout
Expand Down
40 changes: 40 additions & 0 deletions src/pages/login-success.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useNavigate } from 'react-router-dom';
import React, { useEffect, useContext } from 'react';

import { AuthContext } from 'src/contexts/AuthContext';

const LoginSuccess = () => {
const navigate = useNavigate();
const { setAuthState } = useContext(AuthContext);
const apiUrl = import.meta.env.VITE_API_URL;

useEffect(() => {
const fetchUserProfile = async () => {
try {
const response = await fetch(`${apiUrl}/user`, {
credentials: 'include' // Crucial setting
});

if (!response.ok) {
throw new Error('Profile fetch failed');
}

const data = await response.json();
setAuthState(data);
navigate('/', { replace: true });
} catch (error) {
console.error('Error fetching profile:', error);
// Handle the error (redirect to login, show error message)
}
};
console.log('fetchUserProfile:');
fetchUserProfile();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return (
<div>Loading...</div> // Or a loading indicator
);
};

export default LoginSuccess;
14 changes: 14 additions & 0 deletions src/pages/login.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
/* eslint-disable import/no-unresolved */
import { Helmet } from 'react-helmet-async';
import { useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';

import { AuthContext } from 'src/contexts/AuthContext';

import { LoginView } from 'src/sections/login';

// ----------------------------------------------------------------------

export default function LoginPage() {
const navigate = useNavigate();
const { isAuthenticated } = useContext(AuthContext);
useEffect(() => {
if (isAuthenticated) {
console.log('ProtectedComponent: authenticated');
navigate('/', { replace: true })
};
});

return (
<>
<Helmet>
Expand Down
43 changes: 36 additions & 7 deletions src/routes/sections.jsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,52 @@
import { lazy, Suspense } from 'react';
import { Outlet, Navigate, useRoutes } from 'react-router-dom';
/* eslint-disable import/no-unresolved */
import PropTypes from 'prop-types';
import { lazy, Suspense, useEffect, useContext } from 'react';
import { Outlet, Navigate, useRoutes, useNavigate } from 'react-router-dom';

import DashboardLayout from 'src/layouts/dashboard';
import { AuthContext } from 'src/contexts/AuthContext';

export const IndexPage = lazy(() => import('src/pages/app'));
export const BlogPage = lazy(() => import('src/pages/blog'));
export const UserPage = lazy(() => import('src/pages/user'));
export const LoginPage = lazy(() => import('src/pages/login'));
export const LoginSuccess = lazy(() => import('src/pages/login-success'));
export const ProductsPage = lazy(() => import('src/pages/products'));
export const FeedPage = lazy(() => import('src/pages/feed'));
export const Page404 = lazy(() => import('src/pages/page-not-found'));

// ----------------------------------------------------------------------

const ProtectedComponent = ({ children }) => {
const navigate = useNavigate();
const { isAuthenticated } = useContext(AuthContext);
console.log('ProtectedComponent children:', { children, isAuthenticated });

useEffect(() => {
if (!isAuthenticated) {
console.log('ProtectedComponent: not authenticated')
navigate('/login', { replace: true })
};
});

return children;
};

ProtectedComponent.propTypes = {
children: PropTypes.node,
};

export default function Router() {
const routes = useRoutes([
{
element: (
<DashboardLayout>
<Suspense>
<Outlet />
</Suspense>
</DashboardLayout>
<ProtectedComponent>
<DashboardLayout>
<Suspense>
<Outlet />
</Suspense>
</DashboardLayout>
</ProtectedComponent>
),
children: [
{ element: <IndexPage />, index: true },
Expand All @@ -35,6 +60,10 @@ export default function Router() {
path: 'login',
element: <LoginPage />,
},
{
path: 'login-success',
element: <LoginSuccess />,
},
{
path: '404',
element: <Page404 />,
Expand Down
Loading