简体   繁体   中英

Post request error when attempting to log user in

I have a post route request function below to login a user. I keep getting 401 unauthorized errors when attempting to make the request. Based on my code below, is there any refactoring I can do to fix this? Many thanks!!!


router.post('/login', async (req, res, next) => {
    try {

        // attempt to find the user in database //

        const user = await User.findOne({ username: req.body.username });

        // if user entered doesn't match which is in the database throw an error //

        if (!user) {
            res.status(401).json('wrong credentials!')
       
            var hashedPassword = Cryptojs.AES.decrypt(
                user.password, 
                process.env.PASS_SEC);
            var Orginalpassword = hashedPassword.toString(Cryptojs.enc.Utf8);
        } 

        //  check if password entered matches the orignal password entered during registration, if not return error //

         else if ( Orginalpassword !== req.body.password ) {
            res.status(401).json('wrong credentials!');
    
                var accessToken = jwt.sign({
                    id: user._id, 
                    isAdmin: user.isAdmin
                },
                    process.env.JWT_SEC,
                    {expiresIn:'3d'}
                );
            
            var { password, ...others} = user._doc;
         }
          else  {

            // if password and username both match successfully log user in //

            return res.status(200).json({...others, accessToken})
            
          }
          
    } catch (error) {
        res.status(500).json(error);
    }
});

here i did the simplest way to implement the login API try this

router.post('/login', async (req, res, next) => {
    try {
        const {username, password} = req.body;

        // attempt to find the user in database 
        const user = await User.findOne({ username });

        // compares the password
        if (user && await bcrypt.compare(password, user.password)) {
            let accessToken = jwt.sign({
                id: user._id, 
                isAdmin: user.isAdmin
            },
                process.env.JWT_SEC,
                {expiresIn:'3d'}
            );
            
            user.accessToken = accessToken;

            return res.status(200).json({...others, accessToken})
        }
        return res.status(401).send('wrong credentials!');
          
    } catch (error) {
       return res.status(500).json(error.message);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM