From 7e1407cbb152ded5c406cab0d54592da6f86f512 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Fri, 23 Dec 2022 00:36:35 +0100 Subject: [PATCH] Fare procedura per cambiare gli username in giro nelle varie tabelle --- src/server/models/extralist.js | 4 +- src/server/models/graduatoria.js | 2 +- src/server/models/mailinglist.js | 4 +- src/server/models/user.js | 31 +- src/server/router/index_router.js | 3 +- src/server/router/subscribe_router.js | 2 + src/server/router/users_router.js | 521 +++++++++++++------------- src/server/tools/globalTables.js | 59 +++ 8 files changed, 352 insertions(+), 274 deletions(-) diff --git a/src/server/models/extralist.js b/src/server/models/extralist.js index cb75fb2..6815c54 100755 --- a/src/server/models/extralist.js +++ b/src/server/models/extralist.js @@ -114,7 +114,7 @@ ExtraListSchema.statics.getTotInLista = async function (idapp) { const myfind = { idapp }; - return await ExtraList.count(myfind); + return await ExtraList.countDocuments(myfind); }; ExtraListSchema.statics.getRegDellaLista = async function (idapp) { @@ -122,7 +122,7 @@ ExtraListSchema.statics.getRegDellaLista = async function (idapp) { const myfind = { idapp, registered: true }; - return await ExtraList.count(myfind); + return await ExtraList.countDocuments(myfind); }; ExtraListSchema.statics.getLastUser = function (idapp) { diff --git a/src/server/models/graduatoria.js b/src/server/models/graduatoria.js index 420ee03..7ae5af7 100755 --- a/src/server/models/graduatoria.js +++ b/src/server/models/graduatoria.js @@ -138,7 +138,7 @@ GraduatoriaSchema.statics.findByAllRecByUsername = function (idapp, username) { GraduatoriaSchema.statics.getNumDaImbarcare = async function (idapp) { const Graduatoria = this; - return await Graduatoria.count({ idapp }) + return await Graduatoria. countDocuments({ idapp }) }; diff --git a/src/server/models/mailinglist.js b/src/server/models/mailinglist.js index 707c431..2ca9a73 100755 --- a/src/server/models/mailinglist.js +++ b/src/server/models/mailinglist.js @@ -74,7 +74,7 @@ MailingListSchema.statics.getnumSent = async function (idapp, idmailinglist) { // Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit. - return await MailingList.count(myfind); + return await MailingList.countDocuments(myfind); }; MailingListSchema.statics.isOk = async function (idapp, iduser, idmailinglist) { @@ -84,7 +84,7 @@ MailingListSchema.statics.isOk = async function (idapp, iduser, idmailinglist) { // Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit. - return await MailingList.count(myfind) > 0; + return await MailingList.countDocuments(myfind) > 0; }; MailingListSchema.statics.findAllIdApp = async function (idapp) { diff --git a/src/server/models/user.js b/src/server/models/user.js index e7db9ea..4563582 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -384,14 +384,14 @@ const UserSchema = new mongoose.Schema({ _id: false, groupname: { type: String }, date: { type: Date }, - }], // username + }], mycircuits: [ { _id: false, circuitname: { type: String }, date: { type: Date }, - }], // username + }], notifs: [ { @@ -1102,7 +1102,7 @@ UserSchema.statics.isUserQualified9 = async function(idapp, username) { UserSchema.statics.getnumPaymentOk = function (idapp) { const User = this; - return await User.count({ + return await User. countDocuments({ idapp, $and: [ { @@ -3299,7 +3299,7 @@ UserSchema.statics.getUsersRegistered = async function (idapp) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersRegisteredToday = async function (idapp) { @@ -3314,7 +3314,7 @@ UserSchema.statics.getUsersRegisteredToday = async function (idapp) { date_reg: { $gt: starttoday }, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersOnLineToday = async function (idapp) { @@ -3329,7 +3329,7 @@ UserSchema.statics.getUsersOnLineToday = async function (idapp) { lasttimeonline: { $gt: starttoday }, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; /* @@ -3398,7 +3398,7 @@ UserSchema.statics.getEmailNotVerified = async function (idapp) { verified_email: false, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersTelegramAttivo = async function (idapp) { @@ -3410,7 +3410,7 @@ UserSchema.statics.getUsersTelegramAttivo = async function (idapp) { 'profile.teleg_id': { $gt: 0 }, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersAutorizzati = async function (idapp) { @@ -3423,7 +3423,7 @@ UserSchema.statics.getUsersAutorizzati = async function (idapp) { verified_by_aportador: true, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersAutorizzare = async function (idapp) { @@ -3436,7 +3436,7 @@ UserSchema.statics.getUsersAutorizzare = async function (idapp) { verified_by_aportador: { $exists: false }, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersTelegramPending = async function (idapp) { @@ -3448,7 +3448,7 @@ UserSchema.statics.getUsersTelegramPending = async function (idapp) { 'profile.teleg_checkcode': { $gt: 0 }, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getNumUsers = async function (idapp) { @@ -3459,7 +3459,7 @@ UserSchema.statics.getNumUsers = async function (idapp) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersZoom = async function (idapp) { @@ -3471,7 +3471,7 @@ UserSchema.statics.getUsersZoom = async function (idapp) { 'profile.saw_zoom_presentation': true, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersResidenti = async function (idapp) { @@ -3495,7 +3495,7 @@ UserSchema.statics.getSaw_and_Accepted = async function (idapp) { 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getUsersDreams = async function (idapp) { @@ -3508,7 +3508,7 @@ UserSchema.statics.getUsersDreams = async function (idapp) { '$expr': { '$gt': [{ '$strLenCP': '$profile.my_dream' }, 10] }, }; - return await User.count(myfind); + return await User. countDocuments(myfind); }; UserSchema.statics.getLastUsers = async function (idapp) { @@ -4303,6 +4303,7 @@ UserSchema.statics.tooManyReqPassword = async function (idapp, email, set) { }; + UserSchema.statics.createNewSubRecord = async function (idapp, req) { const User = this; diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 1642074..1ee6e2d 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -281,7 +281,7 @@ router.post('/settable', authenticate, async (req, res) => { if (req.user && req.user.username) { User.setOnLine(req.user.idapp, req.user.username); } - + let consentito = false; try { @@ -1748,6 +1748,7 @@ router.delete('/delfile', authenticate, (req, res) => { deleteFile(req, res, 0); }); + function deleteFile(req, res, version) { const relativefile = req.query.filename; const idapp = req.user.idapp; diff --git a/src/server/router/subscribe_router.js b/src/server/router/subscribe_router.js index 009d33a..b0852ff 100755 --- a/src/server/router/subscribe_router.js +++ b/src/server/router/subscribe_router.js @@ -38,6 +38,8 @@ router.post('/', authenticate, async (req, res) => { subscriptionModel.access = req.body.others.access; subscriptionModel.browser = req.get('User-Agent'); + // console.log('subscriptionModel.browser', subscriptionModel.browser); + // Find if already exist await Subscription.findOne({ userId: subscriptionModel.userId, diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 050db43..318f804 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -1,7 +1,7 @@ const express = require('express'); const router = express.Router(); -const {User} = require('../models/user'); +const { User } = require('../models/user'); // const { Nave } = require('../models/nave'); const Hours = require('../models/hours'); @@ -9,13 +9,13 @@ const Hours = require('../models/hours'); //const { ListaIngresso } = require('../models/listaingresso'); //const { Graduatoria } = require('../models/graduatoria'); // const { ExtraList } = require('../models/extralist'); -const {ObjectID} = require('mongodb'); +const { ObjectID } = require('mongodb'); const sendemail = require('../sendemail'); -const {Settings} = require('../models/settings'); +const { Settings } = require('../models/settings'); -const {SendNotif} = require('../models/sendnotif'); +const { SendNotif } = require('../models/sendnotif'); const tools = require('../tools/general'); const shared_consts = require('../tools/shared_nodejs'); @@ -28,7 +28,7 @@ const _ = require('lodash'); const reg = require('../reg/registration'); -const {authenticate} = require('../middleware/authenticate'); +const { authenticate } = require('../middleware/authenticate'); const Cart = require('../models/cart'); const CartClass = require('../modules/Cart'); @@ -36,15 +36,15 @@ const Product = require('../models/product'); const Variant = require('../models/variant'); const TypedError = require('../modules/ErrorHandler'); -const {MyGroup} = require('../models/mygroup'); -const {Circuit} = require('../models/circuit'); +const { MyGroup } = require('../models/mygroup'); +const { Circuit } = require('../models/circuit'); const mongoose = require('mongoose').set('debug', false); const Subscription = mongoose.model('subscribers'); function existSubScribe(userId, access, browser) { - return Subscription.findOne({userId, access, browser}).then(itemsub => { + return Subscription.findOne({ userId, access, browser }).then(itemsub => { return itemsub; }).catch(err => { return null; @@ -69,7 +69,7 @@ router.post('/test1', async (req, res) => { }); await sendemail.sendEmail_Registration(user.lang, user.email, user, - user.idapp, user.linkreg); + user.idapp, user.linkreg); }); @@ -105,17 +105,17 @@ router.post('/', async (req, res) => { // tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp); if (!tools.isAlphaNumericAndSpecialCharacter(body.username) || - body.email.length < 6 || - body.username.length < 6 || body.password.length < 6) { + body.email.length < 6 || + body.username.length < 6 || body.password.length < 6) { await tools.snooze(5000); console.log('Username non valido in Registrazione: ' + body.username); res.status(400). - send({code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: ''}); + send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' }); return 1; } if (tools.blockwords(body.username) || tools.blockwords(body.name) || - tools.blockwords(body.surname)) { + tools.blockwords(body.surname)) { // tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname); await tools.snooze(5000); return res.status(404).send(); @@ -155,11 +155,11 @@ router.post('/', async (req, res) => { let ris = tools.isdiffSecDateLess(lastrec.date_reg, 120); if (ris) { tools.writeIPToBan( - user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + - user.surname); + user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + + user.surname); await tools.snooze(10000); res.status(400). - send({code: server_constants.RIS_CODE_BANIP, msg: ''}); + send({ code: server_constants.RIS_CODE_BANIP, msg: '' }); return 1; } } @@ -185,29 +185,29 @@ router.post('/', async (req, res) => { // Check if already esist email or username exit = await User.findByUsername(user.idapp, user.username). - then((useralreadyexist) => { - if (useralreadyexist) { + then((useralreadyexist) => { + if (useralreadyexist) { - if (tools.getAskToVerifyReg(useralreadyexist.idapp)) { - if (!useralreadyexist.verified_by_aportador && useralreadyexist.profile.teleg_id > 0) { - if (trovarec) { - utentenonancoraVerificato = true; - } + if (tools.getAskToVerifyReg(useralreadyexist.idapp)) { + if (!useralreadyexist.verified_by_aportador && useralreadyexist.profile.teleg_id > 0) { + if (trovarec) { + utentenonancoraVerificato = true; } - } - if (!utentenonancoraVerificato) { - res.status(400). - send({ - code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST, - msg: '', - }); - return 1; - } } - }); + if (!utentenonancoraVerificato) { + res.status(400). + send({ + code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST, + msg: '', + }); + return 1; + } + } + + }); if (!utentenonancoraVerificato) { @@ -215,17 +215,17 @@ router.post('/', async (req, res) => { return; exit = await User.findByEmail(user.idapp, user.email). - then((useralreadyexist) => { - if (useralreadyexist) { - res.status(400). - send({ - code: server_constants.RIS_CODE_EMAIL_ALREADY_EXIST, - msg: '', - }); - return 1; - } + then((useralreadyexist) => { + if (useralreadyexist) { + res.status(400). + send({ + code: server_constants.RIS_CODE_EMAIL_ALREADY_EXIST, + msg: '', + }); + return 1; + } - }); + }); if (exit === 1) return; @@ -233,14 +233,14 @@ router.post('/', async (req, res) => { let recuser = null; recuser = await User.findByCellAndNameSurname(user.idapp, user.profile.cell, - user.name, user.surname); + user.name, user.surname); if (recuser && user.name !== '' && user.surname !== '' && - user.profile.cell !== '') { + user.profile.cell !== '') { console.log('UTENTE GIA ESISTENTE:\n'); console.log(user); // User already registered! res.status(400). - send({code: server_constants.RIS_CODE_USER_ALREADY_EXIST, msg: ''}); + send({ code: server_constants.RIS_CODE_USER_ALREADY_EXIST, msg: '' }); return 1; } @@ -258,14 +258,14 @@ router.post('/', async (req, res) => { if (!id_aportador && tools.getAskToVerifyReg(body.idapp)) { // Si sta tentando di registrare una persona sotto che non corrisponde! let msg = 'Il link di registrazione non sembra risultare valido.
invitante: ' + - user.aportador_solidario + '
username: ' + user.username; + user.aportador_solidario + '
username: ' + user.username; await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); res.status(400). - send({ - code: server_constants.RIS_CODE_USER_APORTADOR_NOT_VALID, - msg: '', - }); + send({ + code: server_constants.RIS_CODE_USER_APORTADOR_NOT_VALID, + msg: '', + }); return 1; } @@ -274,9 +274,9 @@ router.post('/', async (req, res) => { // Se mi sono registrato ma l'invitante non mi abilita, allora il posso registrarmi nuovamente, con lo stesso username e password, // con un'altro link di un'altro invitante ! await User.setaportador_solidario(user.idapp, user.username, - user.aportador_solidario); + user.aportador_solidario); - const myuser = await User.findOne({_id: trovarec._id}); + const myuser = await User.findOne({ _id: trovarec._id }); if (myuser) { await telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); @@ -306,44 +306,44 @@ router.post('/', async (req, res) => { return user.save().then(async () => { return User.findByUsername(user.idapp, user.username, false). - then((usertrovato) => { + then((usertrovato) => { - // tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato); - if (usertrovato !== null) { - return user.generateAuthToken(req); - } else { - res.status(400).send(); - return 0; - } - }). - then(async (token) => { - // tools.mylog("passo il TOKEN: ", token); + // tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato); + if (usertrovato !== null) { + return user.generateAuthToken(req); + } else { + res.status(400).send(); + return 0; + } + }). + then(async (token) => { + // tools.mylog("passo il TOKEN: ", token); - if (recextra) { - recextra.registered = true; - recextra.username = user.username; - await recextra.save(); + if (recextra) { + recextra.registered = true; + recextra.username = user.username; + await recextra.save(); - // await User.fixUsername(user.idapp, user.ind_order, user.username); - } - return token; - }). - then(async (token) => { + // await User.fixUsername(user.idapp, user.ind_order, user.username); + } + return token; + }). + then(async (token) => { - // tools.mylog("LINKREG = " + user.linkreg); - // Invia un'email all'utente - // tools.mylog('process.env.TESTING_ON', process.env.TESTING_ON); - console.log('res.locale', res.locale); + // tools.mylog("LINKREG = " + user.linkreg); + // Invia un'email all'utente + // tools.mylog('process.env.TESTING_ON', process.env.TESTING_ON); + console.log('res.locale', res.locale); - await telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', regexpire); + await telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', regexpire); - // if (!tools.testing()) { - await sendemail.sendEmail_Registration(user.lang, user.email, user, - user.idapp, user.linkreg); - // } - res.header('x-auth', token).send(user); - return true; - }); + // if (!tools.testing()) { + await sendemail.sendEmail_Registration(user.lang, user.email, user, + user.idapp, user.linkreg); + // } + res.header('x-auth', token).send(user); + return true; + }); }).catch((e) => { console.error(e.message); res.status(400).send(e); @@ -378,15 +378,15 @@ router.patch('/:id', authenticate, (req, res) => { if (!User.isAdmin(req.user.perm)) { // If without permissions, exit return res.status(404). - send({code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: ''}); + send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } - User.findByIdAndUpdate(id, {$set: body}).then((user) => { + User.findByIdAndUpdate(id, { $set: body }).then((user) => { tools.mylogshow(' USER TO MODIFY: ', user); if (!user) { return res.status(404).send(); } else { - res.send({code: server_constants.RIS_CODE_OK, msg: ''}); + res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); } }).catch((e) => { @@ -410,18 +410,18 @@ router.post('/profile', authenticate, (req, res) => { SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif); return User.getUserProfileByUsername(idapp, username, req.user.username, - false, req.user.perm). - then((ris) => { + false, req.user.perm). + then((ris) => { - return User.getFriendsByUsername(idapp, req.user.username). - then((friends) => { - res.send({user: ris, friends}); - }); + return User.getFriendsByUsername(idapp, req.user.username). + then((friends) => { + res.send({ user: ris, friends }); + }); - }).catch((e) => { - tools.mylog('ERRORE IN Profile: ' + e.message); - res.status(400).send(); - }); + }).catch((e) => { + tools.mylog('ERRORE IN Profile: ' + e.message); + res.status(400).send(); + }); } catch (e) { tools.mylogserr('Error profile: ', e); res.status(400).send(); @@ -437,27 +437,27 @@ router.post('/panel', authenticate, async (req, res) => { if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) { // If without permissions, exit return res.status(404). - send({code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: ''}); + send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } try { - const myuser = await User.findOne({idapp, username}, - { - username: 1, - name: 1, - surname: 1, - email: 1, - verified_by_aportador: 1, - aportador_solidario: 1, - lasttimeonline: 1, - deleted: 1, - sospeso: 1, - blocked: 1, - reported: 1, - username_who_report: 1, - date_report: 1, - profile: 1, - }).lean(); + const myuser = await User.findOne({ idapp, username }, + { + username: 1, + name: 1, + surname: 1, + email: 1, + verified_by_aportador: 1, + aportador_solidario: 1, + lasttimeonline: 1, + deleted: 1, + sospeso: 1, + blocked: 1, + reported: 1, + username_who_report: 1, + date_report: 1, + profile: 1, + }).lean(); if (!!myuser) { res.send(myuser); } else { @@ -502,7 +502,7 @@ router.post('/notifs', authenticate, async (req, res) => { router.post('/login', (req, res) => { var body = _.pick(req.body, - ['username', 'password', 'idapp', 'keyappid', 'lang']); + ['username', 'password', 'idapp', 'keyappid', 'lang']); var user = new User(body); // const subs = _.pick(req.body, ['subs']); @@ -516,86 +516,86 @@ router.post('/login', (req, res) => { let resalreadysent = false; User.findByCredentials(user.idapp, user.username, user.password). - then(async (user) => { - // tools.mylog("CREDENZIALI ! "); - if (!user) { - await tools.snooze(3000); - const msg = 'Tentativo di Login ERRATO [' + body.username + ' , ' + - body.password + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + - ']'; - tools.mylogshow(msg); - tools.writeErrorLog(msg); - // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg); - res.status(404).send({code: server_constants.RIS_CODE_LOGIN_ERR}); - } - return user; - }). - then(user => { - // console.log('Lgn-Ok'); - if (user) { - return user.generateAuthToken(req).then((token) => { - var usertosend = new User(); + then(async (user) => { + // tools.mylog("CREDENZIALI ! "); + if (!user) { + await tools.snooze(3000); + const msg = 'Tentativo di Login ERRATO [' + body.username + ' , ' + + body.password + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + + ']'; + tools.mylogshow(msg); + tools.writeErrorLog(msg); + // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg); + res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR }); + } + return user; + }). + then(user => { + // console.log('Lgn-Ok'); + if (user) { + return user.generateAuthToken(req).then((token) => { + var usertosend = new User(); - shared_consts.fieldsUserToChange().forEach((field) => { - usertosend[field] = user[field]; - }); - - // usertosend._id = user._id.toHexString(); - // if (!User.isAdmin(req.user)) { - // usertosend.ipaddr = user.ipaddr; - // } - - // tools.mylog("user.verified_email:" + user.verified_email); - // tools.mylog("usertosend.userId", usertosend.userId); - - return {usertosend, token}; - - }).then((myris) => { - const access = 'auth'; - const browser = req.get('User-Agent'); - - // Check if already exist Subscribe - return existSubScribe(myris.usertosend._id, access, browser). - then(subscribe => { - return (subscribe !== null); - }). - then(subsExistonDb => { - // console.log('ESEGUITO OK') - return { - usertosend: myris.usertosend, - token: myris.token, - subsExistonDb, - }; - }). - catch(err => { - return { - usertosend: myris.usertosend, - token: myris.token, - subsExistonDb: false, - }; - }); - }).then(myris => { - // console.log('res', myris.token, myris.usertosend); - - // SEND TOKEN AND CODE RESULT - return res.header('x-auth', myris.token).send({ - usertosend: myris.usertosend, - code: server_constants.RIS_CODE_OK, - subsExistonDb: myris.subsExistonDb, - }); - - // tools.mylog("TROVATOOO!"); - - // tools.mylog('FINE LOGIN') + shared_consts.fieldsUserToChange().forEach((field) => { + usertosend[field] = user[field]; }); - } - }). - catch((e) => { - console.error('ERRORE IN LOGIN: ' + e.message); - if (!resalreadysent) - res.status(400). - send({code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC}); - }); + + // usertosend._id = user._id.toHexString(); + // if (!User.isAdmin(req.user)) { + // usertosend.ipaddr = user.ipaddr; + // } + + // tools.mylog("user.verified_email:" + user.verified_email); + // tools.mylog("usertosend.userId", usertosend.userId); + + return { usertosend, token }; + + }).then((myris) => { + const access = 'auth'; + const browser = req.get('User-Agent'); + + // Check if already exist Subscribe + return existSubScribe(myris.usertosend._id, access, browser). + then(subscribe => { + return (subscribe !== null); + }). + then(subsExistonDb => { + // console.log('ESEGUITO OK') + return { + usertosend: myris.usertosend, + token: myris.token, + subsExistonDb, + }; + }). + catch(err => { + return { + usertosend: myris.usertosend, + token: myris.token, + subsExistonDb: false, + }; + }); + }).then(myris => { + // console.log('res', myris.token, myris.usertosend); + + // SEND TOKEN AND CODE RESULT + return res.header('x-auth', myris.token).send({ + usertosend: myris.usertosend, + code: server_constants.RIS_CODE_OK, + subsExistonDb: myris.subsExistonDb, + }); + + // tools.mylog("TROVATOOO!"); + + // tools.mylog('FINE LOGIN') + }); + } + }). + catch((e) => { + console.error('ERRORE IN LOGIN: ' + e.message); + if (!resalreadysent) + res.status(400). + send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC }); + }); }); router.delete('/me/token', authenticate, (req, res) => { @@ -685,7 +685,7 @@ router.post('/friends/cmd', authenticate, async (req, res) => { // If without permissions, exit if (usernameOrig !== usernameLogged) { return res.status(404). - send({code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: ''}); + send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } } @@ -693,13 +693,13 @@ router.post('/friends/cmd', authenticate, async (req, res) => { usernameDest = await User.getRealUsernameByUsername(idapp, usernameDest); return User.setFriendsCmd(req, idapp, usernameOrig, usernameDest, cmd, value). - then((ris) => { - res.send(ris); - }). - catch((e) => { - tools.mylog('ERRORE IN Friends/cmd: ' + e.message); - res.status(400).send(); - }); + then((ris) => { + res.send(ris); + }). + catch((e) => { + tools.mylog('ERRORE IN Friends/cmd: ' + e.message); + res.status(400).send(); + }); }); @@ -721,13 +721,13 @@ router.post('/groups/cmd', authenticate, (req, res) => { }*/ return User.setGroupsCmd(idapp, usernameOrig, groupnameDest, cmd, value, usernameLogged). - then((ris) => { - res.send(ris); - }). - catch((e) => { - tools.mylog('ERRORE IN groups/cmd: ' + e.message); - res.status(400).send(); - }); + then((ris) => { + res.send(ris); + }). + catch((e) => { + tools.mylog('ERRORE IN groups/cmd: ' + e.message); + res.status(400).send(); + }); }); @@ -741,6 +741,7 @@ router.post('/circuits/cmd', authenticate, async (req, res) => { const value = req.body.value; const extrarec = req.body.extrarec; + /*if (!User.isAdmin(req.user.perm) || !User.isManager(req.user.perm)) { // If without permissions, exit if (usernameOrig !== usernameLogged) { @@ -750,29 +751,31 @@ router.post('/circuits/cmd', authenticate, async (req, res) => { }*/ return await User.setCircuitCmd(idapp, usernameOrig, circuitname, cmd, value, usernameLogged, extrarec). - then(async (ris) => { + then(async (ris) => { - // Check if ìs a Notif to read - if (extrarec && extrarec.hasOwnProperty('idnotif')) { - const idnotif = extrarec['idnotif'] ? extrarec['idnotif'] : ''; - await SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif); - } + // Check if ìs a Notif to read + if (extrarec && extrarec.hasOwnProperty('idnotif')) { + const idnotif = extrarec['idnotif'] ? extrarec['idnotif'] : ''; + await SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif); + } - return res.send(ris); - }). - catch((e) => { - tools.mylog('ERRORE IN circuits/cmd: ' + e.message); - res.status(400).send(); - }); + return res.send(ris); + }). + catch((e) => { + tools.mylog('ERRORE IN circuits/cmd: ' + e.message); + res.status(400).send(); + }); }); -async function eseguiDbOp(idapp, mydata, locale) { +async function eseguiDbOp(idapp, mydata, locale, req, res) { let ris = await User.DbOp(idapp, mydata); const populate = require('../populate/populate'); + const globalTables = require('../tools/globalTables'); + let mystr = ''; try { @@ -1015,7 +1018,7 @@ async function eseguiDbOp(idapp, mydata, locale) { } else if (mydata.dbop === 'creaUtentiTest') { let num = 0; - lastrec = await User.find({idapp}).sort({_id: -1}).limit(1); + lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); let last = 1; if (lastrec) { last = lastrec[0].index; @@ -1045,7 +1048,7 @@ async function eseguiDbOp(idapp, mydata, locale) { num++; } - ris = {num}; + ris = { num }; /*} else if (mydata.dbop === 'visuPlacca') { mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + @@ -1081,6 +1084,12 @@ async function eseguiDbOp(idapp, mydata, locale) { ris = populate.rewriteTable('contribtypes'); + } else if (mydata.dbop === 'ReplaceUsername') { + + if (User.isAdmin(req.user.perm)) { + ris = globalTables.replaceUsername(req.body.idapp, mydata.search_username, mydata.replace_username); + } + } else if (mydata.dbop === 'copyFrom1To14') { const idapporig = 1; const idappdest = 14; @@ -1106,11 +1115,11 @@ async function eseguiDbOp(idapp, mydata, locale) { tools.mylogshow('copyfromapptoapp: ', table, mytable); await mytable.DuplicateAllRecords(idapporig, idappdest). - then((numrec) => { - // tools.mylogshow(' REC TO MODIFY: ', rec); - if (numrec) - numrectot += numrec; - }); + then((numrec) => { + // tools.mylogshow(' REC TO MODIFY: ', rec); + if (numrec) + numrectot += numrec; + }); } ris = true; @@ -1121,10 +1130,10 @@ async function eseguiDbOp(idapp, mydata, locale) { } else if (mydata.dbop === 'emptyTabCatServiziBeni') { - const {Sector} = require('../models/sector'); - const {SectorGood} = require('../models/sectorgood'); - const {Skill} = require('../models/skill'); - const {Good} = require('../models/good'); + const { Sector } = require('../models/sector'); + const { SectorGood } = require('../models/sectorgood'); + const { Skill } = require('../models/skill'); + const { Good } = require('../models/good'); await Sector.deleteMany({}); await SectorGood.deleteMany({}); @@ -1135,16 +1144,16 @@ async function eseguiDbOp(idapp, mydata, locale) { // Svuota e Ricrea - const {Sector} = require('../models/sector'); - const {SectorGood} = require('../models/sectorgood'); - const {Skill} = require('../models/skill'); - const {Good} = require('../models/good'); - const {SubSkill} = require('../models/subskill'); - const {Contribtype} = require('../models/contribtype'); - const {AdType} = require('../models/adtype'); - const {AdTypeGood} = require('../models/adtypegood'); - const {StatusSkill} = require('../models/statusSkill'); - const {CatGrp} = require('../models/catgrp'); + const { Sector } = require('../models/sector'); + const { SectorGood } = require('../models/sectorgood'); + const { Skill } = require('../models/skill'); + const { Good } = require('../models/good'); + const { SubSkill } = require('../models/subskill'); + const { Contribtype } = require('../models/contribtype'); + const { AdType } = require('../models/adtype'); + const { AdTypeGood } = require('../models/adtypegood'); + const { StatusSkill } = require('../models/statusSkill'); + const { CatGrp } = require('../models/catgrp'); await Sector.deleteMany({}); await SectorGood.deleteMany({}); @@ -1163,8 +1172,8 @@ async function eseguiDbOp(idapp, mydata, locale) { // Svuota e Ricrea - const {City} = require('../models/city'); - const {Province} = require('../models/province'); + const { City } = require('../models/city'); + const { Province } = require('../models/province'); await City.deleteMany({}); await Province.deleteMany({}); @@ -1188,8 +1197,8 @@ async function eseguiDbOp(idapp, mydata, locale) { } else if (mydata.dbop === 'emptyCityProvinces') { - const {City} = require('../models/city'); - const {Province} = require('../models/province'); + const { City } = require('../models/city'); + const { Province } = require('../models/province'); await City.remove({}); await Province.remove({}); @@ -1236,13 +1245,19 @@ router.post('/dbop', authenticate, async (req, res) => { idapp = req.body.idapp; locale = req.body.locale; + if (!User.isAdmin(req.user.perm)) { + // If without permissions, exit + return res.status(404). + send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + } + try { - const ris = await eseguiDbOp(idapp, mydata, locale); + const ris = await eseguiDbOp(idapp, mydata, locale, req, res); res.send(ris); } catch (e) { - res.status(400).send({code: server_constants.RIS_CODE_ERR, msg: e}); + res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); console.log(e.message); } @@ -1256,13 +1271,13 @@ router.post('/mgt', authenticate, async (req, res) => { locale = req.body.locale; try { - const {nummsgsent, numrec, textsent, text} = await telegrambot.sendMsgFromSiteToBotTelegram(idapp, req.user, mydata); + const { nummsgsent, numrec, textsent, text } = await telegrambot.sendMsgFromSiteToBotTelegram(idapp, req.user, mydata); - return res.send({numrec, nummsgsent, textsent, text}); + return res.send({ numrec, nummsgsent, textsent, text }); } catch (e) { res.status(400).send(); - res.send({code: server_constants.RIS_CODE_ERR, msg: e}); + res.send({ code: server_constants.RIS_CODE_ERR, msg: e }); console.log(e.message); } diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index f437127..daf7446 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -438,4 +438,63 @@ module.exports = { return await this.SendMsgToParam(idapp, params); }, + replaceUsername: async function (idapp, search_username, replace_username) { + + try { + let ris = null; + console.log('replaceUsername = ', search_username, replace_username); + + ris = await User.findOneAndUpdate({ idapp, username: search_username }, { $set: { username: replace_username } }); + console.log('username result = ', ris); + + ris = await User.findOneAndUpdate({ idapp, 'profile.username_telegram': search_username }, { $set: { 'profile.username_telegram': replace_username } }); + console.log('profile.username_telegram result = ', ris); + + ris = await User.updateOne({ idapp, 'profile.friends.username': search_username }, + { + $set: + { 'profile.friends.$.username': replace_username } + }); + console.log('friends.username result = ', ris); + + ris = await User.updateOne({ idapp, 'profile.req_friends.username': search_username }, + { + $set: + { 'profile.req_friends.$.username': replace_username } + }); + console.log('req_friends.username result = ', ris); + + ris = await Circuit.updateOne({ idapp, 'admins.username': search_username }, + { $set: { 'admins.$.username': replace_username } }); + console.log('Circuit.admins.username result = ', ris); + + ris = await Circuit.updateOne({ idapp, 'req_users.username': search_username }, + { $set: { 'req_users.$.username': replace_username } }); + console.log('Circuit.req_users.username result = ', ris); + + ris = await Circuit.updateOne({ idapp, 'refused_users.username': search_username }, + { $set: { 'refused_users.$.username': replace_username } }); + console.log('Circuit.refused_users.username result = ', ris); + + ris = await MyGroup.updateOne({ idapp, 'admins.username': search_username }, + { $set: { 'admins.$.username': replace_username } }); + console.log('MyGroup.refused_users.username result = ', ris); + + ris = await MyGroup.updateOne({ idapp, 'req_users.username': search_username }, + { $set: { 'req_users.$.username': replace_username } }); + console.log('MyGroup.req_users.username result = ', ris); + + // MyGroup.refused_users.username + ris = await MyGroup.updateOne({ idapp, 'refused_users.username': search_username }, + { $set: { 'refused_users.$.username': replace_username } }); + console.log('MyGroup.refused_users.username result = ', ris); + + + } catch (e) { + console.error(e); + } + + }, + + };