I have a site written in PHP and I am adding new features using Python and Django. In part, this will be Django authentication using the standard contribs.auth package.
As soon as someone logged in using our Django setup when they come to the PHP side, I need to see that they logged in and use the user information from the database).
What is the best way to get the user id and proof that the Django session id is valid with PHP using this Django sessionID cookie value?
My plan is to create a hash of the Django session id, my Django private key, and login ID. This value will be set as an additional cookie. Then in PHP I will extract the user ID, make a hash of this and the private key plus the cookie sessionID value of Django, and compare if they match.
I expanded the auth authorization window to set an additional cookie as soon as the user is authenticated successfully. Instead of HttpResponseRedirect, it will return HttpResponseSetAuthCookieAndRedirect.
HttpResponseSetAuthCookieAndRedirect receives request.session.session_id and user_id as an argument.
class HttpResponseSetAuthCookieAndRedirect(HttpResponse):
""" a cookie enhanced version of HttpResponseRedirect """
status_code = 302
def __init__(self, user_id, session_id, redirect_to):
HttpResponse.__init__(self)
self['Location'] = iri_to_uri(redirect_to)
my_hash=hashlib.sha512('{0}|-|{1}|-|{2}'.format(settings.SECRET_KEY,user_id,session_id)).hexdigest()
cookie_hash="{0}::{1}".format(user_id,my_hash[:64])
self.set_cookie('check', value=cookie_hash, max_age=172800, path='/', domain=None)
cookie, , Django , .
PHP,
$check_cookie=$_COOKIE['check'];
$django_cookie=$_COOKIE['sessionid'];
$check_cookie=str_replace('"','',$check_cookie);
$django_cookie=str_replace('"','',$django_cookie); //they have quotes for some reason
$parts=explode('::',$check_cookie);
$sent_user_id=(int)$parts[0];
$sent_hash=$parts[1];
$cookie_hash=hash('sha512',"$secret_key|-|$sent_user_id|-|$dj_cookie_sessionid");
$reconstructed_security_hash=$sent_user_id.'::'.substr($cookie_hash,0,64);
if($reconstructed_security_hash==$cookie_hash)
{
return $sent_user_id; //cookies are valid, and user id is the one set by Django for this session id.
}
return false; //cookies do not match
.
?