1
0

Video 105: Logging in Users

This commit is contained in:
JayWll 2020-04-13 15:41:18 -06:00
parent 9b4115afd5
commit 6a7cb2882f
2 changed files with 27 additions and 0 deletions

View File

@ -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

View File

@ -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({})