-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
BTVN8: Add Authorization and API Register/Login with JWT #45
base: main
Are you sure you want to change the base?
Conversation
src/routes/user.route.js
Outdated
const userRouter = express.Router(); | ||
|
||
userRouter.route("/").get(getUsers).post(createUser); | ||
userRouter.route("/").get(authMiddleware, getUsers).post(createUser); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- createUser cũng nên đặt authMiddleware nhé em
const login = async (req, res, next) => { | ||
try { | ||
const { studentCode, password } = req.body; | ||
const user = await User.findOne({ studentCode }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Em nên check user có tồn tại hay không ở đây luôn nhé, nếu không thì throw luôn ra error nhé
try { | ||
const { studentCode, password } = req.body; | ||
const user = await User.findOne({ studentCode }); | ||
const isPassword = await bcrypt.compare(password, user.password); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Nếu thằng user mà không tồn tại thì không càn phải thực hiện bước này nữa
src/controllers/auth.controller.js
Outdated
err.status = 401; | ||
throw err; | ||
} | ||
const token = jwt.sign({ userId: user._id }, process.env.SECRET_KEY, { expiresIn: "1h" }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sử dụng env cho thời gian sống của token em nhé
const token = jwt.sign({ userId: user._id }, process.env.SECRET_KEY, { expiresIn: "1h" }); | |
const token = jwt.sign({ userId: user._id }, process.env.SECRET_KEY, { expiresIn: process.env.JWT_EXPIRES_IN }); |
src/controllers/auth.controller.js
Outdated
res.status(200).json({ | ||
message: "Login successfully!", | ||
token, | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
res.status(200).json({ | |
message: "Login successfully!", | |
token, | |
}); | |
res.status(200).json({ | |
token, | |
}); |
src/controllers/auth.controller.js
Outdated
const checkUser = await User.findOne({ studentCode }); | ||
if (checkUser) { | ||
const err = new Error("Student code is exit!"); | ||
err.status = 400; | ||
throw err; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tên biến để danh từ em nhé, động từ để cho tên hàm
const checkUser = await User.findOne({ studentCode }); | |
if (checkUser) { | |
const err = new Error("Student code is exit!"); | |
err.status = 400; | |
throw err; | |
} | |
const existingUser = await User.findOne({ studentCode }); | |
if (existingUser) { | |
const err = new Error("Student code is exit!"); | |
err.status = 400; | |
throw err; | |
} |
src/middlewares/auth.middleware.js
Outdated
const authorization = req.headers.authorization; | ||
if (!authorization) { | ||
const err = new Error("Unauthorized!"); | ||
err.status = 401; | ||
throw err; | ||
} | ||
const token = authorization.split(" ")[1]; | ||
const payload = jwt.verify(token, process.env.SECRET_KEY); | ||
const userId = payload.userId; | ||
const user = await User.findById(userId); | ||
if (!user || user.role !== "admin") { | ||
const err = new Error("Unauthorized"); | ||
err.status = 401; | ||
throw err; | ||
} | ||
req.user = user; | ||
next(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hàm này em nên tách nhỏ ra cho dễ đọc chứ để cả đống logic không cách hàng gì cả. Em có thể cấu trúc lại theo sườn tham khảo như dưới nhé, chỗ trả về lỗi kia chỉ là ví dụ nhé, không phải lỗi nào cũng unauthorized, tìm hiểu thêm các lỗi khác nhé
const extractTokenFromHeader = (request) => {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
const unauthorized = () => {
const err = new Error("Unauthorized!");
err.status = 401;
throw err;
};
const authMiddleware = (req,res,next) => {
const token = extractTokenFromHeader(req)
if(!token) return unauthorized()
// verify token
// �check user
// check permission
if(!admin) return unauthorized()
next()
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
vâng ạ
em nộp bài tập về nhà ạ