userActions.js
2.35 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const bcrypt = require("bcryptjs");
// handles "exception" inside of async express routes
const asyncHandler = require("express-async-handler");
const User = require("../models/userModel");
const { jwtGenerator } = require("../config/jwt");
// @desc Signup new user
// @route POST /api/users
// @access Public
const signupUser = asyncHandler(async (req, res) => {
const { username, email, password } = req.body;
if (!username || !email || !password) {
res.status(400);
throw new Error("Please fill in all fields");
}
// Check if user already exists
const userExists = await User.findOne({ email });
if (userExists) {
res.status(400);
throw new Error("User with the email already exists");
}
// Hash password (bcrypt)
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
// Create/Build user
const user = await User.create({
username,
email,
password: hashedPassword,
});
// Send response
if (user) {
// 201: Resource successfully created
res.status(201).json({
_id: user.id,
username: user.username,
email: user.email,
token: jwtGenerator(user._id),
});
} else {
res.status(400);
throw new Error("Invalid user data");
}
});
// @desc Login user
// @route POST /api/users/login
// @access Public
const loginUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
// Check email & password
const userInDB = await User.findOne({ email });
const validPassword = await bcrypt.compare(password, userInDB.password);
if (userInDB && validPassword) {
res.status(200).json({
_id: userInDB.id,
username: userInDB.username,
email: userInDB.email,
token: jwtGenerator(userInDB._id),
});
} else {
res.status(400);
throw new Error("Invalid credentials");
}
});
// @desc Get all users
// @route GET /api/users/all
// @access Public
const getAllusers = asyncHandler(async (req, res) => {
const users = await User.find()
.select("-password")
.select("-updatedAt")
.select("-createdAt")
.select("-email");
res.status(200).json(users);
});
// @desc Get user
// @route GET /api/users/self
// @access Private
const getSelf = asyncHandler(async (req, res) => {
res.status(200).json(req.user);
});
module.exports = {
signupUser,
loginUser,
getAllusers,
getSelf,
};