Skip to content

Commit

Permalink
user login implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
dinilgamage committed Feb 23, 2024
1 parent cd620db commit bc3b218
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
14 changes: 13 additions & 1 deletion backend/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
};


Expand Down
23 changes: 23 additions & 0 deletions backend/models/userModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);

0 comments on commit bc3b218

Please sign in to comment.