A
A
aznhautroalvyl2019-04-10 10:36:06
Node.js
aznhautroalvyl, 2019-04-10 10:36:06

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' });
  };
}

Function call example:
app.route('/test-page')
  .get(permit('admin'), (req, res) => {
   ...
  });

The problem is to understand which user is logged in and is using the system at the moment.
I tried to make sessions, but got confused in their implementation. Code example :
app.use(session({
  secret:  'testtest',
  resave:  false,
  saveUninitialized:  true,
  cookie:  { secure:  true }
}));

How to do authentication and authorization correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Robur, 2019-04-10
@Robur

Take something ready made, passport.js for example

K
Kirill Kudryavtsev, 2019-04-10
@Deissh

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);

Usage example
router.get('/',
  token({ required: true, roles: ['admin'] }),
  someepichandler);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question