tokenController.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const config = require('../config.js')
  2. const db = require('knex')(config.database)
  3. const randomstring = require('randomstring')
  4. let tokenController = {}
  5. tokenController.verify = function(req, res, next){
  6. if(req.body.token === undefined) return res.json({ success: false, description: 'No token provided' })
  7. let token = req.body.token
  8. db.table('users').where('token', token).then((user) => {
  9. if(user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
  10. return res.json({ success: true, username: user[0].username})
  11. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  12. }
  13. tokenController.list = function(req, res, next){
  14. let token = req.headers.token
  15. if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  16. db.table('users').where('token', token).then((user) => {
  17. if(user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
  18. return res.json({ success: true, token: token })
  19. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  20. }
  21. tokenController.change = function(req, res, next){
  22. let token = req.headers.token
  23. if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  24. let newtoken = randomstring.generate(64)
  25. db.table('users').where('token', token).update({
  26. token: newtoken,
  27. timestamp: Math.floor(Date.now() / 1000)
  28. }).then(() => {
  29. res.json({ success: true, token: newtoken })
  30. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  31. }
  32. module.exports = tokenController