1

We generally work as, doing validation and doing all sort of validation in validator and we expect that if the request reaches controller it has already been validated againsts all the application criteria, i.e., if an owner and adming both can create a user but admin can create user on any branch but owner can create user on only his branch then the route create user can be used by both admin and owner.

all kind of complex validation logic before the controller, i.e., in nest it will be in validationPipe.

is it the correct approach in nest ? or i should do this role based validation in service, and if it is okey then how to do this complex validation in class validator or should i use some other validation library such as joi. Thanks

1 Answer 1

1

By way of clean separation, think about validation layers as:

  • Data validation (errors which result in 400)
  • Authentication/user validation (401)
  • Authorization checks (403), along with:
    • Route checks
    • Data (field level) authorizations
    • Data masking

For data validation, implement Joi or Zod, as to your preference, with a validation pipe. This will ensure data arrives which is structurally valid (or it returns a 400).

For Authentication, and Route checks, implement Guards. The route checks would implement authentication (or 401) role based permissions (403), and/or something more complicated if your routes are structured well.

Finally, implement your field-level authorization (sorry, you can't set this greater than 5, because ...reasons - 403) in the handlers themselves, along with data masking (filtered queries - if no results because of restricted access, 404 or 403 as your preference).

This way you can make simple assertions at each point, with limited context to consider. This makes testing each part easier.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.