ecomm/__tests__/controllers/UserController.test.ts

87 lines
2.7 KiB
TypeScript
Raw Normal View History

2023-06-13 13:10:17 +00:00
import { Request, Response } from 'express';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { User, IUser } from '../mongoose/Schema';
import { clearJwtCookie, setJwtCookie } from '../middlewares/checkAuth.test';
import validate from 'deep-email-validator';
export async function createUser(req: Request, res: Response) {
try {
const { email, password, address } = req.body;
const isValidEmail = await validate(email);
if (!isValidEmail.valid) {
console.error('Email is invalid:', isValidEmail.validators);
return res.status(400).json({ error: 'Email is invalid' });
}
if (!(password && address)) {
return res.status(400).json({ error: 'All inputs are required' });
}
// checkIfUserExists return true if the user exists
const userExists = await User.exists({ email });
if(userExists) {
return res.status(400).json({ error: 'User already exists, Try login :)' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user: IUser = await User.create({
email,
password: hashedPassword,
address,
});
res.status(200).json({
massage: 'User created successfully'
});
} catch (error) {
console.error('Error creating user:', error);
res.status(500).json({ error: 'An error occurred while creating the user.' });
}
}
export async function login(req: Request, res: Response) {
try {
const { email, password } = req.body;
// Check if the user exists
const user: IUser | null = await User.findOne({ email });
if (!user) {
console.error('User not found');
return res.status(401).json({ error: 'Invalid email or password' });
}
// Compare the provided password with the stored password
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (!isPasswordCorrect) {
console.error('Invalid password');
return res.status(401).json({ error: 'Invalid email or password' });
}
const payload = {
userId: user._id
}
// Generate a JWT
const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1d' });
setJwtCookie(res, token);
// Send the JWT as the response
res.status(200).json({
token
});
} catch (error) {
console.error('Error during login:', error);
res.status(500).json({ error: 'An error occurred during login' });
}
}
export async function logout(req: Request, res: Response) {
try {
clearJwtCookie(res);
res.status(200).json({ message: 'Logout successful' });
} catch (error) {
console.error('Error during logout:', error);
res.status(500).json({ error: 'An error occurred during logout' });
}
}