177 lines
5.6 KiB
JavaScript
177 lines
5.6 KiB
JavaScript
const db = require("../models");
|
|
const bcrypt = require("bcryptjs");
|
|
const jwt = require("jsonwebtoken");
|
|
require("dotenv").config();
|
|
|
|
const User = db.user;
|
|
const EstablishmentUser = db.EstablishmentUser;
|
|
const Establishment = db.Establishment;
|
|
|
|
|
|
//Admin user and Establishment user login
|
|
exports.login = async (req, res) => {
|
|
try {
|
|
const { email, password } = req.body;
|
|
|
|
let userRole = null;
|
|
let userData = null;
|
|
|
|
// Try EstablishmentUser first
|
|
userData = await EstablishmentUser.scope("withSensitive").findOne({ where: { email } });
|
|
if (userData) {
|
|
userRole = "EstablishmentUser";
|
|
} else {
|
|
// Try Admin user
|
|
userData = await User.scope("withSensitive").findOne({ where: { email } });
|
|
if (userData) {
|
|
userRole = "Admin";
|
|
}
|
|
}
|
|
|
|
// No user found
|
|
if (!userData) {
|
|
return res.status(404).json({ status: "failed", message: "Invalid user", data: "" });
|
|
}
|
|
|
|
// Check ACTIVE status
|
|
if (!userData.is_active) {
|
|
return res.status(403).json({ status: "failed", message: "User account is inactive", data: "" });
|
|
}
|
|
|
|
// Check password
|
|
const validPass = await bcrypt.compare(password, userData.password);
|
|
if (!validPass) {
|
|
return res.status(401).json({ status: "failed", message: "Invalid password", data: "" });
|
|
}
|
|
|
|
// Prepare token data
|
|
let tokenData = {
|
|
id: userData.id,
|
|
email: userData.email,
|
|
name: userData.name,
|
|
role: userRole,
|
|
last_login: userData.last_login,
|
|
};
|
|
|
|
if (userRole === "EstablishmentUser") {
|
|
tokenData.establishment_id = userData.establishment_id;
|
|
tokenData.establishment_data = await Establishment.findByPk(userData.establishment_id);
|
|
|
|
await EstablishmentUser.update(
|
|
{ last_login: new Date(), updated_at: new Date() },
|
|
{ where: { id: userData.id } }
|
|
);
|
|
} else {
|
|
await User.update(
|
|
{ last_login: new Date() },
|
|
{ where: { id: userData.id } }
|
|
);
|
|
}
|
|
|
|
// Generate JWT token
|
|
const token = jwt.sign(tokenData, process.env.JWT_SECRET, {
|
|
expiresIn: "6h",
|
|
});
|
|
|
|
// Set token in HTTP-only cookie (IMPORTANT PART)
|
|
const isProd = process.env.NODE_ENV === "production";
|
|
|
|
res.cookie("auth_token", token, {
|
|
httpOnly: true,
|
|
secure: isProd, // only true in production (HTTPS)
|
|
sameSite: isProd ? "none" : "lax", // 'none' requires HTTPS, so use 'lax' locally
|
|
maxAge: 6 * 60 * 60 * 1000, // 6 hours
|
|
});
|
|
|
|
|
|
// Optionally return minimal user info (WITHOUT password)
|
|
return res.status(200).json({
|
|
status: "success",
|
|
message: "Login successful",
|
|
data: tokenData,
|
|
});
|
|
|
|
// return res.status(200).json({ status: "success", message: "Login successful", data: token });
|
|
|
|
} catch (err) {
|
|
return res.status(500).json({
|
|
status: "failed",
|
|
message: err.message,
|
|
});
|
|
}
|
|
};
|
|
|
|
//logout
|
|
exports.logout = (req, res) => {
|
|
res.clearCookie("auth_token", {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === "production",
|
|
sameSite: "lax",
|
|
});
|
|
|
|
return res.status(200).json({
|
|
status: "success",
|
|
message: "Logged out successfully",
|
|
});
|
|
};
|
|
|
|
|
|
// Register new user
|
|
exports.register = async (req, res) => {
|
|
try {
|
|
const { name, email, password } = req.body;
|
|
if (!name || !email || !password)
|
|
return res.status(400).send({'status':"failed",'message':"All fields required",'data': ""});
|
|
|
|
const existing = await User.findOne({ where: { email } });
|
|
if (existing) res.status(400).send({'status':"failed",'message':"Email already used",'data': ""});
|
|
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
const newUser = await User.create({ name, email, password: hashedPassword });
|
|
|
|
res.status(201).send({'status':"success",'message':"User registered successfully",'data': newUser });
|
|
} catch (err) {
|
|
res.status(500).send({'status':"failed",'message':err.message });
|
|
}
|
|
};
|
|
|
|
// Login user
|
|
// exports.login = async (req, res) => {
|
|
// try {
|
|
// const { email, password } = req.body;
|
|
|
|
// userRole = 'EstablishmentUser'
|
|
// userData = await EstablishmentUser.findOne({ where: { email, is_active : { [Op.or]: [true, 1] } } });
|
|
// if (!userData) {
|
|
// userData = await User.findOne({ where: { email, is_active : { [Op.or]: [true, 1] } } });
|
|
// userRole = 'Admin'
|
|
// if (!userData) res.status(404).send({'status':"failed",'message':"User not found",'data': ""});
|
|
// }
|
|
|
|
|
|
// const validPass = await bcrypt.compare(password, userData.password);
|
|
// if (!validPass) res.status(401).send({'status':"failed",'message':"Invalid password",'data': ""});
|
|
|
|
|
|
// if(userRole == 'Admin')
|
|
// {
|
|
// tokenData = { id: userData.id, email: userData.email , name: userData.name , role : userRole , last_login : userData.last_login }
|
|
// await User.update({ last_login : Date() }, { where: { id: userData.id } });
|
|
// }else{
|
|
// const establishment_data = await Establishment.findByPk(userData.establishment_id);
|
|
// tokenData = { id: userData.id, email: userData.email , name: userData.name , role : userRole , establishment_id: userData.establishment_id , establishment_data , last_login : userData.last_login }
|
|
// await EstablishmentUser.update({ last_login : Date(), updated_at: new Date() }, { where: { id: userData.id } });
|
|
// }
|
|
|
|
// const token = jwt.sign(tokenData, process.env.JWT_SECRET, {
|
|
// expiresIn: "6h",
|
|
// });
|
|
|
|
// res.status(200).send({'status':"success",'message':"Login successful",'data': token });
|
|
|
|
// } catch (err) {
|
|
// res.status(500).send({'status':"failed",'message':err.message });
|
|
// }
|
|
// };
|
|
|