Skip to content

Commit 241a238

Browse files
committed
components: auth[auth_controller]
1 parent 4b43cb0 commit 241a238

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

components/auth/auth_controller.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { userModel } from '../../models/user_model';
2+
import { AppError } from '../../utils/app_error';
3+
import { catchAsyncError } from '../../utils/catch_async_error';
4+
import jwt from "jsonwebtoken";
5+
import bcrypt from "bcrypt";
6+
7+
const signUp = catchAsyncError(async (req, res, next) => {
8+
let isUserExist = await userModel.findOne({ email: req.body.email });
9+
if (isUserExist) {
10+
return next(new AppError("Account is already exist!", 409));
11+
}
12+
const user = new userModel(req.body);
13+
await user.save();
14+
15+
let token = jwt.sign(
16+
{ email: user.email, name: user.name, id: user._id, role: user.role },
17+
"JR"
18+
);
19+
res.status(201).json({ message: "success", user, token });
20+
});
21+
22+
const signIn = catchAsyncError(async (req, res, next) => {
23+
const { email, password } = req.body;
24+
let user = await userModel.findOne({ email });
25+
if (!user || !bcrypt.compareSync(password, user.password)) {
26+
return next(new AppError("Invalid email or password", 401));
27+
}
28+
let token = jwt.sign(
29+
{ email: user.email, name: user.name, id: user._id, role: user.role },
30+
"JR"
31+
);
32+
res.status(201).json({ message: "success", token });
33+
});
34+
35+
const protectedRoutes = catchAsyncError(async (req, res, next) => {
36+
const { token } = req.headers;
37+
if (!token) return next(new AppError("Token was not provided!", 401));
38+
39+
let decoded = await jwt.verify(token, "JR");
40+
41+
let user = await userModel.findById(decoded.id);
42+
if (!user) return next(new AppError("Invalid user", 404));
43+
44+
if (user.passwordChangedAt) {
45+
let passwordChangedAt = parseInt(user.passwordChangedAt.getTime() / 1000);
46+
if (passwordChangedAt > decoded.iat)
47+
return next(new AppError("Invalid token", 401));
48+
}
49+
50+
req.user = user;
51+
next();
52+
});
53+
54+
const allowedTo = (...roles) => {
55+
return catchAsyncError(async (req, res, next) => {
56+
if (!roles.includes(req.user.role))
57+
return next(
58+
new AppError(
59+
`You are not authorized to access this route. Your are ${req.user.role}`,
60+
401
61+
)
62+
);
63+
next();
64+
});
65+
};
66+
export { signUp, signIn, protectedRoutes, allowedTo };

0 commit comments

Comments
 (0)