Login Controller Step -11

Login Controller Step -11

Step 11:-Login Controller

const ErrorResponse= require('../util/errorResponse')
const asyncHandler =require('../middleware/async')
const login= require('../models/login');

// Insert data into db
exports.insertData = asyncHandler(async(req,res,next)=>{
    const createData = await login.create(req.body);
    //CREATE TOKEN
    const token = createData.getSignedJwtToken();
    res.status(200).json({sucess:true,token})
});

// Login data from db
exports.getData = asyncHandler(async(req,res,next)=>{
    const{email,password}=req.body;
    console.log(req.body)
    if(!email || !password)
    {
        return next(new ErrorResponse('please provide email and password',400));
    }
    //check user
    const findUser =await login.findOne({email}).select('+password');
    if(!findUser)
    {
        return next(new ErrorResponse('Invalid credential',401));
    }

    //check if password matches
    const isMatch = await findUser.matchPassword(password);
    if(!isMatch)
    {
         return next(new ErrorResponse('Invalid credential',401));
    }
    
    //CREATE TOKEN
    const token = findUser.getSignedJwtToken();
    res.status(200).json({sucess:true,token,data:findUser})
});

// Login as a single user
exports.getMe =asyncHandler(async(req,res,next)=>{
    const User =await login.findById(req.user.id);
      res.status(200).json({sucess:true,data:User});
});

Post Your Comments & Reviews

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

*

*