Hi rajivb,
I was in a spot where I had to tie an existing PHP site in with a
Django site. I did not want folks to be able to access the PHP part
of the site unless the following conditions applied:
(1) they were logged in with the Django app, and
(2) they did NOT belong to the "Sales" group
Here is the PHP code that I used to implement that:
---------- cut here ----------
<?php
require(dirname($_SERVER['DOCUMENT_ROOT']) . "/config/db.php");
$authenticated = false;
if(array_key_exists('sessionid',$_COOKIE)) {
$sessionid = $_COOKIE['sessionid'];
$dbj = get_django();
$result = $dbj->query("select * from django_session where
session_key='$sessionid'");
if($row = $result->fetch(PDO::FETCH_ASSOC)) {
$raw_data = base64_decode($row['session_data']);
$raw_arr = explode('_auth_user_id', $raw_data);
$len = ord(substr($raw_arr[1],3,1));
$dec = 0;
while($len > 0) {
$dec <<= 8;
$byte = ord(substr($raw_arr[1],3+$len,1));
$dec |= $byte;
$len -= 1;
}
$result = $dbj->query("select is_active from auth_user where
id=$dec");
if($row = $result->fetch(PDO::FETCH_ASSOC)) {
if($row['is_active']) {
$result = $dbj->query("select count(*) from
auth_user_groups t1 left join auth_group t2 on t1.group_id=
t2.id" .
" where t1.user_id=$dec and
t2.name='Sales'");
$row = $result->fetch(PDO::FETCH_NUM);
if($row[0] == 0) {
$authenticated = true;
}
}
}
}
else {
$error_info = $result->errorInfo();
syslog(LOG_DEBUG, sprintf("hbadmin/index.php: SQLSTATE=%s,
error_code=%s, error_message=%s",
$error_info[0], $error_info[2], $error_info[2]));
}
}
if(!$authenticated) {
header("Location: /accounts/login?next=/hbadmin/");
exit;
}
?>
---------- cut here ----------
A few notes...
The get_django() function (defined elsewhere) returned a PHP PDO
object to my Django database. Basically the code makes sure they have
a Django session. It grabs their session data, which is a base64
encoded pickled object. It's not easy to decode a pickled python
object in PHP, but I decode just enough to grab the user id of the
logged in user.
By the way, this is on a secure site and both PHP and Django are
configured to use secure cookies. Also I really need to update that
first query so that an expired session key cannot be returned.. Right
now that app is in-house only and I will update it before it is
online.
--gordy