Skip to content

Instantly share code, notes, and snippets.

@FikriRNurhidayat
Created September 5, 2019 05:04
Show Gist options
  • Save FikriRNurhidayat/d6b1dad22083e72d2fa0ae6c2ea2ee78 to your computer and use it in GitHub Desktop.
Save FikriRNurhidayat/d6b1dad22083e72d2fa0ae6c2ea2ee78 to your computer and use it in GitHub Desktop.
Try Catch
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const UserProfile = require('./userProfile.js');
var userSchema = new mongoose.Schema({
name: {
type: 'string',
required: true
},
email: {
type: 'string',
unique: true,
required: true,
downcase: true
},
password: {
type: 'string',
required: true
},
isVerified: {
type: 'boolean',
default: false
}
});
userSchema.path("email").validate(email => {
var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailRegex.test(email);
}, "Not a valid email!");
userSchema.pre("save", async function(next) {
let salt = await bcrypt.genSalt(10);
let hashedPassword = await bcrypt.hash(this.password, salt);
this.password = hashedPassword;
next();
});
userSchema.post("save", function(next) {
let id = this._id
UserProfile.create({
user: id
});
});
var User = mongoose.model('User', userSchema);
User.register = async function(data) {
return new Promise(async function(resolve, reject) {
if (!data.password) {
return reject([400, "Password is blank"]);
};
if (data.password != data.password_confirmation) {
return reject([400, "Password doesn't match!"]);
};
delete data.password_confirmation
try {
let user = await User.create(data);
resolve([201, {
_id: user._id,
name: user.name,
email: user.email
}]);
}
catch (err) {
reject([422, err]);
}
});
}
User.authenticate = async function(data) {
return new Promise(async function(resolve, reject) {
if (!data.password) {
return reject([400, "No password!"]);
}
let user = await User.findOne({
email: data.email
}).select(['_id','email','password']);
if (!user) {
return reject([401, "Email hasn't registered yet!"]);
}
let isCorrect = await bcrypt.compare(data.password, user.password);
if (!isCorrect) {
return reject([401, "Password incorrect!"]);
}
let token = jwt.sign({ _id: user._id }, process.env.JWT_SIGNATURE);
resolve([200, token]);
});
}
module.exports = User;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment