- aggiunto Elena come admin di tutti i circuiti ...

shared_consts.USER_ADMIN_CIRCUITS
This commit is contained in:
Surya Paolo
2025-10-27 13:34:06 +01:00
parent 8f54cd2791
commit 38c13eef28
5 changed files with 119 additions and 97 deletions

View File

@@ -285,7 +285,7 @@ CircuitSchema.statics.isCircuitAdmin = async function (idrec, username) {
const mycirc = await Circuit.findOne({ _id: idrec }).lean();
if (mycirc) {
return mycirc.admins.some(admin => (admin.username === username) || (admin.username === shared_consts.USER_ADMIN_CIRCUITS));
return mycirc.admins.some(admin => (admin.username === username) || (shared_consts.USER_ADMIN_CIRCUITS.includes(admin.username)));
}
return false;
@@ -1018,7 +1018,7 @@ CircuitSchema.statics.getListAdminsByCircuitPath = async function (idapp, circui
let myarr = arr && arr.admins ? arr.admins : [];
return [...myarr, shared_consts.USER_ADMIN_CIRCUITS]
return [...myarr, ...shared_consts.USER_ADMIN_CIRCUITS]
};
@@ -1154,7 +1154,7 @@ CircuitSchema.statics.createCircuitIfNotExist = async function (req, idapp, prov
totTransato: 0,
totCircolante: 0,
date_created: new Date(),
admins: [{ username: useradmin }],
admins: useradmin.map(username => ({ username })),
askManagerToEnter: false,
sendEmailAfterAskingToEnter: false,
circuitoIndipendente: false,
@@ -1223,7 +1223,7 @@ CircuitSchema.statics.isAdminCircuit = async function (idapp, circuitname, usern
if (arr) {
for (const admin of arr.admins) {
if ((admin.username === username) || (shared_consts.USER_ADMIN_CIRCUITS === username))
if (shared_consts.USER_ADMIN_CIRCUITS.includes(username) || (admin.username === username))
return true;
}
}

View File

@@ -777,19 +777,60 @@ UserSchema.statics.isFacilitatore = function (perm) {
* The status code reflects the validity of the token: valid, expired, or invalid.
*/
// Funzione helper separata per trovare l'utente
async function findUserByTokenAndAccess(User, decoded, token, typeaccess, withuser, withlean, project) {
try {
const query = {
_id: decoded._id,
tokens: {
$elemMatch: {
token,
access: typeaccess,
},
},
};
if (withuser && !withlean) {
return await User.findOne(query, project);
}
return await User.findOne(query, project).lean();
} catch (err) {
console.warn('Errore con decoded._id, provo con decoded.smart:', err.message);
// Fallback: usa decoded.smart
const query = {
_id: decoded.smart,
tokens: {
$elemMatch: {
token,
access: typeaccess,
},
},
};
if (withuser && !withlean) {
return await User.findOne(query, project);
}
return await User.findOne(query, project).lean();
}
}
// Funzione principale refactored
UserSchema.statics.findByToken = async function (token, typeaccess, con_auth, withuser, withlean = false) {
const User = this;
let code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
let user = null;
let decoded;
const start = process.hrtime.bigint();
const start_jwt = process.hrtime.bigint();
// Validazione token
if (!token) {
console.warn('TOKEN VUOTO ! ');
console.warn('TOKEN VUOTO!');
return { user, code };
}
// Verifica JWT
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
code = server_constants.RIS_CODE_OK;
@@ -803,83 +844,32 @@ UserSchema.statics.findByToken = async function (token, typeaccess, con_auth, wi
return { user: null, code };
}
const end_jwt = process.hrtime.bigint();
// console.log(` jwt.verify impiega ${Math.round(Number(end_jwt - start_jwt) / 1e6) / 1000} secondi.`);
// Definizione projection
const project = withuser ? undefined : {
perm: 1,
_id: 1,
idapp: 1,
username: 1,
deleted: 1,
aportador_solidario: 1,
aportador_solidario_nome_completo: 1,
'profile.socioresidente': 1,
};
let project = undefined;
if (withuser) {
const start_find = process.hrtime.bigint();
if (withlean) {
user = await User.findOne(
{
_id: decoded._id,
tokens: {
$elemMatch: {
token,
access: typeaccess,
},
},
},
project
).lean();
} else {
user = await User.findOne(
{
_id: decoded._id,
tokens: {
$elemMatch: {
token,
access: typeaccess,
},
},
},
project
);
}
const end_find = process.hrtime.bigint();
// console.log(` User.findOne impiega ${Math.round(Number(end_find - start_find) / 1e6) / 1000} secondi.`);
} else {
project = {
perm: 1,
_id: 1,
idapp: 1,
username: 1,
deleted: 1,
aportador_solidario: 1,
aportador_solidario_nome_completo: 1,
'profile.socioresidente': 1,
};
const start_find = process.hrtime.bigint();
user = await User.findOne(
{
_id: decoded._id,
tokens: {
$elemMatch: {
token,
access: typeaccess,
},
},
},
project
).lean();
const end_find = process.hrtime.bigint();
// console.log(` User.findOne LEAN impiega ${Math.round(Number(end_find - start_find) / 1e6) / 1000} secondi.`);
}
// Ricerca utente con funzione separata
user = await findUserByTokenAndAccess(User, decoded, token, typeaccess, withuser, withlean, project);
// Verifica scadenza token per idapp specifici
if (user) {
const checkExpiry = tools.getEnableTokenExpiredByIdApp(user.idapp);
const currentTime = Date.now() / 1000;
if (checkExpiry && decoded.exp < currentTime) {
console.log('Il token è scaduto, generazione del nuovo token...');
code = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED;
}
}
// const end = process.hrtime.bigint();
// console.log(` findByToken impiega ${Math.round(Number(end - start) / 1e6) / 1000} secondi.`);
return { user, code };
};
@@ -900,7 +890,7 @@ UserSchema.statics.findByTokenAnyAccess = function (token) {
}).lean();
};
UserSchema.statics.findByRefreshTokenAnyAccess = function (refreshToken) {
UserSchema.statics.findByRefreshTokenAnyAccess = async function (refreshToken) {
const User = this;
let decoded;
@@ -911,12 +901,25 @@ UserSchema.statics.findByRefreshTokenAnyAccess = function (refreshToken) {
return Promise.resolve(null);
}
return User.findOne({
_id: decoded._id,
'tokens.refreshToken': refreshToken,
});
let ris = null;
if (decoded) {
try {
ris = await User.findOne({
_id: decoded._id,
'tokens.refreshToken': refreshToken,
});
} catch (e) {
ris = await User.findOne({
_id: decoded.smart,
'tokens.refreshToken': refreshToken,
});
}
}
};
UserSchema.statics.findByCredentials = async function (idapp, username, password, pwdcrypted) {
const User = this;
let pwd = '';

View File

@@ -20,19 +20,18 @@ const _ = require('lodash');
const { ObjectId } = require('mongodb');
async function getCircuitRecAdminsInfo(idapp, data) {
try {
if (data && data.admins) {
for (const admin of data.admins) {
const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
if (myuser && myuser.profile)
admin.profile = { img: myuser.profile.img };
if (myuser && myuser.profile) admin.profile = { img: myuser.profile.img };
}
if (data.admins.length === 0) {
data.admins.push({username: shared_consts.USER_ADMIN_CIRCUITS})
for (const admin of shared_consts.USER_ADMIN_CIRCUITS) {
data.admins.push({ username: admin });
}
}
}
} catch (e) {
console.error(e);
@@ -48,7 +47,6 @@ router.post('/load', authenticate, async (req, res) => {
const usernameOrig = req.user.username;
try {
const { SendNotif } = require('../models/sendnotif');
const { Movement } = require('../models/movement');
@@ -80,7 +78,7 @@ router.post('/load', authenticate, async (req, res) => {
if (data === null) {
data = null;
}
const users_in_circuit = await Circuit.getUsersSingleCircuit(idapp, req.user.username, data.name, data._id);
data = await getCircuitRecAdminsInfo(idapp, data);
@@ -94,11 +92,23 @@ router.post('/load', authenticate, async (req, res) => {
}
let arrrecnotifcoins = null;
const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(req.user.username, lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER, shared_consts.QualiNotifs.OTHERS);
const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(
req.user.username,
lastdr,
idapp,
shared_consts.LIMIT_NOTIF_FOR_USER,
shared_consts.QualiNotifs.OTHERS
);
if (User.isAdminById(req.user.id)) {
arrrecnotifcoins = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp);
} else {
arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(req.user.username, lastdr, idapp, shared_consts.LIMIT_NOTIFCOINS_FOR_USER, shared_consts.QualiNotifs.CIRCUITS);
arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(
req.user.username,
lastdr,
idapp,
shared_consts.LIMIT_NOTIFCOINS_FOR_USER,
shared_consts.QualiNotifs.CIRCUITS
);
}
/// E' QUIIII !!!!
const useraccounts = await Account.getUserAccounts(idapp, req.user.username);
@@ -106,14 +116,12 @@ router.post('/load', authenticate, async (req, res) => {
await User.setLastCircuitOpened(idapp, req.user.username, path);
res.send({ circuit: data, users_in_circuit, arrrecnotif, arrrecnotifcoins, useraccounts });
} catch (e) {
console.error('Error in Circuits', e);
return res.status(400).send(e);
}
const ris = null;
});
module.exports = router;

View File

@@ -1138,7 +1138,7 @@ module.exports = {
groupname,
myrecgroup._id,
'',
'',
''
);
onlysave = false;
} else if (cmd === shared_consts.GROUPSCMD.BLOCK_USER) {
@@ -1463,10 +1463,21 @@ module.exports = {
}
},
// VERSIONE CORRETTA - USER_ADMIN_CIRCUITS è un array
getAdminsByCircuit(circuit) {
// return circuit.admins
const adminsMap = new Map();
return [...circuit.admins, { username: shared_consts.USER_ADMIN_CIRCUITS }];
// Aggiungi gli admin esistenti
circuit.admins.forEach((admin) => {
adminsMap.set(admin.username, admin);
});
// Aggiungi gli admin dei circuiti dall'array (sovrascrive se esistono già)
shared_consts.USER_ADMIN_CIRCUITS.forEach((username) => {
adminsMap.set(username, { username });
});
return Array.from(adminsMap.values());
},
sendNotificationByCircuit: async function (
@@ -6093,10 +6104,10 @@ module.exports = {
}
if (aggiornatoimg?.filepath?.includes('noimg.jpg')) {
// nascondi il prodotto se non trovo l'immagine !
// await Product.updateOne({ _id: product._id }, { $set: { deleted: true } });
aggiornatoimg = { ris: false, deleted: true };
// nascondi il prodotto se non trovo l'immagine !
// await Product.updateOne({ _id: product._id }, { $set: { deleted: true } });
aggiornatoimg = { ris: false, deleted: true };
}
if (aggiornatoimg?.filepath) {

View File

@@ -1,5 +1,5 @@
module.exports = {
USER_ADMIN_CIRCUITS: 'surya1977',
USER_ADMIN_CIRCUITS: ['surya1977', 'elenaEspx'],
ADMIN_USER_SERVER: 'surya1977',
Accepted: {
CHECK_READ_GUIDELINES: 1,