auth.service.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @file Provides a service to handle languages and localizations.
  3. * @author Inigo Valentin
  4. * @since 4.0.0
  5. */
  6. const sha1 = require('sha1');
  7. const jwt = require('jsonwebtoken');
  8. const users = require("../controllers/user.controller.js");
  9. const config = process.env;
  10. /**
  11. * Handles localization of elements.
  12. */
  13. class AuthService {
  14. /**
  15. * Database connection.
  16. */
  17. #db;
  18. /**
  19. * Constructor.
  20. *
  21. * @param db Database connection.
  22. * @constructor
  23. */
  24. constructor(db){
  25. this.#db = db;
  26. }
  27. /**
  28. * Logs a user in.
  29. *
  30. * @param req The request received by the server.
  31. */
  32. async login(req, res){
  33. try {
  34. // Get user input
  35. const email = req.body.email ? req.body.email : "";
  36. const username = req.body.username ? req.body.username : "";
  37. const password = req.body.password;
  38. // Validate user input
  39. if (!(password && (email || username))) res.status(401).send("Credentials required");
  40. // Validate if user exist in our database
  41. const user = await User.findOne({where: {[this.#db.Sequelize.Op.or]: {username: username, email: email}}});
  42. if (user && user.password == sha1(user.hash + password)){
  43. require('dotenv').config()
  44. const {TOKEN_SECRET, TOKEN_ISSUER} = process.env;
  45. const token = jwt.sign({user: user.id}, TOKEN_SECRET, {algorithm: 'HS256', expiresIn: '5h', issuer: TOKEN_ISSUER, subject: user.username})
  46. res.send({token});
  47. }
  48. return res.status(403).send("Invalid Credentials");
  49. }
  50. catch (err) {
  51. console.log("Error logging in: " + err);
  52. return res.status(500).send("Error logging in");
  53. }
  54. }
  55. /**
  56. * Validates a token in the request.
  57. *
  58. * @param req The request received by the server.
  59. * @return An object with four values:
  60. * - success: True if the user was authenticated, false otherwise.
  61. * - user: The ID of the authenticated user, or null if no user was authenticated.
  62. * - code: A HTTP status code that can be set on the response: 200, 401, 403 or 500.
  63. * - message: A message describing the HTTP status code.
  64. */
  65. validateToken(req, res) {
  66. const token = req.body.token || req.query.token || req.headers["x-access-token"];
  67. console.log("TOKEN: " + token);
  68. if (!token) return {success: false, user: null, code: 401, message: "A token is required for authentication."};
  69. try {
  70. require('dotenv').config()
  71. const {TOKEN_SECRET, TOKEN_ISSUER} = process.env;
  72. const {exp, iss, user} = jwt.verify(token, TOKEN_SECRET);
  73. if (iss === TOKEN_ISSUER && exp < Date.now()) return {success: true, user: user, code: 200, message: "OK"};
  74. return {success: false, user: null, code: 403, message: "Invalid token."};;
  75. }
  76. catch (err) {
  77. console.log("Error validating token: " + err);
  78. return {success: false, user: null, code: 500, message: "Authentication error."};;
  79. }
  80. }
  81. }
  82. module.exports = AuthService;