Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared authentication between rails and node.js with redis store

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.

like image 894
Elie Génard Avatar asked Apr 16 '13 17:04

Elie Génard


2 Answers

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.

like image 119
Tyler Morgan Avatar answered Oct 05 '22 13:10

Tyler Morgan


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

like image 29
Ashan Avatar answered Oct 05 '22 11:10

Ashan