Video 105: Logging in Users
This commit is contained in:
parent
9b4115afd5
commit
6a7cb2882f
@ -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
|
||||
|
||||
|
@ -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({})
|
||||
|
Loading…
Reference in New Issue
Block a user