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(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
const data = await authService.fetchAuthData();
|
const data = await authService.fetchAuthData();
|
||||||
console.log(data);
|
|
||||||
setAuthData(data);
|
setAuthData(data);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { useEffect } from 'react';
|
import { useEffect } from 'react';
|
||||||
import { useNavigate, useLocation } from 'react-router-dom';
|
import { useNavigate, useLocation } from 'react-router-dom';
|
||||||
import apiService from '../../../services/ApiService';
|
import apiService from '../../../services/ApiService';
|
||||||
import { jwtDecode } from 'jwt-decode';
|
|
||||||
|
|
||||||
const OAuthCallback: React.FC = () => {
|
const OAuthCallback: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
@ -12,15 +11,7 @@ const OAuthCallback: React.FC = () => {
|
||||||
const user = searchParams.get('user');
|
const user = searchParams.get('user');
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
// Save user data to localStorage or sessionStorage
|
|
||||||
console.log(user);
|
|
||||||
apiService.saveToken(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('/');
|
navigate('/');
|
||||||
} else {
|
} else {
|
||||||
navigate('/login');
|
navigate('/login');
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { ENV_VARIABLES } from '../../../../constants';
|
|
||||||
import '../css/buttonAuth.css';
|
import '../css/buttonAuth.css';
|
||||||
|
|
||||||
interface ButtonAuthContainerProps {
|
interface ButtonAuthContainerProps {
|
||||||
|
|
@ -8,7 +7,7 @@ interface ButtonAuthContainerProps {
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleAuthLogin = (provider: string) => {
|
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 }) => {
|
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
|
// JoinRoom.tsx
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
|
|
@ -11,7 +11,6 @@ import LoginContainer from '../../../../components/LoginContainer/LoginContainer
|
||||||
import ApiService from '../../../../services/ApiService';
|
import ApiService from '../../../../services/ApiService';
|
||||||
|
|
||||||
const SimpleLogin: React.FC = () => {
|
const SimpleLogin: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
|
|
@ -27,15 +26,10 @@ const SimpleLogin: React.FC = () => {
|
||||||
|
|
||||||
const login = async () => {
|
const login = async () => {
|
||||||
const result = await ApiService.login(email, password);
|
const result = await ApiService.login(email, password);
|
||||||
|
if (result !== true) {
|
||||||
if (result != true) {
|
|
||||||
setConnectionError(result);
|
setConnectionError(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
else {
|
|
||||||
navigate("/")
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,3 @@
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
|
|
||||||
// JoinRoom.tsx
|
// JoinRoom.tsx
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
|
@ -10,7 +8,6 @@ import LoginContainer from '../../../../components/LoginContainer/LoginContainer
|
||||||
import ApiService from '../../../../services/ApiService';
|
import ApiService from '../../../../services/ApiService';
|
||||||
|
|
||||||
const Register: React.FC = () => {
|
const Register: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const [name, setName] = useState(''); // State for name
|
const [name, setName] = useState(''); // State for name
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
|
|
@ -46,8 +43,6 @@ const Register: React.FC = () => {
|
||||||
setConnectionError(result);
|
setConnectionError(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
navigate("/login");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -80,7 +80,6 @@ class ApiService {
|
||||||
public isLoggedInTeacher(): boolean {
|
public isLoggedInTeacher(): boolean {
|
||||||
const token = this.getToken();
|
const token = this.getToken();
|
||||||
|
|
||||||
console.log("Check if loggedIn : " + token);
|
|
||||||
|
|
||||||
if (token == null) {
|
if (token == null) {
|
||||||
return false;
|
return false;
|
||||||
|
|
@ -129,8 +128,12 @@ class ApiService {
|
||||||
|
|
||||||
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
||||||
|
|
||||||
if (result.status !== 200) {
|
console.log(result);
|
||||||
throw new Error(`L'enregistrement a échoué. Status: ${result.status}`);
|
if (result.status == 200) {
|
||||||
|
window.location.href = result.request.responseURL;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new Error(`La connexion a échoué. Status: ${result.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
@ -152,11 +155,14 @@ class ApiService {
|
||||||
* @returns true if successful
|
* @returns true if successful
|
||||||
* @returns A error string if unsuccessful,
|
* @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> {
|
public async login(email: string, password: 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(`/auth/simple-auth/login`);
|
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 });
|
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
||||||
|
|
||||||
if (result.status !== 200) {
|
// If login is successful, redirect the user
|
||||||
throw new Error(`La connexion a échoué. Status: ${result.status}`);
|
if (result.status === 200) {
|
||||||
}
|
window.location.href = result.request.responseURL;
|
||||||
|
|
||||||
this.saveToken(result.data.token);
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
} else {
|
||||||
|
throw new Error(`La connexion a échoué. Statut: ${result.status}`);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("Error details:", error);
|
console.log("Error details:", error);
|
||||||
|
|
||||||
|
// Handle Axios-specific errors
|
||||||
if (axios.isAxiosError(error)) {
|
if (axios.isAxiosError(error)) {
|
||||||
const err = error as AxiosError;
|
const err = error as AxiosError;
|
||||||
const data = err.response?.data as { error: string } | undefined;
|
const responseData = err.response?.data as { message?: string } | undefined;
|
||||||
return data?.error || 'Erreur serveur inconnue lors de la requête.';
|
|
||||||
|
// 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 true if successful
|
||||||
* @returns A error string if unsuccessful,
|
* @returns A error string if unsuccessful,
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,6 @@ class AuthService {
|
||||||
async fetchAuthData(){
|
async fetchAuthData(){
|
||||||
try {
|
try {
|
||||||
const response = await fetch(this.constructRequestUrl('/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) {
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,6 @@ 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
|
||||||
|
|
|
||||||
|
|
@ -43,8 +43,8 @@ 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,userInfo.roles);
|
||||||
res.redirect(`${process.env['FRONTEND_URL']}/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`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,7 @@ class PassportOpenIDConnect {
|
||||||
roles: []
|
roles: []
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
if (hasNestedValue(profile, provider.OIDC_ROLE_TEACHER_VALUE)) received_user.roles.push('teacher')
|
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')
|
if (hasNestedValue(profile, provider.OIDC_ROLE_STUDENT_VALUE)) received_user.roles.push('student')
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ class SimpleAuth{
|
||||||
}
|
}
|
||||||
|
|
||||||
async register(self, req, res) {
|
async register(self, req, res) {
|
||||||
|
try {
|
||||||
let userInfos = {
|
let userInfos = {
|
||||||
name: req.body.name,
|
name: req.body.name,
|
||||||
email: req.body.email,
|
email: req.body.email,
|
||||||
|
|
@ -32,8 +33,13 @@ class SimpleAuth{
|
||||||
roles: req.body.roles
|
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("/login")
|
||||||
else res.redirect("/login")
|
}
|
||||||
|
catch (error) {
|
||||||
|
return res.status(400).json({
|
||||||
|
message: error.message
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async authenticate(self, req, res, next) {
|
async authenticate(self, req, res, next) {
|
||||||
|
|
@ -41,22 +47,20 @@ class SimpleAuth{
|
||||||
const { email, password } = req.body;
|
const { email, password } = req.body;
|
||||||
|
|
||||||
if (!email || !password) {
|
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);
|
const user = await model.login(email, password);
|
||||||
|
|
||||||
if (!user) {
|
await self.authmanager.login(user, req, res, next);
|
||||||
throw new AppError(LOGIN_CREDENTIALS_ERROR);
|
} catch (error) {
|
||||||
}
|
const statusCode = error.statusCode || 500;
|
||||||
|
const message = error.message || "An internal server error occurred";
|
||||||
|
|
||||||
user.name = user.name ?? user.email
|
console.error(error);
|
||||||
self.authmanager.login(user,req,res,next)
|
return res.status(statusCode).json({ message });
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
return res.status(400).json({
|
|
||||||
message: error.message
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,8 @@ dotenv.config();
|
||||||
|
|
||||||
class Token {
|
class Token {
|
||||||
|
|
||||||
create(email, userId) {
|
create(email, userId, roles) {
|
||||||
return jwt.sign({ email, userId }, process.env.JWT_SECRET);
|
return jwt.sign({ email, userId, roles }, process.env.JWT_SECRET);
|
||||||
}
|
}
|
||||||
|
|
||||||
authenticate(req, res, next) {
|
authenticate(req, res, next) {
|
||||||
|
|
|
||||||
|
|
@ -64,24 +64,32 @@ class Users {
|
||||||
}
|
}
|
||||||
|
|
||||||
async login(email, password) {
|
async login(email, password) {
|
||||||
|
try {
|
||||||
await db.connect();
|
await db.connect();
|
||||||
const conn = db.getConnection();
|
const conn = db.getConnection();
|
||||||
|
|
||||||
const userCollection = conn.collection("users");
|
const userCollection = conn.collection("users");
|
||||||
|
|
||||||
const user = await userCollection.findOne({ email: email });
|
const user = await userCollection.findOne({ email: email });
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return false;
|
const error = new Error("User not found");
|
||||||
|
error.statusCode = 404;
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const passwordMatch = await this.verify(password, user.password);
|
const passwordMatch = await this.verify(password, user.password);
|
||||||
|
|
||||||
if (!passwordMatch) {
|
if (!passwordMatch) {
|
||||||
return false;
|
const error = new Error("Password does not match");
|
||||||
|
error.statusCode = 401;
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return user;
|
return user;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async resetPassword(email) {
|
async resetPassword(email) {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue