feat: login controller
This commit is contained in:
@@ -36,3 +36,29 @@ const register = async (req, res) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const login = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { email, password } = req.body;
|
||||||
|
if (!email || !password) return res.status(400).send('Email and password are required')
|
||||||
|
if (password.length < 6) return res.status(400).send('Password must be at least 6 characters')
|
||||||
|
|
||||||
|
let user = await User.findOne({ email }).exec()
|
||||||
|
const match = await comparePassword(password, user.password)
|
||||||
|
if (!match) return res.status(400).send('Invalid email or password')
|
||||||
|
|
||||||
|
// create signed jwt
|
||||||
|
const token = jwt.sign({
|
||||||
|
_id: user._id
|
||||||
|
}, process.env.JWT_SECRET as string, {
|
||||||
|
expiresIn: '3d'
|
||||||
|
})
|
||||||
|
// return user and token to client, exclude hashed password
|
||||||
|
user.password = undefined
|
||||||
|
res.cookie('token', token, {
|
||||||
|
httpOnly: true
|
||||||
|
})
|
||||||
|
res.json(user)
|
||||||
|
} catch (error) {
|
||||||
|
res.status(400).send(`Could not login user - ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user