97 lines
2.4 KiB
JavaScript
97 lines
2.4 KiB
JavaScript
import dotenv from "dotenv";
|
|
import UserModal from "../models/user.js";
|
|
import bcrypt from "bcryptjs";
|
|
import jwt from "jsonwebtoken";
|
|
|
|
dotenv.config();
|
|
const secret = process.env.SECRET_KEY;
|
|
|
|
// This is signup
|
|
export const signup = async (req, res) => {
|
|
const { email, password, firstName, lastName } = req.body;
|
|
|
|
try {
|
|
// Check if user already exists
|
|
const oldUser = await UserModal.findOne({ email });
|
|
if (oldUser) {
|
|
return res.status(400).json({ message: "User already exists" });
|
|
}
|
|
|
|
// Hash the password
|
|
const hashedPassword = await bcrypt.hash(password, 12);
|
|
|
|
// Create new user
|
|
const result = await UserModal.create({
|
|
email,
|
|
password: hashedPassword,
|
|
firstName,
|
|
lastName,
|
|
});
|
|
|
|
// Generate JWT (if needed)
|
|
const token = jwt.sign({ email: result.email, id: result._id }, secret, { expiresIn: "7h" });
|
|
|
|
// Save the token in the user's tokens array
|
|
result.tokens.push({ token });
|
|
// Save the user
|
|
await result.save();
|
|
|
|
|
|
// console.log("ss", result)
|
|
|
|
// Send the user info and token back to the client
|
|
res.status(201).json({ result, token });
|
|
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ message: "Something went wrong" });
|
|
}
|
|
};
|
|
|
|
export const signin = async (req, res) => {
|
|
const { email, password } = req.body;
|
|
|
|
try {
|
|
const oldUser = await UserModal.findOne({ email });
|
|
if (!oldUser)
|
|
return res.status(404).json({ message: "User doesn't exist" });
|
|
|
|
const isPasswordCorrect = await bcrypt.compare(password, oldUser.password);
|
|
|
|
if (!isPasswordCorrect)
|
|
return res.status(400).json({ message: "Invalid credentials" });
|
|
|
|
// if (!oldUser.verified) {
|
|
// return res.status(401).json({ message: "User is not verified" });
|
|
// }
|
|
|
|
const token = jwt.sign({ email: oldUser.email, id: oldUser._id }, secret, {
|
|
expiresIn: "8h",
|
|
});
|
|
|
|
res.status(200).json({ result: oldUser, token });
|
|
} catch (error) {
|
|
res.status(500).json({ message: "Something went wrong" });
|
|
console.log(error);
|
|
}
|
|
};
|
|
|
|
//To show user
|
|
|
|
export const showUser = async (req, res) => {
|
|
const { id } = req.params;
|
|
try {
|
|
|
|
const user = await UserModal.findById({id});
|
|
|
|
if (!user) {
|
|
return res.status(404).json({ message: "User not found" });
|
|
}
|
|
|
|
res.status(200).json(user);
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ message: "Internal servers error" });
|
|
}
|
|
};
|