login.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import bcrypt from 'bcrypt';
  2. import { User, Syslog, ServerSettings } from '../database/config.js';
  3. // Login page
  4. export const Login = async function(req,res){
  5. if (req.session.userID) { res.redirect("/dashboard"); return; }
  6. let authentication = await ServerSettings.findOne({ where: { key: 'authentication' }});
  7. if (!authentication) { await ServerSettings.create({ key: 'authentication', value: 'default' }); }
  8. authentication = await ServerSettings.findOne({ where: { key: 'authentication' }});
  9. if (authentication.value == 'localhost' && req.hostname == 'localhost') {
  10. req.session.username = 'Localhost';
  11. req.session.userID = '00000000-0000-0000-0000-000000000000';
  12. req.session.role = 'admin';
  13. res.redirect("/dashboard");
  14. return;
  15. } else if (authentication.value == 'no_auth') {
  16. req.session.username = 'No Auth';
  17. req.session.userID = '00000000-0000-0000-0000-000000000000';
  18. req.session.role = 'admin';
  19. res.redirect("/dashboard");
  20. return;
  21. }
  22. res.render("login",{
  23. "error":"",
  24. });
  25. }
  26. // Submit login
  27. export const submitLogin = async function(req,res){
  28. const { password } = req.body;
  29. let email = req.body.email.toLowerCase();
  30. let error = '';
  31. if (!email || !password) { error = "Invalid credentials."; }
  32. let user = await User.findOne({ where: { email: email }});
  33. if (!user || !await bcrypt.compare(password, user.password)) { error = "Invalid credentials."; }
  34. if (error) { res.render("login",{ "error":error }); return; }
  35. else {
  36. req.session.username = user.username;
  37. req.session.userID = user.userID;
  38. req.session.role = user.role;
  39. res.redirect("/dashboard");
  40. }
  41. }
  42. // Logout
  43. export const Logout = function(req,res){
  44. req.session.destroy(() => {
  45. res.redirect("/login");
  46. });
  47. }