74 lines
2.3 KiB
JavaScript
74 lines
2.3 KiB
JavaScript
const bcrypt = require("bcrypt");
|
|
const jwt = require("jsonwebtoken");
|
|
const UserModel = require("../models/userModel");
|
|
const { sendResponse } = require("../middlewares/responses");
|
|
const env = require("../helpers/Env");
|
|
|
|
const secretKey = env.get("JWT_KEY"); // Replace with your own secret key
|
|
|
|
async function registerUser(req, res) {
|
|
try {
|
|
const { name, email, password } = req.body;
|
|
if (!name || !email || !password) {
|
|
return sendResponse(res, 400, {
|
|
error: "Name, email, and password are required",
|
|
});
|
|
}
|
|
const existingUser = await UserModel.findOne({ email });
|
|
if (existingUser) {
|
|
return sendResponse(res, 400, { error: "Email already exists" });
|
|
}
|
|
const user = new UserModel({ name, email, password });
|
|
await user.save();
|
|
sendResponse(res, 201, { message: "User registered successfully" });
|
|
} catch (error) {
|
|
sendResponse(res, 500, { error: "Registration failed" });
|
|
}
|
|
}
|
|
|
|
async function loginUser(req, res) {
|
|
try {
|
|
const { email, password } = req.body;
|
|
if (!email || !password) {
|
|
return sendResponse(res, 400, {
|
|
error: "Email and password are required",
|
|
});
|
|
}
|
|
const user = await UserModel.findOne({ email });
|
|
if (!user) {
|
|
return sendResponse(res, 401, { error: "Authentication failed" });
|
|
}
|
|
const passwordMatch = await bcrypt.compare(password, user.password);
|
|
if (!passwordMatch) {
|
|
return sendResponse(res, 401, { error: "Authentication failed" });
|
|
}
|
|
const token = jwt.sign({ id: user._id }, secretKey, {
|
|
expiresIn: "1h",
|
|
});
|
|
// Set the token as a cookie in the response header
|
|
res.setHeader("Set-Cookie", `token=${token}; HttpOnly; Max-Age=3600`); // 1 hour
|
|
sendResponse(res, 200, { token });
|
|
} catch (error) {
|
|
console.log(error);
|
|
sendResponse(res, 500, { error: "Login failed", error: error });
|
|
}
|
|
}
|
|
|
|
function logoutUser(req, res) {
|
|
res.setHeader("Set-Cookie", "token=; HttpOnly; Max-Age=0"); // Clear the cookie
|
|
sendResponse(res, 200, { message: "User logged out successfully" });
|
|
}
|
|
|
|
async function userProfile(res, user) {
|
|
const userId = user.id;
|
|
const userInfo = await UserModel.findOne({ _id: userId }).select("name email -_id");
|
|
sendResponse(res, 200, userInfo);
|
|
}
|
|
|
|
module.exports = {
|
|
registerUser,
|
|
loginUser,
|
|
logoutUser,
|
|
userProfile,
|
|
};
|