{"size": 1297, "ext": "js", "max_stars_repo_path": "personal-site/db/models/user.js", "max_stars_repo_name": "gubtos/personal-site", "max_stars_repo_stars_event_min_datetime": "2019-05-17T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-17T15:53:08.000Z", "max_issues_repo_path": "personal-site/db/models/user.js", "max_issues_repo_name": "gubtos/personal-site", "max_issues_repo_issues_event_min_datetime": "2020-09-04T21:37:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:50:08.000Z", "max_forks_repo_path": "personal-site/db/models/user.js", "max_forks_repo_name": "gubtos/personal-site", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 11, "max_forks_count": null, "avg_line_length": 25.431372549, "max_line_length": 83, "alphanum_fraction": 0.6044718581}
const mongoose = require('mongoose');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const params = require('../../config/jwt');

const UserSchema = new mongoose.Schema({
    name: String,
    email: {type: String, unique: true},
    isAdmin: Boolean,
    password: String,
    salt: String
});

// Mongoose don't work with arrow functions

UserSchema.pre('save', function(next){
    var user = this;
    user.salt = crypto.randomBytes(16).toString('hex');
    crypto.pbkdf2(user.password, user.salt, 10000, 512, 'sha512', (err, hash) => {
            if(err){
                return next(err);
            }
            user.password = hash;
            next();         
        }
    );
});

UserSchema.methods.validatePassword = function(password){
    const validated = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512');
    return validated == this.password;
}

UserSchema.methods.generateJWT = function(){
    return jwt.sign({
        email: this.email,
        id: this._id,
    }, params.secret, {
        expiresIn: params.expiration
    });
}

UserSchema.methods.toAuthJSON = function(){
    return {
        _id : this._id,
        email : this.email,
        token : this.generateJWT()
    };
};

module.exports = mongoose.model('User', UserSchema);