Bialecki
Bialecki

Reputation: 31051

How do I authenticate a user in a Node app with Django authentication?

My main app is a Django app, however, for some realtime stuff, I want to use Node/Socket.IO. I'm using Redis to do some pub/sub from Django to Node (and then on to various clients). The tricky part is how do I authenticate the Node user against the Django auth?

In my Node app, I have:

io.on('connection', function (socket) {
  const subscribe = redis.createClient();
  var userId = authenticateAndGetUserId();
  subscribe.subscribe(userId + ':feed-items');

  subscribe.on('message', function (channel, message) {
    socket.emit('feed-items', JSON.parse(message));
  });

});

So my question is what's a good strategy for implementing authenticateAndGetUserId? The sessions are backed in MySQL, so I can go through there. Just curious if there's a better way to go about it.

Upvotes: 8

Views: 2768

Answers (2)

Alp
Alp

Reputation: 29739

Since you already have a redis server you could store (username, sessionkey) pairs for every logged in user, optionally with a TTL value corresponding to your session settings.

Then, every time a user requests to subscribe to a channel he sends his username, which is then checked against the redis data store.

Upvotes: 3

deltanovember
deltanovember

Reputation: 44051

On the Django side I would expose a REST API. Then on the Node.js you could do something like POST username/password to

http://yourdjangoserver.com/authenticate

Which will return some JSON with the information you need. If you wish to protect the API from public scrutiny then either make it private or protect it with something like basic auth.

restify is an npm package that makes it very easy to work with REST APIs on the Node.js side. The good thing about this architecture is it is loosely coupled. You could replace Django with anything and the client would never know.

Upvotes: 4

Related Questions