diff --git a/task-manager/src/models/user.js b/task-manager/src/models/user.js index 28476c9..588dadb 100644 --- a/task-manager/src/models/user.js +++ b/task-manager/src/models/user.js @@ -10,6 +10,7 @@ const userSchema = new mongoose.Schema({ }, email: { type: String, + unique: true, required: true, trim: true, lowercase: true, @@ -41,6 +42,23 @@ const userSchema = new mongoose.Schema({ } }) +userSchema.statics.findByCredentials = async (email, password) => { + const user = await User.findOne({ email }) + + if (!user) { + throw new Error('Unable to login') + } + + const isMatch = await bcrypt.compare(password, user.password) + + if (!isMatch) { + throw new Error('Unable to login') + } + + return user +} + +// Hash the plain text password before saving userSchema.pre('save', async function(next) { const user = this diff --git a/task-manager/src/routers/user.js b/task-manager/src/routers/user.js index ed8ce04..f3c2559 100644 --- a/task-manager/src/routers/user.js +++ b/task-manager/src/routers/user.js @@ -13,6 +13,15 @@ router.post('/users', async (req, res) => { } }) +router.post('/users/login', async (req, res) => { + try { + const user = await User.findByCredentials(req.body.email, req.body.password) + res.send(user) + } catch (e) { + res.status(400).send() + } +}) + router.get('/users', async (req, res) => { try { const users = await User.find({})