tokenController.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const config = require('../config.js');
  2. const db = require('knex')(config.database);
  3. const randomstring = require('randomstring');
  4. const utils = require('./utilsController.js');
  5. const tokenController = {};
  6. tokenController.verify = async (req, res, next) => {
  7. const token = req.body.token;
  8. if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' });
  9. const user = await db.table('users').where('token', token).first();
  10. if (!user) return res.status(401).json({ success: false, description: 'Invalid token' });
  11. return res.json({ success: true, username: user.username });
  12. };
  13. tokenController.list = async (req, res, next) => {
  14. const {user, response} = await utils.authorize(req, res);
  15. if(!user) return response;
  16. return res.json({ success: true, token: user.token });
  17. };
  18. tokenController.change = async (req, res, next) => {
  19. const {user, response} = await utils.authorize(req, res);
  20. if(!user) return response;
  21. const newtoken = randomstring.generate(64);
  22. await db.table('users').where('token', user.token).update({
  23. token: newtoken,
  24. timestamp: Math.floor(Date.now() / 1000)
  25. });
  26. res.json({ success: true, token: newtoken });
  27. };
  28. module.exports = tokenController;