I built an app with node.js server using express 4.12.4 and socket.io. Now I have some socket-events that should be restricted only to the admin user. Since there are tons of plugins and possibilities I'm little confused. Unfortunately all the examples I found where outdated. So if somebody may provide a minimal example it would make me really happy!
FYI: The admin frontend is based on angularjs.
This can be done easily with Passport and Passport.SocketIO.
With Passport you want to authenticate the users, or at least your admin user, and set appropriate flag like
user.admin = true
Then with passport.socketio which enables you to get the same user object in socket connection, you can easily verify whether the user is your admin user or not, and set appropriate listeners/emitters.
More details on how to set it all up:
Passport allows you to authenticate a user. That usually requires the client to either register with an ID/password or over OAuth through google/facebook etc.
If the client doesn't (yet) chooses to, or you simply don't want registration process, but still want a user, what you want to do is create and login a randomly generated user.
req.logIn
method gives you more control to login the user than using passport.local strategy (which it itself uses internally).Note: Your
user
should have anid
property, which is required for de/serialization.So now you'll have every user who first visits your site automatically logged in with a randomly generated user object. It's available as
req.user
in each middleware/request-handler.Now Passport.SocketIO plugin for Socket.IO allows you access to the same user object as
socket.request.user
in your socket connection handler.Your configuration should look something like this:
Note the
cookieParser
,secretSauce
, and if you usedsessionStore
should be the same as those that you used in your Express app, something probably like this:With all that set up, you now have access to the same user object in both your Express middlewares and your Socket.IO connection handler.