updated user controller - put and post

This commit is contained in:
ak 2023-09-29 16:16:56 -07:00
parent e3a527f5ec
commit a830eb0ef4

View file

@ -5,7 +5,7 @@ const { body, validationResult } = require("express-validator");
const { default: mongoose } = require("mongoose");
// C
exports.put = [
exports.post = [
// Validate and sanitize username
body("username", "Please enter username!")
.isLength({ min: 1 })
@ -23,7 +23,7 @@ exports.put = [
// if there are validation errors, return them
if (!errors.isEmpty()) {
return res.status(400).json({
message: "Comment produced validation errors!",
message: "There were validation errors!",
errors: errors.array(),
});
}
@ -48,7 +48,7 @@ exports.put = [
await User.findByIdAndUpdate(dbUser._id, user, {});
return res.status(200).json({
message: "User updated!",
message: "User created!",
});
}),
];
@ -64,7 +64,7 @@ exports.get = asyncHandler(async (req, res, next) => {
});
// U
exports.post = [
exports.put = [
// Validate and sanitize username
body("username", "Please enter username!")
.isLength({ min: 1 })
@ -78,25 +78,7 @@ exports.post = [
.escape(),
asyncHandler(async (req, res, next) => {
// begin by authorizing token
const token = req.cookies.JWT_TOKEN;
// if token is not for this user - compares by creating another token
let opts = {
expiresIn: "1d",
};
const originalUsername = req.params.username;
const userToken = jwt.sign(
{ originalUsername },
process.env.SECRET_KEY,
opts
);
if (token != userToken) {
return res.status(403).json({
message: "Not authorized!",
});
}
// then return any validation errors
// return any validation errors
const errors = validationResult(req);
// if there are validation errors, return them
if (!errors.isEmpty()) {