53 lines
1.7 KiB
JavaScript
53 lines
1.7 KiB
JavaScript
// server/controller/authController.js
|
|
import bcrypt from "bcrypt";
|
|
import supabase from "../config/supabaseClient.js";
|
|
|
|
export const login = async (req, res) => {
|
|
const { username, password } = req.body;
|
|
|
|
try {
|
|
// Fetch user by username
|
|
const { data: user, error } = await supabase
|
|
.from("users")
|
|
.select("*")
|
|
.eq("username", username)
|
|
.single();
|
|
|
|
if (error || !user) {
|
|
return res.status(400).json({ message: "User not found" });
|
|
}
|
|
|
|
// Check if user is active
|
|
if (user.status !== "active") {
|
|
return res.status(403).json({ message: "User is not active" });
|
|
}
|
|
|
|
// Check password - try bcrypt first, then plain text fallback
|
|
let isValidPassword = false;
|
|
|
|
// Try bcrypt comparison first (for hashed passwords)
|
|
if (user.password.startsWith('$2b$') || user.password.startsWith('$2a$')) {
|
|
// This looks like a bcrypt hash
|
|
isValidPassword = await bcrypt.compare(password, user.password);
|
|
} else {
|
|
// Plain text fallback (for your mock data)
|
|
isValidPassword = (password === user.password);
|
|
}
|
|
|
|
if (!isValidPassword) {
|
|
return res.status(401).json({ message: "Invalid password" });
|
|
}
|
|
|
|
// Success
|
|
return res.status(200).json({
|
|
user_id: user.user_id,
|
|
username: user.username,
|
|
full_name: user.full_name,
|
|
role: user.role,
|
|
status: user.status,
|
|
});
|
|
} catch (err) {
|
|
console.error("Login error:", err);
|
|
return res.status(500).json({ message: "Server error" });
|
|
}
|
|
}; |