401 lines
8.1 KiB
JavaScript
401 lines
8.1 KiB
JavaScript
var bcrypt = require('bcryptjs');
|
|
const mongoose = require('mongoose');
|
|
const validator = require('validator');
|
|
const jwt = require('jsonwebtoken');
|
|
const _ = require('lodash');
|
|
|
|
const tools = require('../tools/general');
|
|
|
|
const shared_consts = require('../tools/shared_nodejs');
|
|
const queryclass = require('../classes/queryclass');
|
|
|
|
mongoose.Promise = global.Promise;
|
|
|
|
mongoose.level = "F";
|
|
// Resolving error Unknown modifier: $pushAll
|
|
mongoose.plugin(schema => {
|
|
schema.options.usePushEach = true
|
|
});
|
|
|
|
mongoose.set('debug', process.env.DEBUG);
|
|
|
|
var UserSchema = new mongoose.Schema({
|
|
userId: {
|
|
type: String,
|
|
},
|
|
email: {
|
|
type: String,
|
|
required: true,
|
|
trim: true,
|
|
minlength: 1,
|
|
unique: false,
|
|
/*validate: {
|
|
validator: validator.isEmail,
|
|
message: '{VALUE} is not a valid email'
|
|
}*/
|
|
},
|
|
cell: {
|
|
type: String,
|
|
},
|
|
idapp: {
|
|
type: String,
|
|
required: true,
|
|
},
|
|
username: {
|
|
type: String,
|
|
required: true,
|
|
trim: true,
|
|
minlength: 6,
|
|
unique: false,
|
|
},
|
|
name: {
|
|
type: String,
|
|
trim: true,
|
|
},
|
|
surname: {
|
|
type: String,
|
|
trim: true,
|
|
},
|
|
password: {
|
|
type: String,
|
|
require: true,
|
|
minlength: 6,
|
|
},
|
|
lang: {
|
|
type: String,
|
|
require: true,
|
|
},
|
|
linkreg: {
|
|
type: String,
|
|
required: false
|
|
},
|
|
verified_email: {
|
|
type: Boolean,
|
|
},
|
|
tokens: [{
|
|
access: {
|
|
type: String,
|
|
required: true
|
|
},
|
|
browser: {
|
|
type: String,
|
|
required: true
|
|
},
|
|
token: {
|
|
type: String,
|
|
required: true
|
|
},
|
|
date_login: {
|
|
type: Date
|
|
},
|
|
}],
|
|
perm: {
|
|
type: Number
|
|
},
|
|
img: {
|
|
type: String
|
|
},
|
|
ipaddr: {
|
|
type: String,
|
|
},
|
|
date_reg: {
|
|
type: Date,
|
|
default: Date.now()
|
|
},
|
|
date_tokenforgot: {
|
|
type: Date
|
|
},
|
|
tokenforgot: {
|
|
type: String,
|
|
},
|
|
lasttimeonline: {
|
|
type: Date
|
|
}
|
|
|
|
});
|
|
|
|
UserSchema.methods.toJSON = function () {
|
|
var user = this;
|
|
var userObject = user.toObject();
|
|
|
|
return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
|
|
};
|
|
|
|
UserSchema.methods.generateAuthToken = function (req) {
|
|
// console.log("GENERA TOKEN : ");
|
|
var user = this;
|
|
|
|
const useragent = req.get('User-Agent');
|
|
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();
|
|
|
|
// CANCELLA IL PRECEDENTE !
|
|
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(() => {
|
|
console.log("TOKEN CREATO IN LOGIN : " + token);
|
|
return token;
|
|
})
|
|
.catch(err => {
|
|
console.log("Error", err.message);
|
|
});
|
|
};
|
|
|
|
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 (user) {
|
|
try {
|
|
return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
|
|
} catch (e) {
|
|
return false
|
|
}
|
|
};
|
|
|
|
UserSchema.statics.isManager = function (user) {
|
|
try {
|
|
return ((user.perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
|
|
} catch (e) {
|
|
return false
|
|
}
|
|
};
|
|
|
|
UserSchema.statics.findByToken = function (token, typeaccess) {
|
|
const User = this;
|
|
let decoded;
|
|
|
|
try {
|
|
decoded = jwt.verify(token, process.env.SIGNCODE);
|
|
} catch (e) {
|
|
return Promise.resolve(null);
|
|
}
|
|
|
|
return User.findOne({
|
|
'_id': decoded._id,
|
|
'tokens.token': token,
|
|
'tokens.access': typeaccess,
|
|
});
|
|
};
|
|
|
|
UserSchema.statics.findByTokenAnyAccess = function (token) {
|
|
var User = this;
|
|
var decoded;
|
|
|
|
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) {
|
|
var User = this;
|
|
var pwd = "";
|
|
|
|
return User.findOne({ idapp, username: username }).then((user) => {
|
|
if (!user) {
|
|
// Check if with email:
|
|
return User.findOne({ idapp, email: username })
|
|
} else {
|
|
return user
|
|
}
|
|
}).then(user => {
|
|
if (!user)
|
|
return null;
|
|
|
|
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);
|
|
bcrypt.compare(password, pwd, (err, res) => {
|
|
if (res) {
|
|
resolve(user);
|
|
} else {
|
|
return resolve(null);
|
|
}
|
|
});
|
|
});
|
|
});
|
|
};
|
|
|
|
|
|
UserSchema.statics.findByUsername = function (idapp, username) {
|
|
const User = this;
|
|
|
|
return User.findOne({
|
|
'idapp': idapp,
|
|
'username': username,
|
|
});
|
|
};
|
|
|
|
UserSchema.statics.findByLinkreg = function (idapp, linkreg) {
|
|
var User = this;
|
|
|
|
return User.findOne({
|
|
'linkreg': linkreg,
|
|
'idapp': idapp,
|
|
});
|
|
};
|
|
|
|
UserSchema.statics.findByLinkTokenforgot = function (idapp, email, tokenforgot) {
|
|
var User = this;
|
|
|
|
return User.findOne({
|
|
'email': email,
|
|
'tokenforgot': tokenforgot,
|
|
'date_tokenforgot': { $gte: new Date(ISODate().getTime() - 1000 * 60 * 60 * 4) }, // 4 ore fa!
|
|
'idapp': idapp,
|
|
});
|
|
};
|
|
|
|
|
|
UserSchema.statics.findByEmail = function (idapp, email) {
|
|
var User = this;
|
|
|
|
return User.findOne({
|
|
'idapp': idapp,
|
|
'email': email,
|
|
});
|
|
};
|
|
|
|
UserSchema.pre('save', function (next) {
|
|
var user = this;
|
|
|
|
|
|
/*
|
|
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;
|
|
|
|
return user.update({
|
|
$pull: {
|
|
tokens: { token }
|
|
}
|
|
});
|
|
};
|
|
|
|
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.getUsersList = function (idapp) {
|
|
const User = this;
|
|
|
|
return User.find({ 'idapp': idapp }, {
|
|
username: 1,
|
|
name: 1,
|
|
surname: 1,
|
|
verified_email: 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 },
|
|
{ username: 1, name: 1, surname: 1, verified_email: 1, perm: 1, email: 1, date_reg: 1, img: 1, lasttimeonline: 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', 'cell']
|
|
};
|
|
|
|
UserSchema.statics.executeQueryTable = function (idapp, params) {
|
|
params.fieldsearch = this.getFieldsForSearch();
|
|
return tools.executeQueryTable(this, idapp, params);
|
|
};
|
|
|
|
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 });
|
|
}
|
|
|
|
const User = mongoose.model('User', UserSchema);
|
|
|
|
|
|
|
|
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 };
|
|
|
|
|