feat: découverte dynamique apps - portail dynamique - fix URLs
This commit is contained in:
61
backend/src/auth.js
Normal file
61
backend/src/auth.js
Normal file
@@ -0,0 +1,61 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const config = require('./config');
|
||||
|
||||
// Hash du mot de passe au démarrage
|
||||
let passwordHash = null;
|
||||
|
||||
async function initAuth() {
|
||||
passwordHash = await bcrypt.hash(config.auth.password, 10);
|
||||
}
|
||||
|
||||
async function authenticate(username, password) {
|
||||
if (username !== config.auth.username) {
|
||||
return null;
|
||||
}
|
||||
// Comparer directement car on stocke le mot de passe en clair dans la config
|
||||
if (password !== config.auth.password) {
|
||||
return null;
|
||||
}
|
||||
const token = jwt.sign(
|
||||
{ username, role: 'admin' },
|
||||
config.jwtSecret,
|
||||
{ expiresIn: config.jwtExpiry }
|
||||
);
|
||||
return token;
|
||||
}
|
||||
|
||||
function verifyToken(token) {
|
||||
try {
|
||||
return jwt.verify(token, config.jwtSecret);
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
// Check Authorization header
|
||||
let token = null;
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
token = authHeader.substring(7);
|
||||
}
|
||||
// Check cookie
|
||||
if (!token && req.cookies) {
|
||||
token = req.cookies.dashboard_token;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Non authentifié' });
|
||||
}
|
||||
|
||||
const decoded = verifyToken(token);
|
||||
if (!decoded) {
|
||||
return res.status(401).json({ error: 'Token invalide ou expiré' });
|
||||
}
|
||||
|
||||
req.user = decoded;
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = { initAuth, authenticate, verifyToken, authMiddleware };
|
||||
Reference in New Issue
Block a user