loginPOST.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const Route = require('../../structures/Route');
  2. const config = require('../../../../config');
  3. const db = require('knex')(config.server.database);
  4. const bcrypt = require('bcrypt');
  5. const moment = require('moment');
  6. const JWT = require('jsonwebtoken');
  7. class loginPOST extends Route {
  8. constructor() {
  9. super('/auth/login', 'post', { bypassAuth: true });
  10. }
  11. async run(req, res) {
  12. if (!req.body) return res.status(400).json({ message: 'No body provided' });
  13. const { username, password } = req.body;
  14. if (!username || !password) return res.status(401).json({ message: 'Invalid body provided' });
  15. /*
  16. Checks if the user exists
  17. */
  18. const user = await db.table('users').where('username', username).first();
  19. if (!user) return res.status(401).json({ message: 'Invalid authorization' });
  20. /*
  21. Checks if the password is right
  22. */
  23. const comparePassword = await bcrypt.compare(password, user.password);
  24. if (!comparePassword) return res.status(401).json({ message: 'Invalid authorization.' });
  25. /*
  26. Create the jwt with some data
  27. */
  28. const jwt = JWT.sign({
  29. iss: 'lolisafe',
  30. sub: user.id,
  31. iat: moment.utc().valueOf()
  32. }, config.server.secret, { expiresIn: '30d' });
  33. return res.json({
  34. message: 'Successfully logged in.',
  35. user: { username: user.username },
  36. token: jwt,
  37. apiKey: user.apiKey
  38. });
  39. }
  40. }
  41. module.exports = loginPOST;