Skip to content

Commit

Permalink
user add & update validations
Browse files Browse the repository at this point in the history
  • Loading branch information
angelalvaigle committed Dec 11, 2024
1 parent b36cc0b commit 6ae9154
Show file tree
Hide file tree
Showing 8 changed files with 166 additions and 5 deletions.
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ services:
profiles: ['dev', 'prod']
build: ./users/authservice
volumes:
- ./errors:/usr/src/authservice/errors
- ./middleware:/usr/src/authservice/middleware
- ./utils:/usr/src/authservice/utils
depends_on:
- mongodb
Expand Down
90 changes: 90 additions & 0 deletions middleware/validation-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { body, param, validationResult } from 'express-validator';
import { BadRequestError } from '../errors/customErrors.js';
import User from '../user-model.js';

const withValidationErrors = (validateValues) => {
return [
validateValues,
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const errorMessages = errors.array().map((error) => error.msg);
throw new BadRequestError(errorMessages);
}
next();
},
];
};

export const validateRegisterInput = withValidationErrors([
body('name')
.notEmpty()
.withMessage('name is required')
.isLength({ max: 20 })
.withMessage('name must be no more than 20 characters long'),
body('lastName')
.notEmpty()
.withMessage('last name is required')
.isLength({ max: 20 })
.withMessage('last name must be no more than 20 characters long'),
body('username')
.notEmpty()
.withMessage('username is required')
.isLength({ max: 20 })
.withMessage('username must be no more than 20 characters long'),
body('email')
.notEmpty()
.withMessage('email is required')
.isLength({ max: 40 })
.withMessage('email must be no more than 20 characters long')
.isEmail()
.withMessage('invalid email format')
.isLength({ max: 40 })
.withMessage('email must be no more than 20 characters long')
.custom(async (email) => {
const user = await User.findOne({ email });
if (user) throw new BadRequestError('email already exists');
}),
body('password')
.notEmpty()
.withMessage('password is required')
.isLength({ min: 8 })
.withMessage('password must be at least 8 characters long')
.isLength({ max: 20 })
.withMessage('password must be no more than 20 characters long'),
]);

export const validateUpdateUserInput = withValidationErrors([
body('name')
.notEmpty()
.withMessage('name is required')
.isLength({ max: 20 })
.withMessage('name must be no more than 20 characters long'),
body('lastName')
.notEmpty()
.withMessage('last name is required')
.isLength({ max: 40 })
.withMessage('last name must be no more than 20 characters long'),
body('username')
.notEmpty()
.withMessage('username is required')
.isLength({ max: 20 })
.withMessage('username must be no more than 20 characters long'),
body('email')
.notEmpty()
.withMessage('email is required')
.isLength({ max: 40 })
.withMessage('email must be no more than 20 characters long')
.isEmail()
.withMessage('invalid email format')
.isLength({ max: 40 })
.withMessage('email must be no more than 20 characters long')
.custom(async (email, { req }) => {
const user = await User.findOne({ email });
console.log(user);
console.log(req.user);
if (user && user._id.toString() !== req.user.userId) {
throw new BadRequestError('email already exists');
}
}),
]);
29 changes: 29 additions & 0 deletions users/authservice/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion users/authservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"http-status-codes": "^2.2.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.4",
"mongodb-memory-server": "^10.1.2"
"mongodb-memory-server": "^10.1.2",
"express-validator": "^7.0.1"
},
"devDependencies": {
"@babel/preset-env": "^7.26.0",
Expand Down
29 changes: 29 additions & 0 deletions users/userservice/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion users/userservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"express": "^4.18.2",
"http-status-codes": "^2.3.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.4"
"mongoose": "^8.0.4",
"express-validator": "^7.0.1"
},
"devDependencies": {
"jest": "^29.7.0",
Expand Down
13 changes: 11 additions & 2 deletions users/userservice/user-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,22 @@ import {
updateUserController,
} from './user-controller.js';
import { authenticateUser } from './middleware/auth-middleware.js';
import {
validateRegisterInput,
validateUpdateUserInput,
} from './middleware/validation-middleware.js';

const userRouter = express.Router();

// Define la ruta para el login y asocia el controlador
userRouter.post('/adduser', addUserController);
userRouter.post('/adduser', validateRegisterInput, addUserController);
userRouter.get('/users', getUsersController);
userRouter.get('/current-user', authenticateUser, getCurrentUserController);
userRouter.patch('/update-user', authenticateUser, updateUserController);
userRouter.patch(
'/update-user',
authenticateUser,
validateUpdateUserInput,
updateUserController
);

export default userRouter;
2 changes: 1 addition & 1 deletion webapp/src/pages/Profile.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const Profile = () => {
);
setOpenSnackbar(true);
} catch (error) {
setError(error?.response?.data?.msg);
setError(error || 'An error occurred');
}
return null;
};
Expand Down

0 comments on commit 6ae9154

Please sign in to comment.