From bc3b2185c5aaef0ef59486c265ea4790822e4683 Mon Sep 17 00:00:00 2001 From: Dinil Date: Fri, 23 Feb 2024 12:10:33 +0530 Subject: [PATCH] user login implemented --- backend/controllers/userController.js | 14 +++++++++++++- backend/models/userModel.js | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/backend/controllers/userController.js b/backend/controllers/userController.js index aed1c64..1bc0e1c 100644 --- a/backend/controllers/userController.js +++ b/backend/controllers/userController.js @@ -8,7 +8,19 @@ const createToken = (_id) => { //login user exports.loginUser = async (req, res) => { - res.json({message: 'Login'}) + const { email, password } = req.body; + + try { + const user = await User.login(email, password); + + //create token + const token = createToken(user._id); + + res.status(200).json({ email, token }); + } + catch (err) { + res.status(400).json({ error: err.message }); + } }; diff --git a/backend/models/userModel.js b/backend/models/userModel.js index fe8b2bc..22d41eb 100644 --- a/backend/models/userModel.js +++ b/backend/models/userModel.js @@ -44,4 +44,27 @@ userSchema.statics.signup = async function(email, password) { return user; }; +//static login method +userSchema.statics.login = async function(email, password) { + + //validation + if (!email || !password) { + throw new Error('All fields are required'); + } + + const user = await this.findOne({ email }); + + if (!user) { + throw new Error('Invalid email or password'); + } + + const match = await bcrypt.compare(password, user.password); + + if (!match) { + throw new Error('Invalid email or password'); + } + + return user; +}; + module.exports = mongoose.model('User', userSchema); \ No newline at end of file