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.
auth import authenticate, login def my_view(request): username = request. POST['username'] password = request. POST['password'] user = authenticate(username=username, password=password) if user is not None: if user. is_active: login(request, user) # Redirect to a success page.
from django. contrib. auth import authenticate user = authenticate(username='john', password='secret') if user is not None: if user. is_active: print "You provided a correct username and password!" else: print "Your account has been disabled!" else: print "Your username and password were incorrect."
The way authentication works in the browser is by sending the session cookie in each request. Django then checks whether the session belongs to an authenticated user or not. So you need to catch the cookie in the response to the login and send it with every subsequent request.
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.
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.
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