Files
freeplanet_serverside/server/models/user.js
Paolo Arena f6fa45a9e9 Fix: Todo Multi refresh ...
fix some promises problem
2019-02-14 19:01:41 +01:00

261 lines
5.1 KiB
JavaScript

var bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const tools = require('../tools/general');
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: true,
/*validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}*/
},
idapp: {
type: Number,
required: true,
},
username: {
type: String,
required: true,
trim: true,
minlength: 6,
unique: 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
},
}],
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', 'username', 'userId']);
};
UserSchema.methods.generateAuthToken = function (req) {
// console.log("GENERA TOKEN : ");
var user = this;
const useragent = req.get('User-Agent');
tools.mylog("GENERATE USER-AGENT = ", useragent);
var access = 'auth';
const browser = useragent;
var token = jwt.sign({ _id: user._id.toHexString(), access }, process.env.SIGNCODE).toString();
var 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 });
return user.save()
.then(() => {
console.log("TOKEN CREATO IN LOGIN : " + token);
return token;
})
.catch(err => {
console.log("Error", err.message);
});
};
UserSchema.statics.findByToken = function (token, typeaccess) {
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,
'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 (username, password) {
var User = this;
var pwd = "";
return User.findOne({ username: username }).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 (username) {
var User = this;
return User.findOne({
'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 (email) {
var User = this;
return User.findOne({
'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) {
var user = this;
return user.update({
$pull: {
tokens: { token }
}
});
};
var 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 };