feat: Ajout d'une fonction de logout

This commit is contained in:
N3WT DE COMPET
2025-02-17 18:18:52 +01:00
parent 8ea68bbad0
commit 0ef6a2b119
4 changed files with 204 additions and 157 deletions

View File

@ -15,6 +15,7 @@ import {
} from 'lucide-react';
import DropdownMenu from '@/components/DropdownMenu';
import Logo from '@/components/Logo';
import Popup from '@/components/Popup';
import {
FE_ADMIN_HOME_URL,
FE_ADMIN_SUBSCRIPTIONS_URL,
@ -45,6 +46,7 @@ export default function Layout({
const [establishment, setEstablishment] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [isPopupVisible, setIsPopupVisible] = useState(false);
const pathname = usePathname();
const currentPage = pathname.split('/').pop();
@ -54,11 +56,19 @@ export default function Layout({
const softwareName = "N3WT School";
const softwareVersion = `v${process.env.NEXT_PUBLIC_APP_VERSION}`;
const handleDisconnect = () => {
setIsPopupVisible(true);
};
const confirmDisconnect = () => {
setIsPopupVisible(false);
disconnect();
};
const dropdownItems = [
{
label: 'Déconnexion',
onClick: disconnect,
onClick: handleDisconnect,
icon: LogOut,
},
];
@ -74,46 +84,48 @@ export default function Layout({
}, []);
return (
<>
<SessionProvider>
<ProtectedRoute>
{!isLoading && (
<div className="flex min-h-screen bg-gray-50">
<Sidebar establishment={establishment} currentPage={currentPage} items={Object.values(sidebarItems)} className="h-full" />
<div className="flex flex-col flex-1">
{/* Header - h-16 = 64px */}
<header className="h-16 bg-white border-b border-gray-200 px-8 py-4 flex items-center justify-between z-9">
<div className="text-xl font-semibold">{headerTitle}</div>
<DropdownMenu
buttonContent={<img src="https://i.pravatar.cc/32" alt="Profile" className="w-8 h-8 rounded-full cursor-pointer" />}
items={dropdownItems}
buttonClassName=""
menuClassName="absolute right-0 mt-2 w-48 bg-white border border-gray-200 rounded shadow-lg"
/>
</header>
{/* Main Content */}
<div className="flex-1 flex flex-col">
{/* Content avec scroll si nécessaire */}
<div className="flex-1 overflow-auto">
{children}
</div>
{/* Footer - h-16 = 64px */}
<footer className="h-16 bg-white border-t border-gray-200 px-8 py-4 flex items-center justify-between">
<div className="text-sm font-light">
<span>&copy; {new Date().getFullYear()} N3WT-INNOV Tous droits réservés.</span>
<div className="text-sm font-light">{softwareName} - {softwareVersion}</div>
<ProtectedRoute>
{!isLoading && (
<div className="flex min-h-screen bg-gray-50">
<Sidebar establishment={establishment} currentPage={currentPage} items={Object.values(sidebarItems)} className="h-full" />
<div className="flex flex-col flex-1">
{/* Header - h-16 = 64px */}
<header className="h-16 bg-white border-b border-gray-200 px-8 py-4 flex items-center justify-between z-9">
<div className="text-xl font-semibold">{headerTitle}</div>
<DropdownMenu
buttonContent={<img src="https://i.pravatar.cc/32" alt="Profile" className="w-8 h-8 rounded-full cursor-pointer" />}
items={dropdownItems}
buttonClassName=""
menuClassName="absolute right-0 mt-2 w-48 bg-white border border-gray-200 rounded shadow-lg"
/>
</header>
{/* Main Content */}
<div className="flex-1 flex flex-col">
{/* Content avec scroll si nécessaire */}
<div className="flex-1 overflow-auto">
{children}
</div>
<Logo className="w-8 h-8" />
</footer>
{/* Footer - h-16 = 64px */}
<footer className="h-16 bg-white border-t border-gray-200 px-8 py-4 flex items-center justify-between">
<div className="text-sm font-light">
<span>&copy; {new Date().getFullYear()} N3WT-INNOV Tous droits réservés.</span>
<div className="text-sm font-light">{softwareName} - {softwareVersion}</div>
</div>
<Logo className="w-8 h-8" />
</footer>
</div>
</div>
</div>
</div>
)}
</ProtectedRoute>
)}
<Popup
visible={isPopupVisible}
message="Êtes-vous sûr(e) de vouloir vous déconnecter ?"
onConfirm={confirmDisconnect}
onCancel={() => setIsPopupVisible(false)}
/>
</ProtectedRoute>
</SessionProvider>
</>
);
}

View File

@ -36,7 +36,7 @@ export default function Page() {
return data.errorMessage === ""
}
async function handleFormLogin(formData) {
/*async function handleFormLogin(formData) {
setIsLoading(true);
try {
@ -76,7 +76,52 @@ export default function Page() {
setIsLoading(false);
setErrorMessage('An error occurred during sign in.');
}
}
}*/
function handleFormLogin(formData) {
setIsLoading(true);
signIn('credentials', {
redirect: false,
email: formData.get('login'),
password: formData.get('password'),
}).then(result => {
console.log('Sign In Result', result);
setIsLoading(false);
if (result.error) {
setErrorMessage(result.error);
} else {
getSession().then(session => {
if (!session || !session.user) {
throw new Error('Session not found');
}
const user = session.user;
console.log('User Session:', user);
localStorage.setItem('userId', user.id); // Stocker l'identifiant de l'utilisateur
if (user.droit === 0) {
// Vue ECOLE
} else if (user.droit === 1) {
// Vue ADMIN
router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
} else if (user.droit === 2) {
// Vue PARENT
router.push(FE_PARENTS_HOME_URL);
} else {
// Cas anormal
}
}).catch(error => {
console.error('Error during session retrieval:', error);
setIsLoading(false);
setErrorMessage('An error occurred during session retrieval.');
});
}
}).catch(error => {
console.error('Error during sign in:', error);
setIsLoading(false);
setErrorMessage('An error occurred during sign in.');
});
}
if (isLoading === true) {
return <Loader /> // Affichez le composant Loader

View File

@ -1,156 +1,155 @@
import { signOut } from 'next-auth/react';
import {
BE_AUTH_LOGIN_URL,
BE_AUTH_REGISTER_URL,
BE_AUTH_PROFILES_URL,
BE_AUTH_RESET_PASSWORD_URL,
BE_AUTH_NEW_PASSWORD_URL,
FE_USERS_LOGIN_URL ,
FE_USERS_LOGIN_URL,
} from '@/utils/Url';
import {mockUser} from "@/data/mockUsersData";
const useFakeData = process.env.NEXT_PUBLIC_USE_FAKE_DATA === 'true';
const requestResponseHandler = async (response) => {
const body = await response.json();
if (response.ok) {
return body;
}
// Throw an error with the JSON body containing the form errors
const error = new Error('Form submission error');
error.details = body;
throw error;
}
};
/*export const login = (data, csrfToken) => {
const request = new Request(
`${BE_AUTH_LOGIN_URL}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify(data),
credentials: 'include',
}
);
return fetch(request).then(requestResponseHandler);
};*/
export const login = (data, csrfToken) => {
console.log('data', data);
const request = new Request(
`${BE_AUTH_LOGIN_URL}`,
{
method:'POST',
headers: {
'Content-Type':'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify(data),
credentials: 'include',
const request = new Promise((resolve, reject) => {
signIn('credentials', {
redirect: false,
email: data.email,
password: data.password,
}).then(result => {
if (result.error) {
reject(new Error(result.error));
} else {
resolve(result);
}
);
return fetch(request).then(requestResponseHandler)
}
}).catch(reject);
});
return request.then(requestResponseHandler);
};
/**
* Disconnects the user after confirming the action.
* If `NEXT_PUBLIC_USE_FAKE_DATA` environment variable is set to 'true', it will log a fake disconnect and redirect to the login URL.
* Otherwise, it will send a PUT request to the backend to update the user profile and then redirect to the login URL.
* Otherwise, it will call `signOut` from NextAuth.js to handle the logout.
*
* @function
* @name disconnect
* @returns {void}
*/
export const disconnect = () => {
if (confirm("\nÊtes-vous sûr(e) de vouloir vous déconnecter ?")) {
export const disconnect = () => {
signOut({ callbackUrl: FE_USERS_LOGIN_URL });
};
if (useFakeData) {
console.log('Fake disconnect:', mockUser);
router.push(`${FE_USERS_LOGIN_URL}`);
} else {
console.log('Fake disconnect:', mockUser);
router.push(`${FE_USERS_LOGIN_URL}`);
}
export const createProfile = (data, csrfToken) => {
const request = new Request(
`${BE_AUTH_PROFILES_URL}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
};
export const createProfile = (data,csrfToken) => {
const request = new Request(
`${BE_AUTH_PROFILES_URL}`,
{
method:'POST',
headers: {
'Content-Type':'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
);
return fetch(request).then(requestResponseHandler)
}
);
return fetch(request).then(requestResponseHandler);
};
export const updateProfile = (id, data, csrfToken) => {
const request = new Request(
const request = new Request(
`${BE_AUTH_PROFILES_URL}/${id}`,
{
method:'PUT',
headers: {
'Content-Type':'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
);
return fetch(request).then(requestResponseHandler)
}
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
);
return fetch(request).then(requestResponseHandler);
};
export const sendNewPassword = (data, csrfToken) => {
const request = new Request(
`${BE_AUTH_NEW_PASSWORD_URL}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
);
return fetch(request).then(requestResponseHandler)
}
`${BE_AUTH_NEW_PASSWORD_URL}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
);
return fetch(request).then(requestResponseHandler);
};
export const subscribe = (data,csrfToken) =>{
export const subscribe = (data, csrfToken) => {
const request = new Request(
`${BE_AUTH_REGISTER_URL}`,
{
method:'POST',
headers: {
'Content-Type':'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify( data),
}
);
return fetch(request).then(requestResponseHandler)
}
`${BE_AUTH_REGISTER_URL}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
);
return fetch(request).then(requestResponseHandler);
};
export const resetPassword = (uuid, data, csrfToken) => {
const request = new Request(
`${BE_AUTH_RESET_PASSWORD_URL}/${uuid}`,
{
method:'POST',
headers: {
'Content-Type':'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
`${BE_AUTH_RESET_PASSWORD_URL}/${uuid}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
credentials: 'include',
body: JSON.stringify(data),
}
);
return fetch(request).then(requestResponseHandler)
}
return fetch(request).then(requestResponseHandler);
};
export const getResetPassword = (uuid) => {
const url= `${BE_AUTH_RESET_PASSWORD_URL}/${uuid}`;
const url = `${BE_AUTH_RESET_PASSWORD_URL}/${uuid}`;
return fetch(url, {
headers: {
'Content-Type': 'application/json',
},
}).then(requestResponseHandler)
}
headers: {
'Content-Type': 'application/json',
},
}).then(requestResponseHandler);
};

View File

@ -1,9 +0,0 @@
import { signOut } from 'next-auth/react';
export default function SignOut() {
return (
<button onClick={() => signOut({ callbackUrl: '/' })}>
Sign out
</button>
);
}