Express Login Endpoint | JavaScript

March 10th, 2021 09:42:36 PM

					
router.post("/", async (req, res) => { const { email, password } = req.body; try { if (!email) return res.status(400).json({ msg: "An email is required" }); if (!password) return res.status(400).json({ msg: "A password is required" }); const user = await User.findOne({ email }).select("_id password"); if (!user) return res.status(400).json({ msg: "Invalid credentials" }); const match = await bcrypt.compare(password, user.password); if (!match) return res.status(400).json({ msg: "Invalid credentials" }); const accessToken = genAccessToken({ id: user._id }); const refreshToken = genRefreshToken({ id: user._id }); res.cookie("token", refreshToken, { expires: new Date(Date.now() + 604800), httpOnly: true, }); res.json({ accessToken }); } catch (err) { console.log(err.message); res.status(500).json({ msg: "Error logging in user" }); } });

Featured Posts