Login Model Step – 10

Login Model Step – 10

Step 10:-Login Model

Package to run

  • Npm i bcryptjs
  • Npm i jsonwebtoken

Config file

  • JWT_SECRET=shairy
  • JWT_EXPIRE=30d
const mongoose =require('mongoose');
const bcrypt =require('bcryptjs');
const jwt= require('jsonwebtoken');

const loginSchema = new mongoose.Schema({
    email:{
        type:String,
        required:[true,"please enter email"],
    },
    password:{
        type:String,
        select:false,
        required:[true,"please enter password"],
    }, 
    role:{
        type:String,
        enum:['admin'],
        required:[true,"please enter role"],
    },
    created:{
        type:Date,
        default:Date.now
    }

});

//Encrypt password using bcrypt
loginSchema.pre('save',async function(next){
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password,salt)
});

//Sign JWT and Return
loginSchema.methods.getSignedJwtToken=function(){
    return jwt.sign({id:this._id},
        process.env.JWT_SECRET,
        {expiresIn:process.env.JWT_EXPIRE})
}

//Match user data with hash password in database
loginSchema.methods.matchPassword= async function(enteredPassword){
return await bcrypt.compare(enteredPassword,this.password);
}

module.exports=mongoose.model('login',loginSchema)

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*