tokenController.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const config = require('../config.js')
  2. const db = require('knex')(config.database)
  3. let tokenController = {}
  4. tokenController.verify = function(req, res, next){
  5. if(req.body.token === undefined) return res.json({ success: false, description: 'No token provided' })
  6. let token = req.body.token
  7. db.table('users').where('token', token).then((user) => {
  8. if(user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
  9. return res.json({ success: true })
  10. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  11. }
  12. tokenController.list = function(req, res, next){
  13. if(req.headers.auth === undefined) return res.json({ success: false, description: 'No token provided' })
  14. let token = req.headers.auth
  15. db.table('users').where('token', token).then((user) => {
  16. if(user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
  17. return res.json({ success: true, token: token })
  18. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  19. }
  20. tokenController.change = function(req, res, next){
  21. if(req.headers.auth !== config.adminToken)
  22. return res.status(401).json({ success: false, description: 'not-authorized'})
  23. let type = req.body.type
  24. let token = req.body.token
  25. if(type === undefined) return res.json({ success: false, description: 'No type provided.' })
  26. if(token === undefined) return res.json({ success: false, description: 'No token provided.' })
  27. if(type !== 'client' && type !== 'admin') return res.json({ success: false, description: 'Wrong type provided.' })
  28. db.table('tokens').where('name', type).update({ value: token, timestamp: Math.floor(Date.now() / 1000) })
  29. .then(() => {
  30. if(type === 'client')
  31. config.clientToken = token
  32. else if(type === 'admin')
  33. config.adminToken = token
  34. res.json({ success: true })
  35. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  36. }
  37. module.exports = tokenController