| tokenSchema.statics.findByCredentials = async (email, password) => { | tokenSchema.statics.findByCredentials = async (email, password) => { | ||||
| const user = await User.findOne({email}) | const user = await User.findOne({email}) | ||||
| if(!user) { | if(!user) { | ||||
| throw new Error('Login unsuccessfull!') | |||||
| return | |||||
| } | } | ||||
| const checkMatch = await bcrypt.compare(password, user.password) | const checkMatch = await bcrypt.compare(password, user.password) | ||||
| console.log(user.password) | console.log(user.password) | ||||
| console.log(checkMatch) | console.log(checkMatch) | ||||
| if(!checkMatch) { | if(!checkMatch) { | ||||
| return | |||||
| return user | |||||
| } | } | ||||
| return user | return user | ||||
| } | } |
| router.get('/login', async (req, res) => { | router.get('/login', async (req, res) => { | ||||
| const findUser = await Token.findByCredentials(req.body.email, req.body.password) | const findUser = await Token.findByCredentials(req.body.email, req.body.password) | ||||
| if(!findUser) { | if(!findUser) { | ||||
| return res.status(400).send('Invalid credentials!') | |||||
| return res.status(400).send('User does not exist, wrong email') | |||||
| } | } | ||||
| const isValidPassword = await bcrypt.compare(req.body.password, findUser.password) | const isValidPassword = await bcrypt.compare(req.body.password, findUser.password) | ||||
| if(!isValidPassword) { | if(!isValidPassword) { | ||||
| return res.status(400).send("Email or password is incorrect!") | |||||
| return res.status(400).send('Password is incorrect!') | |||||
| } | } | ||||
| return res.send(findUser) | return res.send(findUser) |
| } | } | ||||
| }) | }) | ||||
| router.post('/users/login', async (req, res) => { | |||||
| try { | |||||
| const user = await User.findByCredentials(req.body.email, req.body.password) | |||||
| if(!user) { | |||||
| return res.status(400).send('Invalid email or password!') | |||||
| } | |||||
| console.log(user) | |||||
| const token = await user.generateAuthToken() | |||||
| console.log(token) | |||||
| return res.send(user) | |||||
| } catch(e) { | |||||
| } | |||||
| }) | |||||
| module.exports = router | module.exports = router |