Skip to content

Commit 2f9059e

Browse files
Creating the SignIn method in controller to validate users
1 parent 19c139e commit 2f9059e

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

src/controllers/auth/auth.controller.ts

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
1+
import config from "../../config/config";
2+
13
import { Request, Response } from "express";
24
import User, { IUser } from "../../models/User";
5+
import bcrypt from "bcrypt";
6+
import jwt from "jsonwebtoken";
7+
8+
function createToken(user: IUser) {
9+
return jwt.sign(
10+
{
11+
id: user.id,
12+
email: user.email,
13+
},
14+
config.secretKey,
15+
{
16+
expiresIn: 60 * 60 * 24,
17+
}
18+
);
19+
}
320

421
export const signUp = async (
522
req: Request,
@@ -21,4 +38,25 @@ export const signUp = async (
2138
return res.status(201).json(newUser);
2239
};
2340

24-
export const signIn = (req: Request, res: Response) => {};
41+
export const signIn = async (
42+
req: Request,
43+
res: Response
44+
): Promise<Response> => {
45+
if (!req.body.email || !req.body.password) {
46+
return res
47+
.status(400)
48+
.json({ msg: "Please, send your email and password." });
49+
}
50+
51+
const user = await User.findOne({ email: req.body.email });
52+
if (!user) {
53+
return res.status(400).json({ msg: "User does not exixts!" });
54+
}
55+
56+
const isMatch = await bcrypt.compare(req.body.password, user.password);
57+
if (isMatch) {
58+
return res.status(201).json({ token: createToken(user) });
59+
}
60+
61+
return res.status(400).json({ msg: "The email or password are incorrect!" });
62+
};

0 commit comments

Comments
 (0)