Skip to content

Instantly share code, notes, and snippets.

@AntonioErdeljac
Last active April 24, 2021 15:31
Show Gist options
  • Save AntonioErdeljac/d4b1611e8ce92943c067b3a6ab51154b to your computer and use it in GitHub Desktop.
Save AntonioErdeljac/d4b1611e8ce92943c067b3a6ab51154b to your computer and use it in GitHub Desktop.
const mongoose = require('mongoose');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const { Schema } = mongoose;
const UsersSchema = new Schema({
email: String,
hash: String,
salt: String,
});
UsersSchema.methods.setPassword = function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
};
UsersSchema.methods.validatePassword = function(password) {
const hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
return this.hash === hash;
};
UsersSchema.methods.generateJWT = function() {
const today = new Date();
const expirationDate = new Date(today);
expirationDate.setDate(today.getDate() + 60);
return jwt.sign({
email: this.email,
id: this._id,
exp: parseInt(expirationDate.getTime() / 1000, 10),
}, 'secret');
}
UsersSchema.methods.toAuthJSON = function() {
return {
_id: this._id,
email: this.email,
token: this.generateJWT(),
};
};
mongoose.model('Users', UsersSchema);
Copy link

ghost commented Feb 11, 2021

  }, 'secret');

Just tell people to create their own secret, this isn't secure at all

crypto.pbkdf2Sync

Synchronously hashing passwords is a bad idea.

@alamenai
Copy link

Why there is not an id property in the UsersSchema?

@alamenai
Copy link

@SpheeresX , what's your suggestion about creating our secrets? What do you recomment?

Copy link

ghost commented Apr 24, 2021

@SpheeresX , what's your suggestion about creating our secrets? What do you recomment?

@MenaiAla Generate a secure password and store it in .env. Also, sorry for being so irate in my previous comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment