I have a rails app and a node.js app and I use Devise to authenticate users. I store the session with Redis. Now I'd like that when a user go to the node app, the app checks through socket.io whether the user is logged in or not. I managed to get the session datas from redis but I don't know how to interpret them to check if the user is logged in.
Here is my code for the node app which checks if the _session_id exists in the database and retrieves the session datas:
io.set('authorization', function (data, accept) {
if (data.headers.cookie) {
data.cookie = cookie.parse(data.headers.cookie);
data.sessionID = data.cookie['_session_id'];
redis.get(data.sessionID, function (err, session) {
if (err || !session) {
accept('Error', false);
} else {
data.session = session;
console.log(session);
accept(null, true);
}
});
} else {
return accept('No cookie transmitted.', false);
}
});
This is what the console.log(session) gives me:
{I"_csrf_token:EFI"1HPglfkCCagvb1LLraU1CEEyx7AtDzztqAEPY5G5lNgY=;FI"warden.user.user.key;TI" User;F[iI""$2a$10$IHq2WAhwbaqR4WWajRE/Yu;T
How can I check if a user is logged in the rails app with the node app? Thanks
EDIT: It appears that the redis store gem I use calls a Marshalling method before storing the session in database. So I bypassed the problem by overriding the Marshalling method and stored the session datas in JSON format. It's not very elegant so if you find a better way to share sessions between rails and node.js, please let me know.
It might be easier to create your own oauth api(there's a railscast on how to do this oauth). As far as I know, devise is a ruby gem and isn't really cross-platform but oauth can be used in almost any language. You can add an oauth token to devise which should allow you to pass that token to node.js.
You can easily do it doing few tweaks to the index.js method in Rails-Cookie-Parser for Express https://github.com/instore/rails-cookie-parser library to use it without Express.
This library uses Marshal npm as its dependency
Note: You might need to decodeURIComponent("cookie value") since the original cookie is URL encoded
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With