Home > Enterprise >  generateAuthToken() is not working giving value undefined
generateAuthToken() is not working giving value undefined

Time:11-10

I'm using a method login in which a new user will be created also a user can login through its details meanwhile system is generating jwt token when registering a new user but when user is logging into the page it is not generating token code showing value undefined

I tried cost token = userRegister.generateAuthToken(); same in both the blocks but is working while creating user but not working while login

app.post("/login", async(req,res)=>{
    try{
        const pword = req.body.pword;
        const cpword = req.body.cpword;
        const email = req.body.email;

        if(cpword!=""){
            
            const registerUser = new Truck({
                email:req.body.email,
                pword:req.body.pword,
            })
            const token = await registerUser.generateAuthToken();
            res.cookie("jwt", token,
            {expires:new Date(Date.now() 30000),
                httpOnly:true
                // secure:true
            }
            );
            const registered = await registerUser.save();
            res.status(201).render("dashboard",{registered});
        }
        else{
            const registerUser = await Truck.findOne({email:email});
            const isMatch = await bcrypt.compare(pword, registerUser.pword);
            
            **const token = await registerUser.generateAuthToken(); **
           //here it is not generating token  
                // var token = jwt.sign({ id: registerUser._id }, process.env.SECRET_KEY, {
                //         expiresIn: 86400 // expires in 24 hours
                // });
                console.log(token);
                
                res.cookie("jwt", token,
                {expires:new Date(Date.now() 30000),
                    httpOnly:true,
                    // secure:true
                }
                );
                if(isMatch){
                    res.status(201).render("dashboard",{registerUser});
                }else{                  
                    res.status(400).send("login is not working");
                }
            }
    }catch(e){
        res.status(400).send(e);
        console.log(e);
    }
});

CodePudding user response:

the issue was with generateAuthToken() this method is not able to run the this.save(); due to the validation applied on pword cause bcrypt is increasing the length of the pword so removed maxlength validation from pword and thanks @kayitare Audax for bringing it to consideration.

CodePudding user response:

Maybe you can show us your Truck model so that we can see generateAuthToken()

  • Related