Authentication as an anonymous user

I would like to reproduce how plunker manages anonymous accounts.

Plunker can recognize an anonymous user. For example, we can save the plunker as anonym, and then freeze. As a result

  • only the same user (before clearing the browser history) has full access to this plunker (for example, save changes, unfreeze).

  • if the same user opens it in another browser or other users open the same link, they cannot savechange; they owe forkhim.

On my website, I use a strategy local passport.jsfor managing named users. For instance,

router.post('/login', function (req, res, next) {
    if (!req.body.username || !req.body.password)
        return res.status(400).json({ message: 'Please fill out all fields' });

    passport.authenticate('local', function (err, user, info) {
        if (err) return next(err);
        if (user) res.json({ token: user.generateJWT() });
        else return res.status(401).json(info);
    })(req, res, next);
});

And I use localStorageto store the token. For instance,

auth.logIn = function (user) {
    return $http.post('/login', user).success(function (token) {
        $window.localStorage['account-token'] = token;
    })
};

auth.logOut = function () {
    $window.localStorage.removeItem('account-token');
};

- , passport.js - , , plunker? ?

+4
2

. :

app.get('/',
  // Authenticate using HTTP Basic credentials, with session support disabled,
  // and allow anonymous requests.
  passport.authenticate(['basic', 'anonymous'], { session: false }),
  function(req, res){
    if (req.user) {
      res.json({ username: req.user.username, email: req.user.email });
    } else {
      res.json({ anonymous: true });
    }
  });

, , . , , :

passport.use(new BasicStrategy({
  },
  function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // Find the user by username.  If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure.  Otherwise, return the authenticated `user`.
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false); }
        if (user.password != password) { return done(null, false); }
        return done(null, user);
      })
    });
  }
));

// Use the BasicStrategy within Passport.
//   This is used as a fallback in requests that prefer authentication, but
//   support unauthenticated clients.
passport.use(new AnonymousStrategy());

: - https://github.com/jaredhanson/passport-anonymous/blob/master/examples/basic/app.js

0

, cookie . , , , cookie http-.

0

Source: https://habr.com/ru/post/1675082/


All Articles