-
Notifications
You must be signed in to change notification settings - Fork 580
/
Copy pathuserController.js
85 lines (80 loc) · 2.22 KB
/
userController.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const User = require("../models/userModel");
const bcrypt = require("bcrypt");
module.exports.login = async (req, res, next) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user)
return res.json({ msg: "Incorrect Username or Password", status: false });
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid)
return res.json({ msg: "Incorrect Username or Password", status: false });
delete user.password;
return res.json({ status: true, user });
} catch (ex) {
next(ex);
}
};
module.exports.register = async (req, res, next) => {
try {
const { username, email, password } = req.body;
const usernameCheck = await User.findOne({ username });
if (usernameCheck)
return res.json({ msg: "Username already used", status: false });
const emailCheck = await User.findOne({ email });
if (emailCheck)
return res.json({ msg: "Email already used", status: false });
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({
email,
username,
password: hashedPassword,
});
delete user.password;
return res.json({ status: true, user });
} catch (ex) {
next(ex);
}
};
module.exports.getAllUsers = async (req, res, next) => {
try {
const users = await User.find({ _id: { $ne: req.params.id } }).select([
"email",
"username",
"avatarImage",
"_id",
]);
return res.json(users);
} catch (ex) {
next(ex);
}
};
module.exports.setAvatar = async (req, res, next) => {
try {
const userId = req.params.id;
const avatarImage = req.body.image;
const userData = await User.findByIdAndUpdate(
userId,
{
isAvatarImageSet: true,
avatarImage,
},
{ new: true }
);
return res.json({
isSet: userData.isAvatarImageSet,
image: userData.avatarImage,
});
} catch (ex) {
next(ex);
}
};
module.exports.logOut = (req, res, next) => {
try {
if (!req.params.id) return res.json({ msg: "User id is required " });
onlineUsers.delete(req.params.id);
return res.status(200).send();
} catch (ex) {
next(ex);
}
};