-
Notifications
You must be signed in to change notification settings - Fork 1
/
login.js
34 lines (28 loc) · 963 Bytes
/
login.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
import bcrypt from 'bcrypt';
import chalk from 'chalk';
import User from "../models/user.js";
const login = async (req, res) => {
try {
const body = req.body;
if (!body.email) {
throw new Error('Email is undefined');
}
if (!body.password) {
throw new Error('Password is undefined');
}
const matchingUser = await User.findOne({ email: body.email });
if (!matchingUser) {
throw new Error(`User of email "${body.email}" doesn't exist`);
}
if (!await bcrypt.compare(body.password, matchingUser.password)) {
throw new Error(`Wrong password`);
}
console.log(chalk.cyan.bold('[Login]') + ` Found user: ${matchingUser.email}`);
res.json({ userId: matchingUser._id });
}
catch (error) {
console.log(error);
res.status(400).json({ error: error.message });
}
};
export { login };