-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserController.js
More file actions
77 lines (66 loc) · 2.19 KB
/
userController.js
File metadata and controls
77 lines (66 loc) · 2.19 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
// src/controllers/userController.js
const { validationResult } = require("express-validator");
const User = require("../models/User");
const { generateAuthToken } = require("../../providers/AuthProvider");
// Fetch All User: GET /user
exports.index = async (req, res) => {
const users = await User.find();
res.json({ message: "Success", users });
};
// Register User: POST :PREFIX:/user/register
exports.register = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
// in case request params does NOT meet the validation criteria
res.status(422).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
// Store user
const user = await User.create({ name, email, password });
// Generate auth token
const token = await generateAuthToken(user);
// SUCCESS: return response
return res.status(200).json({
msg: "User created successfully",
token: token,
user: user,
});
} catch (error) {
// ERROR: return response & print error in console
console.error("ERROR: ", error);
return res.status(500).json({ msg: "Something went wrong!" });
}
};
// Login User: POST :PREFIX:/user/login
exports.login = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
// in case request params does NOT meet the validation criteria
res.status(422).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
// Find user
const user = await User.findOne({ email }, 'name email password');
if (user) {
// verify & login user
const login = await user.login(password);
if (login) {
// Generate auth token
const token = await generateAuthToken(user);
// SUCCESS: return response
return res.status(200).json({
msg: "User created successfully",
token: token,
user: user,
});
}
}
return res.status(401).json({ msg: "Incorrect credentials!" });
} catch (error) {
// ERROR: return response & print error in console
console.error("ERROR: ", error);
return res.status(500).json({ msg: "Something went wrong!" });
}
};