Answer the question
In order to leave comments, you need to log in
Working with sessions and tokens for authentication?
The task is to authorize the user and, depending on his rights, grant or not grant access to certain actions.
I checked for a user using the function:
function permit(username) {
return (request, response, next) => {
if (username === 'admin') {
return next();
}
response.status(403).json({ message: 'Forbidden' });
};
}
app.route('/test-page')
.get(permit('admin'), (req, res) => {
...
});
app.use(session({
secret: 'testtest',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
Answer the question
In order to leave comments, you need to log in
An example of using it as an intermediate processor (it is possible without passport.js)
export const token = ({ required, roles } = {}) => (req, res, next) =>
passport.authenticate('token', { session: false }, (err, user, info) => {
if (err || (required && !user) || (required && !~roles.indexOf(user.role))) {
return res.status(401).end();
}
req.logIn(user, { session: false }, (err) => {
if (err) return res.status(401).end();
asyncRedisClient.set(user.id, '1', 'EX', 900000); // 900000 = 15 минутам
next();
});
})(req, res, next);
router.get('/',
token({ required: true, roles: ['admin'] }),
someepichandler);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question