Search code examples
node.jsexpressexpress-validator

Access Express Session/Request on the


I have the following code:

    router.use('*', (req, res, next) => {
        if (!req.user || req.user.adminLevel <= 0 ) {
            logger.info("User has no Admin Level to access /admin")
            res.status(401).json({"errorCode" : "403", "error" : "Forbidden" })
        }
        else {
            logger.info("User has Admin Access, performing action")
            next()
        }
    })





    router.post('/new', controller.validadeUser(), controller.validate, controller.createUser);
    validate: (req, res, next) => {
        var errors = validationResult(req);
          if (!errors.isEmpty()) {
            return res.status(422).json({ errors: errors.array() });
          } else {
            next()
        }
    },
    validadeUser: () => { 
        return [
            check('username').not().isEmpty().withMessage('Name is Required'),
            check('password').not().isEmpty().withMessage('Password is Required'),
             check('adminLevel').custom(value => {
                if (value >  REQ.USER.LEVEL)
                    return Promise.reject("You can't add " + value + " if you are only" + REQ.USER.LEVEL)

            })]
    },

    createUser: (req, res, next) => {
        logger.info("Creating User", req.body)

        const user = new User(req.body.username, req.body.email, req.body.level, req.body.adminLevel, req.body.password)
        User.newUser(user)
            .then((results) => {
                res.status(200).json({"done" : true})
            }).catch(err => {
                logger.debug("Fail to create the user", err)
                res.status(500).json({"done" : false})
            })
     }

Also, the req.user is being validade in the previous middleware. But my question is not related to security.

My question is, how can I access the session inside the controller.validadeUser() ??

On validadeUser() I don't have access to the request, neither the session. But I want to do the validation there. is it possible or do I have to split the validation and do it on the validate method?

I tried to add the parms (req, res, next) to the validadeUser but it is all null.

thanks.


Solution

  • I found how to do it. Just had to add the request on the custom validation:

    check('adminLevel').custom((admLevel, { req }) => {