| const checkMatch = await bcrypt.compare(password, user.password) | const checkMatch = await bcrypt.compare(password, user.password) | ||||
| console.log(password) | console.log(password) | ||||
| console.log(user.password) | console.log(user.password) | ||||
| console.log(checkMatch) | |||||
| if(checkMatch) { | if(checkMatch) { | ||||
| return user | return user | ||||
| } | } | ||||
| tokenSchema.statics.destroyToken = async function(token) { | tokenSchema.statics.destroyToken = async function(token) { | ||||
| const findUser = await User.findOne({ 'tokens.token': token }) | const findUser = await User.findOne({ 'tokens.token': token }) | ||||
| if(!findUser) { | |||||
| return null | |||||
| } | |||||
| findUser.tokens = findUser.tokens.filter((currToken) => { | findUser.tokens = findUser.tokens.filter((currToken) => { | ||||
| return currToken.token !== token | return currToken.token !== token | ||||
| }) | }) | ||||
| await findUser.save() | await findUser.save() | ||||
| console.log('uspesno') | |||||
| return jwt.sign(token, 'a', { expiresIn: 1 }) | |||||
| return true | |||||
| } | } | ||||
| const Token = mongoose.model('Token', tokenSchema) | const Token = mongoose.model('Token', tokenSchema) |
| router.post('/login', async (req, res) => { | router.post('/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('User does not exist, wrong email') | |||||
| return res.status(400).send('Wrong credentials!') | |||||
| } | } | ||||
| const isValidPassword = await bcrypt.compare(req.body.password, findUser.password) | const isValidPassword = await bcrypt.compare(req.body.password, findUser.password) | ||||
| }) | }) | ||||
| router.post('/logout/', async (req, res) => { | router.post('/logout/', async (req, res) => { | ||||
| const result = Token.destroyToken(req.body.token) | |||||
| const result = await Token.destroyToken(req.body.token) | |||||
| if(!result) { | |||||
| return res.status(404).send('No user has the token provided!') | |||||
| } | |||||
| return res.send('Token ' + req.body.token + ' invalidated!') | |||||
| }) | }) | ||||
| module.exports = router | module.exports = router |