login.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import bcrypt from 'bcrypt';
  2. import { User, Syslog } from '../database/models.js';
  3. // Environment variable to disable authentication.
  4. const no_auth = process.env.NO_AUTH || false;
  5. export const Login = function(req,res){
  6. if (req.session.username) { res.redirect("/dashboard"); }
  7. else { res.render("login",{ "error":"", }); }
  8. }
  9. export const Logout = function(req,res){
  10. req.session.destroy(() => {
  11. res.redirect("/login");
  12. });
  13. }
  14. export const submitLogin = async function(req,res){
  15. // Grab values from the form.
  16. let { email, password } = req.body;
  17. // Convert the email to lowercase.
  18. email = email.toLowerCase();
  19. // Create an admin session if NO_AUTH is enabled and the user is on localhost.
  20. if (no_auth && req.hostname == 'localhost') {
  21. req.session.username = 'Localhost';
  22. req.session.userID = '';
  23. req.session.role = 'admin';
  24. res.redirect("/dashboard");
  25. return;
  26. }
  27. // Check that all fields are filled out.
  28. if (!email || !password) {
  29. res.render("login",{
  30. "error":"Please fill in all fields.",
  31. });
  32. return;
  33. }
  34. // Check that the user exists.
  35. let user = await User.findOne({ where: { email: email }});
  36. if (!user) {
  37. res.render("login",{
  38. "error":"Invalid credentials.",
  39. });
  40. return;
  41. }
  42. // Check that the password is correct.
  43. let password_check = await bcrypt.compare( password, user.password);
  44. // If the password is incorrect, log the failed login attempt.
  45. if (!password_check) {
  46. res.render("login",{
  47. "error":"Invalid credentials.",
  48. });
  49. const syslog = await Syslog.create({
  50. user: null,
  51. email: email,
  52. event: "Bad Login",
  53. message: "Invalid password",
  54. ip: req.socket.remoteAddress
  55. });
  56. return;
  57. }
  58. // Successful login. Create the user session.
  59. req.session.username = user.username;
  60. req.session.userID = user.userID;
  61. req.session.role = user.role;
  62. // Update the last login time.
  63. let date = new Date();
  64. let new_login = date.toLocaleString();
  65. await User.update({ lastLogin: new_login }, { where: { userID: user.userID}});
  66. // Create a login entry.
  67. const syslog = await Syslog.create({
  68. user: req.session.username,
  69. email: email,
  70. event: "Successful Login",
  71. message: "User logged in successfully",
  72. ip: req.socket.remoteAddress
  73. });
  74. // Redirect to the dashboard.
  75. res.redirect("/dashboard");
  76. }