mirror of
https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir.git
synced 2025-08-11 21:23:54 -04:00
Roles done
This commit is contained in:
parent
d7986447c4
commit
e30681705f
14 changed files with 227 additions and 223 deletions
|
|
@ -15,7 +15,6 @@ const AuthSelection: React.FC = () => {
|
|||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
const data = await authService.fetchAuthData();
|
||||
console.log(data);
|
||||
setAuthData(data);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { useEffect } from 'react';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import apiService from '../../../services/ApiService';
|
||||
import { jwtDecode } from 'jwt-decode';
|
||||
|
||||
const OAuthCallback: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -12,15 +11,7 @@ const OAuthCallback: React.FC = () => {
|
|||
const user = searchParams.get('user');
|
||||
|
||||
if (user) {
|
||||
// Save user data to localStorage or sessionStorage
|
||||
console.log(user);
|
||||
apiService.saveToken(user);
|
||||
|
||||
const decodedToken = jwtDecode(user);
|
||||
const { email } = decodedToken as { email: string;};
|
||||
console.log(email + " connected!");
|
||||
|
||||
// Navigate to the dashboard or another page
|
||||
navigate('/');
|
||||
} else {
|
||||
navigate('/login');
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import React from 'react';
|
||||
import { ENV_VARIABLES } from '../../../../constants';
|
||||
import '../css/buttonAuth.css';
|
||||
|
||||
interface ButtonAuthContainerProps {
|
||||
|
|
@ -8,7 +7,7 @@ interface ButtonAuthContainerProps {
|
|||
}
|
||||
|
||||
const handleAuthLogin = (provider: string) => {
|
||||
window.location.href = `${ENV_VARIABLES.VITE_BACKEND_URL}/api/auth/` + provider;
|
||||
window.location.href = `/api/auth/` + provider;
|
||||
};
|
||||
|
||||
const ButtonAuth: React.FC<ButtonAuthContainerProps> = ({ providerName, providerType }) => {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
// JoinRoom.tsx
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
|
@ -11,7 +11,6 @@ import LoginContainer from '../../../../components/LoginContainer/LoginContainer
|
|||
import ApiService from '../../../../services/ApiService';
|
||||
|
||||
const SimpleLogin: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
|
|
@ -27,15 +26,10 @@ const SimpleLogin: React.FC = () => {
|
|||
|
||||
const login = async () => {
|
||||
const result = await ApiService.login(email, password);
|
||||
|
||||
if (result != true) {
|
||||
if (result !== true) {
|
||||
setConnectionError(result);
|
||||
return;
|
||||
}
|
||||
else {
|
||||
navigate("/")
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
// JoinRoom.tsx
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
|
|
@ -10,7 +8,6 @@ import LoginContainer from '../../../../components/LoginContainer/LoginContainer
|
|||
import ApiService from '../../../../services/ApiService';
|
||||
|
||||
const Register: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [name, setName] = useState(''); // State for name
|
||||
const [email, setEmail] = useState('');
|
||||
|
|
@ -46,8 +43,6 @@ const Register: React.FC = () => {
|
|||
setConnectionError(result);
|
||||
return;
|
||||
}
|
||||
|
||||
navigate("/login");
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -80,7 +80,6 @@ class ApiService {
|
|||
public isLoggedInTeacher(): boolean {
|
||||
const token = this.getToken();
|
||||
|
||||
console.log("Check if loggedIn : " + token);
|
||||
|
||||
if (token == null) {
|
||||
return false;
|
||||
|
|
@ -129,8 +128,12 @@ class ApiService {
|
|||
|
||||
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
||||
|
||||
if (result.status !== 200) {
|
||||
throw new Error(`L'enregistrement a échoué. Status: ${result.status}`);
|
||||
console.log(result);
|
||||
if (result.status == 200) {
|
||||
window.location.href = result.request.responseURL;
|
||||
}
|
||||
else {
|
||||
throw new Error(`La connexion a échoué. Status: ${result.status}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
|
@ -152,11 +155,14 @@ class ApiService {
|
|||
* @returns true if successful
|
||||
* @returns A error string if unsuccessful,
|
||||
*/
|
||||
/**
|
||||
* @returns true if successful
|
||||
* @returns An error string if unsuccessful
|
||||
*/
|
||||
public async login(email: string, password: string): Promise<any> {
|
||||
try {
|
||||
|
||||
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(`/auth/simple-auth/login`);
|
||||
|
|
@ -165,27 +171,37 @@ class ApiService {
|
|||
|
||||
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
||||
|
||||
if (result.status !== 200) {
|
||||
throw new Error(`La connexion a échoué. Status: ${result.status}`);
|
||||
}
|
||||
|
||||
this.saveToken(result.data.token);
|
||||
|
||||
// If login is successful, redirect the user
|
||||
if (result.status === 200) {
|
||||
window.location.href = result.request.responseURL;
|
||||
return true;
|
||||
|
||||
} else {
|
||||
throw new Error(`La connexion a échoué. Statut: ${result.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("Error details:", error);
|
||||
|
||||
// Handle Axios-specific errors
|
||||
if (axios.isAxiosError(error)) {
|
||||
const err = error as AxiosError;
|
||||
const data = err.response?.data as { error: string } | undefined;
|
||||
return data?.error || 'Erreur serveur inconnue lors de la requête.';
|
||||
const responseData = err.response?.data as { message?: string } | undefined;
|
||||
|
||||
// If there is a message field in the response, print it
|
||||
if (responseData?.message) {
|
||||
console.log("Backend error message:", responseData.message);
|
||||
return responseData.message;
|
||||
}
|
||||
|
||||
return `Une erreur inattendue s'est produite.`
|
||||
// If no message is found, return a fallback message
|
||||
return "Erreur serveur inconnue lors de la requête.";
|
||||
}
|
||||
|
||||
// Handle other non-Axios errors
|
||||
return "Une erreur inattendue s'est produite.";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @returns true if successful
|
||||
* @returns A error string if unsuccessful,
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ class AuthService {
|
|||
async fetchAuthData(){
|
||||
try {
|
||||
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) {
|
||||
|
|
|
|||
|
|
@ -7,8 +7,6 @@ services:
|
|||
context: ./client
|
||||
dockerfile: Dockerfile
|
||||
container_name: frontend
|
||||
environment:
|
||||
VITE_BACKEND_URL: http://localhost:3000
|
||||
ports:
|
||||
- "5173:5173"
|
||||
restart: always
|
||||
|
|
|
|||
|
|
@ -43,8 +43,8 @@ class AuthManager{
|
|||
}
|
||||
|
||||
async login(userInfo,req,res,next){
|
||||
const tokenToSave = jwt.create(userInfo.email, userInfo._id);
|
||||
res.redirect(`${process.env['FRONTEND_URL']}/auth/callback?user=${tokenToSave}`);
|
||||
const tokenToSave = jwt.create(userInfo.email, userInfo._id,userInfo.roles);
|
||||
res.redirect(`/auth/callback?user=${tokenToSave}`);
|
||||
console.info(`L'utilisateur '${userInfo.name}' vient de se connecter`)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ class PassportOpenIDConnect {
|
|||
roles: []
|
||||
};
|
||||
|
||||
|
||||
if (hasNestedValue(profile, provider.OIDC_ROLE_TEACHER_VALUE)) received_user.roles.push('teacher')
|
||||
if (hasNestedValue(profile, provider.OIDC_ROLE_STUDENT_VALUE)) received_user.roles.push('student')
|
||||
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ class SimpleAuth{
|
|||
}
|
||||
|
||||
async register(self, req, res) {
|
||||
try {
|
||||
let userInfos = {
|
||||
name: req.body.name,
|
||||
email: req.body.email,
|
||||
|
|
@ -32,8 +33,13 @@ class SimpleAuth{
|
|||
roles: req.body.roles
|
||||
}
|
||||
let user = await self.authmanager.register(userInfos)
|
||||
if(user) res.redirect("/")
|
||||
else res.redirect("/login")
|
||||
if (user) res.redirect("/login")
|
||||
}
|
||||
catch (error) {
|
||||
return res.status(400).json({
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async authenticate(self, req, res, next) {
|
||||
|
|
@ -41,22 +47,20 @@ class SimpleAuth{
|
|||
const { email, password } = req.body;
|
||||
|
||||
if (!email || !password) {
|
||||
throw new AppError(MISSING_REQUIRED_PARAMETER);
|
||||
const error = new Error("Email or password is missing");
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const user = await model.login(email, password);
|
||||
|
||||
if (!user) {
|
||||
throw new AppError(LOGIN_CREDENTIALS_ERROR);
|
||||
}
|
||||
await self.authmanager.login(user, req, res, next);
|
||||
} catch (error) {
|
||||
const statusCode = error.statusCode || 500;
|
||||
const message = error.message || "An internal server error occurred";
|
||||
|
||||
user.name = user.name ?? user.email
|
||||
self.authmanager.login(user,req,res,next)
|
||||
}
|
||||
catch (error) {
|
||||
return res.status(400).json({
|
||||
message: error.message
|
||||
});
|
||||
console.error(error);
|
||||
return res.status(statusCode).json({ message });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,8 +7,8 @@ dotenv.config();
|
|||
|
||||
class Token {
|
||||
|
||||
create(email, userId) {
|
||||
return jwt.sign({ email, userId }, process.env.JWT_SECRET);
|
||||
create(email, userId, roles) {
|
||||
return jwt.sign({ email, userId, roles }, process.env.JWT_SECRET);
|
||||
}
|
||||
|
||||
authenticate(req, res, next) {
|
||||
|
|
|
|||
|
|
@ -64,24 +64,32 @@ class Users {
|
|||
}
|
||||
|
||||
async login(email, password) {
|
||||
try {
|
||||
await db.connect();
|
||||
const conn = db.getConnection();
|
||||
|
||||
const userCollection = conn.collection("users");
|
||||
|
||||
const user = await userCollection.findOne({ email: email });
|
||||
|
||||
if (!user) {
|
||||
return false;
|
||||
const error = new Error("User not found");
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const passwordMatch = await this.verify(password, user.password);
|
||||
|
||||
if (!passwordMatch) {
|
||||
return false;
|
||||
const error = new Error("Password does not match");
|
||||
error.statusCode = 401;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return user;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async resetPassword(email) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue