shar0
shar0

Reputation: 65

Can this way auth user with role?

I don't want to use additional middleware like connect-roles, so is this sufficient enough to perform authorization?

function authWithRole(role) {
    return (req, res, next) => {
        // Check login and role.
        if (req.isAuthenticated() &&
            _.indexOf(req.user.roles, role) > -1) {
            return next();
        } else {
            res.status(404).send('<h1>404 Not Found!</h1>');
        }
    }
}

router.all('/*', authWithRole("admin"));

Could anyone provide a simpler and more practical example for performing authorization?

Upvotes: 0

Views: 26

Answers (1)

gnerkus
gnerkus

Reputation: 12019

Yes. You can perform authorization this way.

This is as simple as it gets without using any extra modules.

You should refactor:

router.all('/*', authWithRole("admin"));

to:

router.all('*', authWithRole("admin"));

Upvotes: 1

Related Questions