Repository navigation
Expand file tree
/
Copy pathauth.js
More file actions
106 lines (100 loc) · 2.63 KB
/
Copy pathauth.js
File metadata and controls
106 lines (100 loc) · 2.63 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
98
99
100
101
102
103
104
105
106
const { validationResult } = require('express-validator/check');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
exports.signup = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error = new Error('Validation failed.');
error.statusCode = 422;
error.data = errors.array();
throw error;
}
const email = req.body.email;
const name = req.body.name;
const password = req.body.password;
try {
const hashedPw = await bcrypt.hash(password, 12);
const user = new User({
email: email,
password: hashedPw,
name: name
});
const result = await user.save();
res.status(201).json({ message: 'User created!', userId: result._id });
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
exports.login = async (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
let loadedUser;
try {
const user = await User.findOne({ email: email });
if (!user) {
const error = new Error('A user with this email could not be found.');
error.statusCode = 401;
throw error;
}
loadedUser = user;
const isEqual = await bcrypt.compare(password, user.password);
if (!isEqual) {
const error = new Error('Wrong password!');
error.statusCode = 401;
throw error;
}
const token = jwt.sign(
{
email: loadedUser.email,
userId: loadedUser._id.toString()
},
'secretsecretsecret',
{ expiresIn: '1h' }
);
res.status(200).json({ token: token, userId: loadedUser._id.toString() });
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
exports.getUserStatus = async (req, res, next) => {
try {
const user = await User.findById(req.userId);
if (!user) {
const error = new Error('User not found.');
error.statusCode = 404;
throw error;
}
res.status(200).json({ status: user.status });
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
exports.updateUserStatus = async (req, res, next) => {
const newStatus = req.body.status;
try {
const user = await User.findById(req.userId);
if (!user) {
const error = new Error('User not found.');
error.statusCode = 404;
throw error;
}
user.status = newStatus;
await user.save();
res.status(200).json({ message: 'User updated.' });
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};