Files
freeplanet_serverside/server/models/user.js

385 lines
8.0 KiB
JavaScript
Raw Normal View History

2019-07-14 18:44:36 +02:00
var 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 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);
2018-12-24 20:31:02 +01:00
var 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,
},
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,
},
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,
default: Date.now()
},
2018-12-24 20:31:02 +01:00
date_tokenforgot: {
type: Date
},
tokenforgot: {
type: String,
},
});
UserSchema.methods.toJSON = function () {
var user = this;
var userObject = user.toObject();
return _.pick(userObject, ['_id', 'email', 'verified_email', 'idapp', 'username', 'userId', 'name', 'surname', 'perm']);
2018-12-24 20:31:02 +01:00
};
UserSchema.methods.generateAuthToken = function (req) {
// console.log("GENERA TOKEN : ");
2018-12-24 20:31:02 +01:00
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();
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 });
return user.save()
.then(() => {
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 (user) {
try {
return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
}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) {
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) {
2018-12-24 20:31:02 +01:00
var User = this;
var pwd = "";
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,
});
};
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!
2018-12-24 20:31:02 +01:00
'idapp': idapp,
});
};
UserSchema.statics.findByEmail = function (idapp, email) {
2018-12-24 20:31:02 +01:00
var User = this;
return User.findOne({
'idapp': idapp,
2018-12-24 20:31:02 +01:00
'email': email,
});
};
UserSchema.pre('save', function (next) {
var user = this;
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.update({
$pull: {
tokens: { token }
2018-12-24 20:31:02 +01:00
}
});
};
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 })
};
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 })
};
/**
* Query blog posts by user -> paginated results and a total count.
* @returns {Object} Object -> `{ rows, count }`
*/
UserSchema.statics.queryTable = function (idapp, params) {
const User = this;
if (typeof params.startRow !== 'number') {
throw new Error('startRow must be number')
} else if (typeof params.endRow !== 'number') {
throw new Error('endRow must be number')
}
const query = [
{ $match: Object.assign({ idapp }, params.filter) }
];
if (params.sortBy) {
// maybe we want to sort by blog title or something
const mysort = { $sort: params.sortBy };
// console.log('sortBy', params.sortBy);
// console.table(mysort);
query.push(mysort)
}
query.push(
{ $group: {
_id: null,
// get a count of every result that matches until now
count: { $sum: 1 },
// keep our results for the next operation
results: { $push: '$$ROOT' }
} },
// and finally trim the results to within the range given by start/endRow
{ $project: {
count: 1,
rows: { $slice: ['$results', params.startRow, params.endRow] }
} }
);
return User
.aggregate(query)
.then(([{ count, rows }]) => ({ count, rows }))
};
2018-12-24 20:31:02 +01:00
const User = mongoose.model('User', UserSchema);
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