-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathuser-contoller.js
More file actions
74 lines (58 loc) · 1.67 KB
/
user-contoller.js
File metadata and controls
74 lines (58 loc) · 1.67 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
const User = require("../model/User");
const bcrypt = require("bcryptjs");
const getAllUser = async (req, res, next) => {
let users;
try {
users = await User.find();
}
catch (err) {
console.log(err);
}
if (!users) {
return res.status(404).json({ message: "users are not found" })
}
return res.status(200).json({ users });
}
const signUp = async (req, res, next) => {
const { name, email, password } = req.body;
let existingUser;
try {
existingUser = await User.findOne({ email })
} catch (err) {
console.log(err);
}
if (existingUser) {
return res.status(400).json({ message: "User is already exists!" })
}
// Generate salt
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password, salt);
const user = new User({
name, email,
password: hashedPassword,
blogs: []
});
try {
await user.save();
return res.status(201).json({ user })
}
catch (e) { console.log(e); }
}
const logIn = async (req, res, next) => {
const { email, password } = req.body;
let existingUser;
try {
existingUser = await User.findOne({ email })
} catch (err) {
console.log(err);
}
if (!existingUser) {
return res.status(404).json({ message: "User is not found" })
}
const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(400).json({ message: "Incorrect Password!" });
}
return res.status(200).json({ user: existingUser });
}
module.exports = { getAllUser, signUp, logIn };