Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.

Paste

Pasted as JavaScript by donots ( 5 years ago )
// signin authentication
router.post('/signin', (req, res) => {

    const username = req.body.username;
    const password = req.body.password;

    // finding user by username
    User.findOne({username}).then(user => {
        //checking if the user exists
        if (!user) {
            return res.status(404).json({message: 'User was not found'});
        }
        //checking password
        bcrypt.compare (password, user.password).then(isMatch => {
            if (isMatch) {
                //user matched, create jwt payload
                const payload = {
                    id: user.id,
                    username: user.username
                };
                //sign token
                jwt.sign(
                    payload,
                    keys.secretOrKey,
                    {
                        expiresIn: 31556926 //  1year
                    },
                    (err, token) => {
                        res.json({
                            success: true,
                            token: "Bearer " + token
                        });
                    }
                )
            }
        })
    })
})

 

Revise this Paste

Children: 123596
Your Name: Code Language: