Files
freeplanet_serverside/src/server/models/user.js

745 lines
16 KiB
JavaScript
Raw Normal View History

const bcrypt = require('bcryptjs');
2018-12-24 20:31:02 +01:00
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const tools = require('../tools/general');
const { Settings } = require('../models/settings');
const shared_consts = require('../tools/shared_nodejs');
const queryclass = require('../classes/queryclass');
2019-02-05 03:40:22 +01:00
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
2019-03-04 19:18:54 +01:00
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
2018-12-24 20:31:02 +01:00
2018-12-27 20:09:40 +01:00
mongoose.set('debug', process.env.DEBUG);
const UserSchema = new mongoose.Schema({
2019-02-05 03:40:22 +01:00
userId: {
type: String,
},
2018-12-24 20:31:02 +01:00
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: false,
/*validate: {
2018-12-24 20:31:02 +01:00
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}*/
2018-12-24 20:31:02 +01:00
},
idapp: {
type: String,
2018-12-24 20:31:02 +01:00
required: true,
},
ind_order: {
type: Number
},
2018-12-24 20:31:02 +01:00
username: {
type: String,
required: true,
trim: true,
minlength: 6,
unique: false,
2018-12-24 20:31:02 +01:00
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
2018-12-24 20:31:02 +01:00
password: {
type: String,
require: true,
minlength: 6,
},
lang: {
type: String,
require: true,
},
linkreg: {
type: String,
2019-02-06 18:48:32 +01:00
required: false
2018-12-24 20:31:02 +01:00
},
verified_email: {
type: Boolean,
},
2019-12-31 00:44:53 +01:00
made_gift: {
type: Boolean,
},
2018-12-24 20:31:02 +01:00
tokens: [{
access: {
type: String,
required: true
},
browser: {
type: String,
required: true
},
2018-12-24 20:31:02 +01:00
token: {
type: String,
required: true
},
date_login: {
type: Date
},
2018-12-24 20:31:02 +01:00
}],
perm: {
type: Number
},
ipaddr: {
type: String,
},
date_reg: {
type: Date,
},
date_temp_reg: {
type: Date,
},
2018-12-24 20:31:02 +01:00
date_tokenforgot: {
type: Date
},
tokenforgot: {
type: String,
},
lasttimeonline: {
type: Date
},
news_on: {
type: Boolean
},
aportador_solidario: {
type: String,
},
aportador_solidario_nome_completo: {
type: String,
},
aportador_solidario_ind_order: {
type: Number,
},
note: {
type: String,
},
profile: {
img: {
type: String
},
2019-12-29 23:30:49 +01:00
nationality: {
type: String
},
intcode_cell: {
type: String
},
iso2_cell: {
type: String
},
cell: {
type: String
},
2019-12-31 00:44:53 +01:00
country_pay: {
type: String
},
email_paypal: {
type: String
},
paymenttypes: [],
username_telegram: {
type: String
},
teleg_id: {
type: Number
},
teleg_checkcode: {
type: Number
},
2020-01-03 22:02:18 +01:00
manage_telegram: {
type: Boolean
},
dateofbirth: {
type: Date,
},
my_dream: {
type: String,
},
saw_zoom_presentation: {
type: Boolean
},
sex: {
type: Number,
},
},
2018-12-24 20:31:02 +01:00
});
UserSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject();
2018-12-24 20:31:02 +01:00
return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
2018-12-24 20:31:02 +01:00
};
UserSchema.methods.generateAuthToken = function (req) {
// console.log("GENERA TOKEN : ");
const user = this;
const useragent = req.get('User-Agent');
2019-12-31 00:44:53 +01:00
// tools.mylog("GENERATE USER-AGENT = ", useragent);
const access = 'auth';
const browser = useragent;
const token = jwt.sign({ _id: user._id.toHexString(), access }, process.env.SIGNCODE).toString();
const date_login = new Date();
2018-12-24 20:31:02 +01:00
// CANCELLA IL PRECEDENTE !
2019-03-04 19:18:54 +01:00
user.tokens = user.tokens.filter(function (tok) {
return (tok.access !== access) || ((tok.access === access) && (tok.browser !== browser));
});
user.tokens.push({ access, browser, token, date_login });
user.lasttimeonline = new Date();
return user.save()
.then(() => {
2019-12-31 00:44:53 +01:00
// console.log("TOKEN CREATO IN LOGIN : " + token);
return token;
})
.catch(err => {
console.log("Error", err.message);
});
2018-12-24 20:31:02 +01:00
};
UserSchema.statics.setPermissionsById = function (id, perm) {
const user = this;
return user.findByIdAndUpdate(id, { $set: { perm } }).then((user) => {
if (user)
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
else
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
});
};
UserSchema.statics.isAdmin = function (perm) {
try {
2020-01-03 22:02:18 +01:00
return ((perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
} catch (e) {
return false
}
};
2020-01-03 22:02:18 +01:00
UserSchema.statics.isManager = function (perm) {
try {
2020-01-03 22:02:18 +01:00
return ((perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
} catch (e) {
return false
}
};
UserSchema.statics.findByToken = function (token, typeaccess) {
const User = this;
let decoded;
2018-12-24 20:31:02 +01:00
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
} catch (e) {
return Promise.resolve(null);
2018-12-24 20:31:02 +01:00
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
'tokens.access': typeaccess,
2018-12-24 20:31:02 +01:00
});
};
2019-02-13 18:47:58 +01:00
UserSchema.statics.findByTokenAnyAccess = function (token) {
const User = this;
let decoded;
2019-02-13 18:47:58 +01:00
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
} catch (e) {
return Promise.resolve(null);
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
});
};
UserSchema.statics.findByCredentials = function (idapp, username, password) {
const User = this;
let pwd = "";
2018-12-24 20:31:02 +01:00
return User.findOne({ idapp, username: username }).then((user) => {
2018-12-24 20:31:02 +01:00
if (!user) {
2019-03-04 19:18:54 +01:00
// Check if with email:
return User.findOne({ idapp, email: username })
2019-03-04 19:18:54 +01:00
} else {
return user
2018-12-24 20:31:02 +01:00
}
2019-03-04 19:18:54 +01:00
}).then(user => {
if (!user)
return null;
2018-12-24 20:31:02 +01:00
pwd = user.password;
return new Promise((resolve, reject) => {
// Use bcrypt.compare to compare password and user.password
// console.log("pwd1 " + password);
// console.log("pwd2 " + pwd);
2018-12-24 20:31:02 +01:00
bcrypt.compare(password, pwd, (err, res) => {
if (res) {
resolve(user);
} else {
return resolve(null);
}
});
});
});
};
UserSchema.statics.findByUsername = function (idapp, username) {
const User = this;
2018-12-24 20:31:02 +01:00
return User.findOne({
'idapp': idapp,
2018-12-24 20:31:02 +01:00
'username': username,
});
};
2019-12-31 00:44:53 +01:00
UserSchema.statics.getUserShortDataByUsername = function (idapp, username) {
const User = this;
return User.findOne({
'idapp': idapp,
'username': username,
}, {
username: 1,
name: 1,
surname: 1,
verified_email: 1,
made_gift: 1,
email: 1,
date_reg: 1,
img: 1
}).then((ris) => {
if (!!ris) {
// console.log('ris', ris);
if (!!ris._doc)
return ris._doc;
else
return null;
}
});
};
UserSchema.statics.getDownlineByUsername = function (idapp, username) {
const User = this;
return User.find({
'idapp': idapp,
'aportador_solidario': username,
}, {
username: 1,
name: 1,
surname: 1,
verified_email: 1,
made_gift: 1,
2019-12-31 00:44:53 +01:00
email: 1,
date_reg: 1,
img: 1
}, (err, arrrec) => {
return arrrec
});
};
UserSchema.statics.getnumInvitatiAttivi = function (idapp, username) {
const User = this;
return User.count({
idapp,
aportador_solidario: username,
teleg_id: { $gt: 1 },
saw_zoom_presentation: true,
});
};
UserSchema.statics.getnumInvitati = function (idapp, username) {
const User = this;
return User.count({
idapp,
aportador_solidario: username,
});
};
2018-12-24 20:31:02 +01:00
UserSchema.statics.findByLinkreg = function (idapp, linkreg) {
const User = this;
2018-12-24 20:31:02 +01:00
return User.findOne({
'linkreg': linkreg,
'idapp': idapp,
});
};
UserSchema.statics.findByLinkTokenforgot = function (idapp, email, tokenforgot) {
const User = this;
2018-12-24 20:31:02 +01:00
return User.findOne({
'email': email,
'tokenforgot': tokenforgot,
'date_tokenforgot': { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa!
2018-12-24 20:31:02 +01:00
'idapp': idapp,
});
};
UserSchema.statics.findByEmail = function (idapp, email) {
const User = this;
2018-12-24 20:31:02 +01:00
return User.findOne({
'idapp': idapp,
2018-12-24 20:31:02 +01:00
'email': email,
});
};
UserSchema.pre('save', function (next) {
const user = this;
2018-12-24 20:31:02 +01:00
2018-12-24 20:31:02 +01:00
/*
if (user.isModified('password')) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
next();
});
});
} else {
next();
}
*/
next();
});
UserSchema.methods.removeToken = function (token) {
const user = this;
2018-12-24 20:31:02 +01:00
return user.updateOne({
2018-12-24 20:31:02 +01:00
$pull: {
tokens: { token }
2018-12-24 20:31:02 +01:00
}
});
};
UserSchema.statics.getEmailByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username })
.then((arrrec) => {
return ((arrrec) ? arrrec.email : '');
}).catch((e) => {
console.error('getEmailByUsername', e);
});
};
UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) {
const User = this;
return await User.findOne({ idapp, 'profile.teleg_id': teleg_id })
.then((rec) => {
return (!!rec) ? rec._doc : null;
}).catch((e) => {
console.error('UserExistByIdTelegram', e);
});
};
2020-01-03 22:02:18 +01:00
UserSchema.statics.TelegIdByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, { 'profile.teleg_id': 1 })
2020-01-03 22:02:18 +01:00
.then((rec) => {
return (!!rec) ? rec.profile.teleg_id : null;
}).catch((e) => {
console.error('TelegIdByUsername', e);
});
};
UserSchema.statics.SetTelegramCheckCode = async function (idapp, username, teleg_checkcode) {
const User = this;
const fields_to_update = {
'profile.teleg_checkcode': teleg_checkcode
};
return await User.findOneAndUpdate({
idapp,
username
}, { $set: fields_to_update }, { new: false }).then((record) => {
return !!record;
});
};
UserSchema.statics.SetTelegramIdSuccess = async function (idapp, username, teleg_id) {
const User = this;
const fields_to_update = {
'profile.teleg_id': teleg_id,
'profile.teleg_checkcode': 0
};
return await User.findOneAndUpdate({
idapp,
username
}, { $set: fields_to_update }, { new: false }).then((record) => {
return record;
});
};
2020-01-03 22:02:18 +01:00
UserSchema.statics.getNameSurnameByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, { name: 1, surname: 1 })
2020-01-03 22:02:18 +01:00
.then((rec) => {
return (!!rec) ? `${rec.name} ${rec.surname}` : '';
}).catch((e) => {
console.error('getNameSurnameByUsername', e);
});
};
UserSchema.statics.getusersManagers = async function (idapp) {
const User = this;
return await User.find({ idapp, 'profile.manage_telegram': true }, { 'profile.teleg_id': 1 })
2020-01-03 22:02:18 +01:00
.then((arrrec) => {
return (!!arrrec) ? arrrec : null;
}).catch((e) => {
console.error('getusersManagers', e);
});
};
UserSchema.statics.getUsersTelegALL = async function (idapp) {
const User = this;
return await User.find({ idapp, 'profile.teleg_id': { $gt: 0 } }, { 'profile.teleg_id': 1 })
.then((arrrec) => {
return (!!arrrec) ? arrrec : null;
}).catch((e) => {
console.error('getusersManagers', e);
});
};
UserSchema.statics.isManagerByIdTeleg = async function (idapp, idtelegram) {
const User = this;
return await User.findOne({ idapp, 'profile.manage_telegram': true, 'profile.teleg_id': idtelegram }, { 'profile.teleg_id': 1 })
.then((rec) => {
return (!!rec && rec.profile.teleg_id === idtelegram);
}).catch((e) => {
console.error('getusersManagers', e);
return false
});
};
UserSchema.statics.getUsersList = function (idapp) {
const User = this;
return User.find({ 'idapp': idapp }, {
username: 1,
name: 1,
surname: 1,
verified_email: 1,
2019-12-31 00:44:53 +01:00
made_gift: 1,
perm: 1,
email: 1,
date_reg: 1,
img: 1
})
};
UserSchema.statics.getUsersListByParams = function (params) {
const User = this;
myclParamQuery = new queryclass.CParamsQuery(params);
const filterMatchBefore = `${ myclParamQuery.filter }`;
return User.find(
{ $match: filterMatchBefore },
{ 'idapp': idapp },
2019-12-31 00:44:53 +01:00
{
username: 1,
name: 1,
surname: 1,
verified_email: 1,
made_gift: 1,
perm: 1,
email: 1,
date_reg: 1,
img: 1,
lasttimeonline: 1,
news_on: 1
})
};
/**
* Query blog posts by user -> paginated results and a total count.
* @returns {Object} Object -> `{ rows, count }`
*/
UserSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email', 'profile.cell', 'profile.email_paypal', 'profile.username_telegram', 'aportador_solidario']
};
UserSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
UserSchema.statics.findAllIdApp = function (idapp) {
const User = this;
const myfind = { idapp };
return User.find(myfind, (err, arrrec) => {
return arrrec
});
};
UserSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return tools.DuplicateAllRecords(this, idapporig, idappdest);
};
UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, username) {
try {
// DATA: username, name, surname, email, intcode_cell, cell
const dashboard = {
aportador: {},
downline: []
};
// Data of my Aportador
dashboard.aportador = await User.getUserShortDataByUsername(idapp, aportador_solidario);
// Data of my Downline
dashboard.downline = await User.getDownlineByUsername(idapp, username);
for (let index = 0; index < dashboard.downline.length; ++index) {
dashboard.downline[index].downline = await User.getDownlineByUsername(idapp, dashboard.downline[index].username);
}
return dashboard;
} catch (e) {
console.error(e);
return false;
}
};
UserSchema.statics.fixUsername = async function (idapp, aportador_solidario_ind_order, username) {
const User = this;
// Check if somewhere there is my username
return User.find({ idapp, aportador_solidario_ind_order }, async (err, arrrec) => {
if (arrrec) {
for (const myuser of arrrec) {
if (!myuser.aportador_solidario || myuser.aportador_solidario === tools.APORTADOR_NONE) {
myuser.aportador_solidario = username;
await myuser.save()
}
}
}
});
};
UserSchema.statics.getUsersRegistered = async function (idapp) {
const User = this;
const myfind = { idapp };
return await User.count(myfind);
};
UserSchema.statics.getLastUsers = async function (idapp) {
const User = this;
const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_USERS', 5);
return await User.find({ idapp }).sort({ date_temp_reg: -1 }).limit(lastn);
};
UserSchema.statics.checkUser = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, {
verified_email: 1,
'profile.teleg_id': 1,
'profile.teleg_checkcode': 1,
});
};
UserSchema.statics.calculateStat = async function (idapp, username) {
const User = this;
return calcstat = {
numinvitati: await User.getnumInvitati(idapp, username),
numinvitati_attivi: await User.getnumInvitatiAttivi(idapp, username),
};
};
if (tools.INITDB_FIRSTIME) {
console.log(' createIndex User Index...');
// UserSchema.index({ username: 'text', name: 'text', surname: 'text', email: 'text' });
// UserSchema.index({ name: 'name' });
// UserSchema.index({ name: 1 });
// UserSchema.index({ surname: 1 });
}
2018-12-24 20:31:02 +01:00
const User = mongoose.model('User', UserSchema);
2018-12-24 20:31:02 +01:00
2018-12-24 20:31:02 +01:00
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
// Adding a method to the constructor
greet() {
return `${this.name} says hello.`;
}
}
module.exports = { User, Hero };
2018-12-24 20:31:02 +01:00