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

View file

@ -12,9 +12,10 @@ import ApiService from '../../../../services/ApiService';
const Register: React.FC = () => {
const navigate = useNavigate();
const [name, setName] = useState(''); // State for name
const [email, setEmail] = 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 [isConnecting] = useState<boolean>(false);
@ -23,8 +24,23 @@ const Register: React.FC = () => {
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 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) {
setConnectionError(result);
@ -39,6 +55,16 @@ const Register: React.FC = () => {
title="Créer un compte"
error={connectionError}
>
<TextField
label="Nom"
variant="outlined"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Votre nom"
sx={{ marginBottom: '1rem' }}
fullWidth
/>
<TextField
label="Email"
variant="outlined"
@ -47,6 +73,9 @@ const Register: React.FC = () => {
placeholder="Adresse courriel"
sx={{ marginBottom: '1rem' }}
fullWidth
type="email"
error={!!connectionError && !isValidEmail(email)}
helperText={connectionError && !isValidEmail(email) ? "Adresse email invalide." : ""}
/>
<TextField
@ -66,11 +95,11 @@ const Register: React.FC = () => {
row
aria-label="role"
name="role"
value={role}
onChange={(e) => setRole(e.target.value)}
value={roles[0]}
onChange={(e) => handleRoleChange(e.target.value)}
>
<FormControlLabel value="etudiant" control={<Radio />} label="Étudiant" />
<FormControlLabel value="professeur" control={<Radio />} label="Professeur" />
<FormControlLabel value="student" control={<Radio />} label="Étudiant" />
<FormControlLabel value="teacher" control={<Radio />} label="Professeur" />
</RadioGroup>
</Box>
@ -79,7 +108,7 @@ const Register: React.FC = () => {
onClick={register}
variant="contained"
sx={{ marginBottom: `${connectionError && '2rem'}` }}
disabled={!email || !password}
disabled={!name || !email || !password}
>
S'inscrire
</LoadingButton>

View file

@ -79,26 +79,26 @@ class ApiService {
public isLoggedInTeacher(): boolean {
const token = this.getToken();
console.log("Check if loggedIn : " + token);
if (token == null) {
return false;
}
try {
const decodedToken = jwtDecode(token) as { role: string };
const userRole = decodedToken.role;
const requiredRole = 'professeur';
if (userRole !== requiredRole) {
const decodedToken = jwtDecode(token) as { roles: string[] };
const userRoles = decodedToken.roles;
const requiredRole = 'teacher';
if (!userRoles || !userRoles.includes(requiredRole)) {
return false;
}
// Update token expiry
this.saveToken(token);
return true;
} catch (error) {
console.error("Error decoding token:", error);
@ -116,16 +116,16 @@ class ApiService {
* @returns true if successful
* @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 {
if (!email || !password) {
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 body = { email, password, role };
const body = { name, email, password, roles };
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.`);
}
const url: string = this.constructRequestUrl(`/user/login`);
const url: string = this.constructRequestUrl(`/auth/simple-auth/login`);
const headers = this.constructRequestHeaders();
const body = { email, password };
@ -197,7 +197,7 @@ class ApiService {
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 body = { email };
@ -233,7 +233,7 @@ class ApiService {
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 body = { email, oldPassword, newPassword };

View file

@ -8,9 +8,14 @@ class AuthService {
this.BASE_URL = ENV_VARIABLES.VITE_BACKEND_URL;
}
private constructRequestUrl(endpoint: string): string {
return `${this.BASE_URL}/api${endpoint}`;
}
async fetchAuthData(){
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();
return data.authActive;
} catch (error) {

View file

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

View file

@ -44,7 +44,7 @@ class AuthManager{
async login(userInfo,req,res,next){
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`)
}

View file

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

View file

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

View file

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