Add super admin user management
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m46s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m46s
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { ADMIN_EMAIL, ADMIN_PASSWORD, API_KEY, JWT_SECRET } = require('./config');
|
||||
const { findUserByEmail, normalizeEmail, publicUserFields, verifyPassword } = require('./services/userService');
|
||||
|
||||
const verifyToken = (req, res, next) => {
|
||||
const authHeader = req.headers.authorization;
|
||||
@@ -15,6 +16,17 @@ const verifyToken = (req, res, next) => {
|
||||
});
|
||||
};
|
||||
|
||||
const verifySuperAdmin = (req, res, next) => {
|
||||
verifyToken(req, res, () => {
|
||||
if (req.user?.role !== 'super_admin') {
|
||||
res.status(403).json({ error: 'Super admin access required' });
|
||||
return;
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
};
|
||||
|
||||
const authenticateAPIKey = (req, res, next) => {
|
||||
const apiKey = req.headers['x-api-key'];
|
||||
if (apiKey === API_KEY) {
|
||||
@@ -25,16 +37,46 @@ const authenticateAPIKey = (req, res, next) => {
|
||||
res.status(401).json({ error: 'Unauthorized: Invalid API Key' });
|
||||
};
|
||||
|
||||
const login = (email, password) => {
|
||||
if (email !== ADMIN_EMAIL || password !== ADMIN_PASSWORD) {
|
||||
const buildTokenResponse = (user) => {
|
||||
const token = jwt.sign(
|
||||
{
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
userId: user.id || null
|
||||
},
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '24h' }
|
||||
);
|
||||
|
||||
return { token, user };
|
||||
};
|
||||
|
||||
const login = async (email, password) => {
|
||||
const normalizedEmail = normalizeEmail(email);
|
||||
|
||||
if (normalizedEmail === normalizeEmail(ADMIN_EMAIL) && password === ADMIN_PASSWORD) {
|
||||
return buildTokenResponse({
|
||||
id: null,
|
||||
name: 'Super Admin',
|
||||
email: normalizedEmail,
|
||||
role: 'super_admin'
|
||||
});
|
||||
}
|
||||
|
||||
const dbUser = await findUserByEmail(normalizedEmail);
|
||||
if (!dbUser || !dbUser.is_active || !verifyPassword(password, dbUser.password_hash)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return jwt.sign({ email }, JWT_SECRET, { expiresIn: '24h' });
|
||||
return buildTokenResponse({
|
||||
...publicUserFields(dbUser),
|
||||
role: 'user'
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
verifyToken,
|
||||
verifySuperAdmin,
|
||||
authenticateAPIKey,
|
||||
login
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user