Skip to content

Commit

Permalink
overwrite user model toJSON, make is_vip vitrual field
Browse files Browse the repository at this point in the history
  • Loading branch information
taobataoma committed May 3, 2017
1 parent 8254a88 commit 46fb801
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
3 changes: 2 additions & 1 deletion modules/core/server/controllers/core.server.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ exports.renderIndex = function (req, res) {
passkey: req.user.passkey,
vip_start_at: req.user.vip_start_at,
vip_end_at: req.user.vip_end_at,
is_vip: isVip(req.user),
is_vip: req.user.is_vip || isVip(req.user),
score: req.user.score,
ratio: req.user.ratio,
profileImageURL: req.user.profileImageURL,
email: validator.escape(req.user.email),
lastName: validator.escape(req.user.lastName),
Expand Down
36 changes: 35 additions & 1 deletion modules/users/server/models/user.server.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ var mongoose = require('mongoose'),
crypto = require('crypto'),
validator = require('validator'),
generatePassword = require('generate-password'),
owasp = require('owasp-password-strength-test');
owasp = require('owasp-password-strength-test'),
moment = require('moment');

owasp.config(config.shared.owasp);

Expand Down Expand Up @@ -141,6 +142,10 @@ var UserSchema = new Schema({
type: Number,
default: 0
},
ratio: {
type: Number,
default: 0
},
seeded: {
type: Number,
default: 0
Expand Down Expand Up @@ -169,6 +174,24 @@ var UserSchema = new Schema({
}
});

/**
* overwrite toJSON
*/
UserSchema.methods.toJSON = function (options) {
var document = this.toObject(options);
document.is_vip = false;

if (!document.vip_start_at || !document.vip_end_at) {
document.is_vip = false;
} else if (moment(Date.now()) > moment(document.vip_end_at)) {
document.is_vip = false;
} else {
document.is_vip = true;
}

return document;
};

/**
* Hook a pre save method to hash the password
*/
Expand All @@ -181,6 +204,17 @@ UserSchema.pre('save', function (next) {
next();
});

/**
* Hook a post save method to set the ratio
*/
UserSchema.post('save', function (doc) {
if (doc.uploaded === 0 || doc.downloaded === 0) {
doc.ratio = 0;
} else {
doc.ratio = Math.round((doc.uploaded / doc.downloaded) * 100) / 100;
}
});

/**
* Hook a pre validate method to test the local password
*/
Expand Down

0 comments on commit 46fb801

Please sign in to comment.