-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathuser-contoller.js
More file actions
69 lines (58 loc) · 2.3 KB
/
user-contoller.js
File metadata and controls
69 lines (58 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const User = require("../model/User");
const bcrypt = require("bcryptjs");
const { ApiResponse } = require("../utils/ApiResponse");
const { ApiError } = require("../utils/ApiError");
const getAllUser = async (req, res, next) => {
try {
const users = await User.find();
if (!users || users.length === 0) {
return res.status(404).json(new ApiError(404, "Users not found"));
}
return res.status(200).json(new ApiResponse(200, { users }, "Users fetched successfully"));
} catch (err) {
console.error(err);
return res.status(500).json(new ApiError(500, "Server error while fetching users"));
}
};
const signUp = async (req, res, next) => {
const { name, email, password } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json(new ApiError(400, "User already exists"));
}
const hashedPassword = bcrypt.hashSync(password, 10);
const user = new User({
name,
email,
password: hashedPassword,
blogs: []
});
await user.save();
return res.status(201).json(new ApiResponse(201, { user }, "User registered successfully"));
} catch (e) {
console.error(e);
return res.status(500).json(new ApiError(500, "Server error while signing up"));
}
};
const logIn = async (req, res) => {
const { email, password } = req.body;
if(!email || !password) {
return res.status(404).json(new ApiError(404, "All fields are required"));
}
try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
return res.status(404).json(new ApiError({statusCode: 404}, {message: 'User not found'}));
}
const isPasswordCorrect = await bcrypt.compare(password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(400).json(new ApiError(400, "Incorrect Password"));
}
return res.status(200).json(new ApiResponse(200, { user: existingUser }, "Login successful"));
} catch (err) {
console.error(err);
return res.status(500).json(new ApiError(500, "Server error while logging in"));
}
};
module.exports = { getAllUser, signUp, logIn };