From 6a7cb2882f954b174bff9e9db53509c55f04fc4f Mon Sep 17 00:00:00 2001 From: JayWll Date: Mon, 13 Apr 2020 15:41:18 -0600 Subject: [PATCH] Video 105: Logging in Users --- task-manager/src/models/user.js | 18 ++++++++++++++++++ task-manager/src/routers/user.js | 9 +++++++++ 2 files changed, 27 insertions(+) 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({})