probleme de communication entre le frontend et backend
This commit is contained in:
MathieuSevignyLavallee 2024-10-18 17:40:28 -04:00
parent dff86aa6e9
commit ddc33bb6ac
9 changed files with 73 additions and 34 deletions

View file

@ -15,6 +15,7 @@ const AuthSelection: React.FC = () => {
useEffect(() => { useEffect(() => {
const fetchData = async () => { const fetchData = async () => {
const data = await authService.fetchAuthData(); const data = await authService.fetchAuthData();
console.log(data);
setAuthData(data); setAuthData(data);
}; };
@ -26,7 +27,7 @@ const AuthSelection: React.FC = () => {
<h1>Connexion</h1> <h1>Connexion</h1>
{/* Formulaire de connexion Simple Login */} {/* Formulaire de connexion Simple Login */}
{authData && authData['simple-login'] && ( {authData && authData['simpleauth'] && (
<div className="form-container"> <div className="form-container">
<SimpleLogin /> <SimpleLogin />
</div> </div>

View file

@ -12,9 +12,10 @@ import ApiService from '../../../../services/ApiService';
const Register: React.FC = () => { const Register: React.FC = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const [name, setName] = useState(''); // State for name
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [role, setRole] = useState('etudiant'); const [roles, setRoles] = useState<string[]>(['student']); // Set 'student' as the default role
const [connectionError, setConnectionError] = useState<string>(''); const [connectionError, setConnectionError] = useState<string>('');
const [isConnecting] = useState<boolean>(false); const [isConnecting] = useState<boolean>(false);
@ -23,8 +24,23 @@ const Register: React.FC = () => {
return () => { }; return () => { };
}, []); }, []);
const handleRoleChange = (role: string) => {
setRoles([role]); // Update the roles array to contain the selected role
};
const isValidEmail = (email: string) => {
// Basic email format validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
const register = async () => { const register = async () => {
const result = await ApiService.register(email, password, role); if (!isValidEmail(email)) {
setConnectionError("Veuillez entrer une adresse email valide.");
return;
}
const result = await ApiService.register(name, email, password, roles);
if (result !== true) { if (result !== true) {
setConnectionError(result); setConnectionError(result);
@ -39,6 +55,16 @@ const Register: React.FC = () => {
title="Créer un compte" title="Créer un compte"
error={connectionError} error={connectionError}
> >
<TextField
label="Nom"
variant="outlined"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Votre nom"
sx={{ marginBottom: '1rem' }}
fullWidth
/>
<TextField <TextField
label="Email" label="Email"
variant="outlined" variant="outlined"
@ -47,6 +73,9 @@ const Register: React.FC = () => {
placeholder="Adresse courriel" placeholder="Adresse courriel"
sx={{ marginBottom: '1rem' }} sx={{ marginBottom: '1rem' }}
fullWidth fullWidth
type="email"
error={!!connectionError && !isValidEmail(email)}
helperText={connectionError && !isValidEmail(email) ? "Adresse email invalide." : ""}
/> />
<TextField <TextField
@ -66,11 +95,11 @@ const Register: React.FC = () => {
row row
aria-label="role" aria-label="role"
name="role" name="role"
value={role} value={roles[0]}
onChange={(e) => setRole(e.target.value)} onChange={(e) => handleRoleChange(e.target.value)}
> >
<FormControlLabel value="etudiant" control={<Radio />} label="Étudiant" /> <FormControlLabel value="student" control={<Radio />} label="Étudiant" />
<FormControlLabel value="professeur" control={<Radio />} label="Professeur" /> <FormControlLabel value="teacher" control={<Radio />} label="Professeur" />
</RadioGroup> </RadioGroup>
</Box> </Box>
@ -79,7 +108,7 @@ const Register: React.FC = () => {
onClick={register} onClick={register}
variant="contained" variant="contained"
sx={{ marginBottom: `${connectionError && '2rem'}` }} sx={{ marginBottom: `${connectionError && '2rem'}` }}
disabled={!email || !password} disabled={!name || !email || !password}
> >
S'inscrire S'inscrire
</LoadingButton> </LoadingButton>

View file

@ -87,12 +87,12 @@ class ApiService {
} }
try { try {
const decodedToken = jwtDecode(token) as { role: string }; const decodedToken = jwtDecode(token) as { roles: string[] };
const userRole = decodedToken.role; const userRoles = decodedToken.roles;
const requiredRole = 'professeur'; const requiredRole = 'teacher';
if (userRole !== requiredRole) { if (!userRoles || !userRoles.includes(requiredRole)) {
return false; return false;
} }
@ -116,16 +116,16 @@ class ApiService {
* @returns true if successful * @returns true if successful
* @returns A error string if unsuccessful, * @returns A error string if unsuccessful,
*/ */
public async register(email: string, password: string, role: string): Promise<any> { public async register(name: string, email: string, password: string, roles: string[]): Promise<any> {
try { try {
if (!email || !password) { if (!email || !password) {
throw new Error(`L'email et le mot de passe sont requis.`); throw new Error(`L'email et le mot de passe sont requis.`);
} }
const url: string = this.constructRequestUrl(`/user/register`); const url: string = this.constructRequestUrl(`/auth/simple-auth/register`);
const headers = this.constructRequestHeaders(); const headers = this.constructRequestHeaders();
const body = { email, password, role }; const body = { name, email, password, roles };
const result: AxiosResponse = await axios.post(url, body, { headers: headers }); const result: AxiosResponse = await axios.post(url, body, { headers: headers });
@ -159,7 +159,7 @@ class ApiService {
throw new Error(`L'email et le mot de passe sont requis.`); throw new Error(`L'email et le mot de passe sont requis.`);
} }
const url: string = this.constructRequestUrl(`/user/login`); const url: string = this.constructRequestUrl(`/auth/simple-auth/login`);
const headers = this.constructRequestHeaders(); const headers = this.constructRequestHeaders();
const body = { email, password }; const body = { email, password };
@ -197,7 +197,7 @@ class ApiService {
throw new Error(`L'email est requis.`); throw new Error(`L'email est requis.`);
} }
const url: string = this.constructRequestUrl(`/user/reset-password`); const url: string = this.constructRequestUrl(`/auth/simple-auth/reset-password`);
const headers = this.constructRequestHeaders(); const headers = this.constructRequestHeaders();
const body = { email }; const body = { email };
@ -233,7 +233,7 @@ class ApiService {
throw new Error(`L'email, l'ancien et le nouveau mot de passe sont requis.`); throw new Error(`L'email, l'ancien et le nouveau mot de passe sont requis.`);
} }
const url: string = this.constructRequestUrl(`/user/change-password`); const url: string = this.constructRequestUrl(`/auth/simple-auth/change-password`);
const headers = this.constructRequestHeaders(); const headers = this.constructRequestHeaders();
const body = { email, oldPassword, newPassword }; const body = { email, oldPassword, newPassword };

View file

@ -8,9 +8,14 @@ class AuthService {
this.BASE_URL = ENV_VARIABLES.VITE_BACKEND_URL; this.BASE_URL = ENV_VARIABLES.VITE_BACKEND_URL;
} }
private constructRequestUrl(endpoint: string): string {
return `${this.BASE_URL}/api${endpoint}`;
}
async fetchAuthData(){ async fetchAuthData(){
try { try {
const response = await fetch(`${this.BASE_URL}/api/auth/getActiveAuth`); const response = await fetch(this.constructRequestUrl('/auth/getActiveAuth'));
console.log("base url: " + this.BASE_URL);
const data = await response.json(); const data = await response.json();
return data.authActive; return data.authActive;
} catch (error) { } catch (error) {

View file

@ -7,6 +7,8 @@ services:
context: ./client context: ./client
dockerfile: Dockerfile dockerfile: Dockerfile
container_name: frontend container_name: frontend
environment:
VITE_BACKEND_URL: http://localhost:3000
ports: ports:
- "5173:5173" - "5173:5173"
restart: always restart: always

View file

@ -44,7 +44,7 @@ class AuthManager{
async login(userInfo,req,res,next){ async login(userInfo,req,res,next){
const tokenToSave = jwt.create(userInfo.email, userInfo._id); const tokenToSave = jwt.create(userInfo.email, userInfo._id);
res.redirect(`http://localhost:${process.env['FRONTEND_PORT']}/auth/callback?user=${tokenToSave}`); res.redirect(`/auth/callback?user=${tokenToSave}`);
console.info(`L'utilisateur '${userInfo.name}' vient de se connecter`) console.info(`L'utilisateur '${userInfo.name}' vient de se connecter`)
} }

View file

@ -26,9 +26,10 @@ class SimpleAuth{
async register(self,req, res) { async register(self,req, res) {
let userInfos = { let userInfos = {
name: req.body.email, name: req.body.name,
email: req.body.email, email: req.body.email,
password: req.body.password, password: req.body.password,
roles: req.body.roles
} }
let user = await self.authmanager.register(userInfos) let user = await self.authmanager.register(userInfos)
if(user) res.redirect("/") if(user) res.redirect("/")

View file

@ -44,8 +44,8 @@ class AuthConfig {
// Méthode pour retourner la configuration de Simple Login // Méthode pour retourner la configuration de Simple Login
getSimpleLoginConfig() { getSimpleLoginConfig() {
if (this.config && this.config.auth && this.config.auth["simple-login"]) { if (this.config && this.config.auth && this.config.auth["simpleauth"]) {
return this.config.auth["simple-login"]; return this.config.auth["simpleauth"];
} else { } else {
return { error: "Aucune configuration Simple Login disponible." }; return { error: "Aucune configuration Simple Login disponible." };
} }
@ -162,10 +162,10 @@ class AuthConfig {
} }
// Gestion du Simple Login // Gestion du Simple Login
if (this.config.auth["simple-login"] && this.config.auth["simple-login"].enabled) { if (this.config.auth["simpleauth"] && this.config.auth["simpleauth"].enabled) {
passportConfig['simple-login'] = { passportConfig['simpleauth'] = {
type: "simple-login", type: "simpleauth",
name: this.config.auth["simple-login"].name name: this.config.auth["simpleauth"].name
}; };
} }

View file

@ -35,6 +35,7 @@ class Users {
email: userInfos.email, email: userInfos.email,
password: await this.hashPassword(userInfos.password), password: await this.hashPassword(userInfos.password),
created_at: new Date(), created_at: new Date(),
roles: userInfos.roles
}; };
let created_user = await userCollection.insertOne(newUser); let created_user = await userCollection.insertOne(newUser);