Source for file GuiUserManager.php

Documentation is available at GuiUserManager.php

  1. <?Php
  2. /**
  3.  * 
  4.  * GuiUserManager.php
  5.  *
  6.  * Long description for file:
  7.  * Class to handle User login, authetication, authorisation
  8.  * for for anoy_auth and ad_auth, alpha code is included for
  9.  * drupal_auth and sql_auth.
  10.  *
  11.  * @package     FreeNAC
  12.  * @author      Sean Boran (FreeNAC Core Team)
  13.  * @copyright   2008 FreeNAC
  14.  * @license     http://www.gnu.org/copyleft/gpl.html   GNU Public License Version 3
  15.  * @version     SVN: $Id$
  16.  * @link        http://freenac.net
  17.  *
  18.  */
  19.  
  20.  
  21.  
  22. class GuiUserManager extends WebCommon 
  23. {
  24.   private $props=array();      // See also WebCommon and Common
  25.  
  26.  
  27.   function __construct($debuglevel=1)
  28.   {
  29.     parent::__construct();     // See also WebCommon and Common
  30.     $this->logger->setDebugLevel($debuglevel);  // 3 for max debugging
  31.     $this->debug(" __construct(), debug=" .$debuglevel1);
  32.   }
  33.  
  34.   public function isValidUserName ($in_user_name)
  35.   {
  36.     if ($in_user_name=='' or ereg('[^[:alnum:] _-]'$in_user_name=== TRUE)
  37.       return FALSE;
  38.     else
  39.       return TRUE;
  40.   }
  41.  
  42.   // Kill old sessions
  43.   private function killSession ($userid=0)
  44.   {
  45.     if ($userid 0{
  46.         if (isset($_COOKIE[session_name()])) {  
  47.           // delete cookie, set timout negative, but not sure if it wroks
  48.           // Cannot send session cache limiter - headers already sent
  49.           setcookie(session_name()''time()-3600'/');
  50.         }
  51.         $_SESSION array();  // Unset all of the session variables
  52.         if (strlen(session_id()) 0)  {
  53.           session_destroy();
  54.           #$this->debug("killSession- session_destroy", 3);
  55.         }
  56.         #TBD $this->clearLogins($userid);
  57.     }
  58.   }
  59.  
  60.  
  61.   // Generate & remember new session
  62.   private function newSession ($userid=0)
  63.   {
  64.     global $sess_time;
  65.     global $ad_auth$anon_auth$sql_auth$drupal_auth$drupal_db;                // config.inc
  66.     $this->debug("newSession() userid=$userid"3);
  67.     $conn $this->getConnection();
  68.  
  69.     //if ($userid > 0) {     // do we really care if user=0?
  70.         // new session
  71.         include('session.inc.php');      // retrieve session
  72.         $this->debug("newSession(): new session timeout/id/name=$sess_time
  73.           .session_id(.", " .session_name());
  74.         $session_id session_id();
  75.  
  76. #      $q = <<<EOQ
  77. #INSERT INTO LoggedInUsers(uid, session_id, last_access)
  78. #     VALUES('$userid', '$session_id', NOW())
  79. #EOQ;
  80.       #$this->logger->debug($q, 2);
  81.       #if (! $conn->query($q)  ) {
  82.       #  $this->logger->logit($q .'; error: ' .$conn->error  );
  83.       #  throw new DatabaseErrorException($conn->error);
  84.       #}
  85.  
  86.       // initialise session data
  87.          $_SESSION['uid']=$userid;
  88.          $_SESSION['username']='';
  89.          $_SESSION['email']   ='';
  90.          $_SESSION['firstname']='';
  91.          $_SESSION['lastname']='';
  92.          $_SESSION['organisation']='';
  93.          $_SESSION['tel']='';
  94.          $_SESSION['address']='';
  95.          $_SESSION['login_data']='';
  96.          $_SESSION['GuiVlanRights']='';
  97.          $_SESSION['nac_rights_text']="none"// default is full access
  98.  
  99.  
  100.       if ($drupal_auth===true{
  101.         $this->logger->debug("newSession(): get user values from drupal");
  102.         // find all available fields, then store them in SESSION
  103.         $field_names=array();
  104.         $q="SELECT name from $drupal_db.profile_fields";
  105.         $this->logger->debug($q2);
  106.         $results $conn->query($q);
  107.         if ($results === FALSEthrow new DatabaseErrorException($conn->error);
  108.         while (($row $results->fetch_assoc()) !== NULL{
  109.           $field_names[]=$row['name'];
  110.           $this->debug("found fieldname   {$row['name']}",  3);
  111.         }
  112.  
  113.         foreach ($field_names as $field_name{
  114.           $q=<<<TXT
  115. SELECT title, name, pv.value 
  116.   FROM $drupal_db.profile_fields pf left join $drupal_db.profile_values pv on pf.fid=pv.fid 
  117.   WHERE name='{$field_name}' AND uid={$userid};
  118. TXT;
  119.           $this->debug($q2);
  120.           $results $conn->query($q);
  121.           if ($results === FALSEthrow new DatabaseErrorException($conn->error);
  122.           while (($row $results->fetch_assoc()) !== NULL{
  123.             $_SESSION[$field_name]=$row['value'];
  124.             $this->debug("Store SESSION {$field_name}={$row['value']}",  1);
  125.           }
  126.         }
  127.  
  128.  
  129.         $q="select * from $drupal_db.users WHERE uid={$userid}";
  130.         $this->debug($q2);
  131.         $results $conn->query($q);
  132.         if ($results === FALSEthrow new DatabaseErrorException($conn->error);
  133.         while (($row $results->fetch_assoc()) !== NULL{
  134.          $_SESSION['username']=$row['name'];
  135.          $_SESSION['mail']=$row['mail'];
  136.         }
  137.  
  138.         // save for later
  139.         $_SESSION['uid']=$userid;
  140.         $_SESSION['login_data']=$_SESSION['profile_forename'
  141.           .' ' .$_SESSION['profile_familyname';
  142.         $this->loggui("Web login drupal_auth: uid=$uid$_SESSION['login_data']);
  143.  
  144.  
  145.       else if ($ad_auth===true{   // we have a userid from The Apache AD login
  146.  
  147.         $q "SELECT * FROM users WHERE id = '$userid' LIMIT 1";
  148.         $this->debug($q2);
  149.         $results $conn->query($q);
  150.         if ($results === FALSEthrow new DatabaseErrorException($conn->error);
  151.         while (($row $results->fetch_assoc()) !== NULL{
  152.           $_SESSION['uid']=$userid;
  153.           $_SESSION['db_name']='opennac';
  154.           $_SESSION['username']=$row['username'];
  155.           $_SESSION['email']   =$row['rfc822mailbox'];
  156.           $_SESSION['firstname']=$row['GivenName'];
  157.           $_SESSION['lastname']=$row['Surname'];
  158.           $_SESSION['organisation']=$row['Department'];
  159.           $_SESSION['nac_rights']=$row['nac_rights'];
  160.           $_SESSION['GuiVlanRights']=$row['GuiVlanRights'];
  161.           $_SESSION['login_data']=$_SESSION['firstname'.' ' .$_SESSION['lastname';
  162.  
  163.           if ($_SESSION['nac_rights']>=1{
  164.             if ($_SESSION['nac_rights'== 99)
  165.               $_SESSION['nac_rights_text']="administrator";
  166.             else if ($_SESSION['nac_rights'== 2)
  167.               $_SESSION['nac_rights_text']="edit";
  168.             else if ($_SESSION['nac_rights'== 4)
  169.               $_SESSION['nac_rights_text']="Helpdesk";
  170.             else
  171.               $_SESSION['nac_rights_text']="read-only";
  172.           }
  173.         }
  174.         $this->loggui("Web login ad_auth: " .$_SESSION['login_data']);
  175.  
  176.       else if ($anon_auth===true{   // we know almost nothing
  177.          $_SESSION['login_data']='Anonymous '$_SERVER['REMOTE_ADDR'];
  178.          $_SESSION['nac_rights_text']="administrator"// default is full access
  179.          $_SESSION['nac_rights'99;
  180.          $_SESSION['GuiVlanRights']='';
  181.          $this->loggui("Web login anonymous: uid=$userid$_SESSION['login_data']);
  182.  
  183.       else {    // should never get her!
  184.         throw new InvalidLoginException("Neither _auth method is set");
  185.       }
  186.       
  187.       if ($this->logger->getDebugLevel()>2{
  188.         var_dump($_SESSION);      // debugging: show user details
  189.       }
  190.     //}
  191.  
  192.   }
  193.  
  194.   /**
  195.    * processLogin: allow SQL login: alpha code
  196.    * - verify that username and password are valid
  197.    * - clear out existing login information for user. (if any)
  198.    * - log user into table (associate SID with user name).
  199.    */
  200.   public function processLogin($in_user_name$in_user_passwd)
  201.   {
  202.     $this->debug("processLogin"2);
  203.     #echo "processLogin <br>";
  204.     // 1. internal arg checking.
  205.     if ($in_user_name == '' || $in_user_passwd == '')
  206.       throw new InvalidArgumentException();
  207.  
  208.     try
  209.     {
  210.       $conn $this->getConnection();
  211.  
  212.       // confirmUser also validates that the
  213.       // username and password are secure and are not
  214.       // attempts at SQL injection attacks ...
  215.       // Throws an InvalidLoginException if
  216.       // the username or password is not valid.
  217.       $userid $this->confirmUser($in_user_name$in_user_passwd$conn);
  218.  
  219.       $this->killSession($userid);
  220.       $this->newSession ($userid);
  221.  
  222.     }
  223.     catch (Exception $e{
  224.       throw $e;
  225.     }
  226.     // our work here is done.  clean up and exit.
  227.     $conn->close();
  228.   }
  229.  
  230.  
  231.   /**
  232.    * processADLogin: allow anobymous & active directory login
  233.    * - verify that username and password are valid
  234.    * - clear out existing login information for user. (if any)
  235.    * - log user into table (associate SID with user name).
  236.    * Sql and drupal login are not yet integrated.
  237.    */
  238.   public function processAdLogin()
  239.   {
  240.     $this->debug("processAdLogin"2);
  241.     try
  242.     {
  243.       $conn $this->getConnection();
  244.       $userid $this->confirmAdUser($conn);
  245.       $this->killSession($userid);
  246.       $this->newSession ($userid);
  247.     }
  248.     catch (Exception $e{
  249.       throw $e;
  250.     }
  251.     // our work here is done.  clean up and exit.
  252.     $conn->close();
  253.   }
  254.  
  255.  
  256.  
  257.   private function confirmAdUser$in_db_conn NULL)
  258.   {
  259.     global $ad_auth$anon_auth;
  260.  
  261.     $userid=-1;     # invalid
  262.     $this->debug("confirmAdUser()"3);
  263.  
  264.     if !isset($ad_auth|| !isset($anon_auth) ) 
  265.         throw new InvalidLoginException("No authentication method has been set, please set ad_auth or anon_auth.");
  266.  
  267.     if ( ($ad_auth===false&& ($anon_auth===false) ) 
  268.         throw new InvalidLoginException("No authentication method has been set, set either ad_auth or anon_auth to true");
  269.  
  270.     if ($ad_auth===true{      // Enforce Active Directory login
  271.       if !isset($_SERVER['PHP_AUTH_USER']|| !$_SERVER['PHP_AUTH_USER']{
  272.         throw new InvalidLoginException("PHP_AUTH_USER not set");
  273.       }
  274.  
  275.     else if ($anon_auth===true{
  276.       $this->logit('Anonymous anon_auth=true so no user authentication');
  277.       return $userid=1;            // no further processing
  278.     }
  279.  
  280.     // 1. make sure we have a database connection.
  281.     if ($in_db_conn==NULL$conn=$this->getConnection()else $conn=$in_db_conn;
  282.  
  283.     try {
  284.       // 2. make sure incoming username is safe for queries.
  285.       $uname $this->sqlescape($_SERVER['PHP_AUTH_USER']);
  286.  
  287.       #$this->debug("Checking user $uname in NAC users table  ..", 2);
  288.       $q = <<<EOQ
  289. SELECT * FROM users WHERE username = '$uname'
  290. EOQ;
  291.       $this->debug($q3);
  292.       $results @$conn->query($q);
  293.       if ($results === FALSE)
  294.         throw new DatabaseErrorException($conn->error);
  295.  
  296.       // 4. re-confirm the name/id
  297.       while (($row $results->fetch_assoc()) !== NULL)
  298.       {
  299.             $userid $row['id'];
  300.             break;    // just take first match?
  301.       }
  302.       $results->close();
  303.  
  304.     catch (Exception $e{
  305.       throw $e;
  306.     }
  307.  
  308.     // only clean up what we allocated.
  309.     if ($in_db_conn === NULL)
  310.       $conn->close();
  311.  
  312.     $this->debug("userid=$userid"3);
  313.     // throw on failure, or return the user ID on success.
  314.     if ($userid==-1)
  315.       throw new InvalidLoginException("user=$uname");
  316.  
  317.     return $userid;
  318.   }
  319.  
  320.   /**
  321.    * confirmUser()
  322.    * Alpha code for drupal, sql login.
  323.    */
  324.   private function confirmUser$in_uname$in_user_passwd$in_db_conn NULL)
  325.   {
  326.     global $drupal_auth$drupal_db$sql_auth$ad_auth;   // config.inc
  327.     $this->debug("confirmUser()"3);
  328.     #echo "confirmUser <br>";
  329.     $login_ok FALSE;
  330.     $userid=-1;     # invalid
  331.  
  332.     // 1. make sure we have a database connection.
  333.     if ($in_db_conn==NULL$conn=$this->getConnection()else $conn=$in_db_conn;
  334.  
  335.     try {
  336.       // 2. make sure incoming username is safe for queries.
  337.       $uname $this->sqlescape($in_uname);
  338.  
  339.       // 3. get the record with this username
  340.       //    either from users, or drupal users
  341.       if ($drupal_auth===true{
  342.         $this->debug("Checking user in drupal DB .."2);
  343.         $q = <<<EOQ
  344. SELECT uid,pass FROM $drupal_db.users
  345.  WHERE name = '$uname'
  346. EOQ;
  347.         
  348.       else if ($sql_auth===true{
  349.         $this->debug("Checking user in NAC users table  .."2);
  350.         $q = <<<EOQ
  351. SELECT * FROM users
  352.  WHERE username = '$uname'
  353. EOQ;
  354.       else if ($ad_auth===true{
  355.         $this->debug("Checking user in NAC users table  .."2);
  356.         $q = <<<EOQ
  357. SELECT * FROM users
  358.  WHERE username = '$uname'
  359. EOQ;
  360.       }
  361.  
  362.       $results @$conn->query($q);
  363.       if ($results === FALSE)
  364.         throw new DatabaseErrorException($conn->error);
  365.  
  366.       // 4. re-confirm the name and the passwords match, get userid
  367.       while (($row $results->fetch_assoc()) !== NULL)
  368.       {
  369.         $this->debug("check $uname and $in_uname"2);
  370.         if (strcasecmp($uname$in_uname== 0{
  371.           $this->debug("user name match, check password.."2);
  372.  
  373.           // good, name matched.  does password?
  374.           if ($ad_auth===true{   // for AD, don't check password
  375.             $login_ok TRUE;
  376.             $userid $row['uid'];
  377.  
  378.           else if (md5($in_user_passwd== $row['pass']{
  379.             $this->debug("password ok"2);
  380.             $login_ok TRUE;
  381.             $userid $row['uid'];
  382.           }
  383.           else
  384.             $login_ok FALSE;
  385.           break;
  386.         }
  387.       }
  388.       $results->close();
  389.  
  390.     catch (Exception $e{
  391.       if ($in_db_conn === NULL and isset($conn))
  392.         $conn->close();
  393.       throw $e;
  394.     }
  395.  
  396.     // only clean up what we allocated.
  397.     if ($in_db_conn === NULL)
  398.       $conn->close();
  399.  
  400.     // throw on failure, or return the user ID on success.
  401.     if ($login_ok === FALSE)
  402.       throw new InvalidLoginException("user=$uname");
  403.  
  404.     return $userid;
  405.   }
  406.  
  407.  
  408. /**
  409.  * clearLogins()
  410.  * Alpha code for drupal or sql login
  411.  */
  412.   private function clearLogins$in_userid$in_db_conn=NULL)
  413.   {
  414.     $this->debug("clearLogins $in_userid"2);
  415.     // 0. internal arg checking
  416.     if (!is_numeric($in_userid))
  417.       throw new InvalidArgumentException();
  418.  
  419.     // 1. make sure we have a database connection.
  420.     if ($in_db_conn==NULL$conn=$this->getConnection()else $conn=$in_db_conn;
  421.  
  422.     try {
  423.       // 2. delete any rows for this user in LoggedInUsers
  424.       $query = <<<EOQ
  425. DELETE IGNORE FROM LoggedInUsers WHERE uid = $in_userid
  426. EOQ;
  427.       $this->debug($query2);
  428.       if ($conn->query($query)  ) {
  429.         throw new DatabaseErrorException($conn->error);
  430.       }
  431.     }
  432.     catch (Exception $e{
  433.       if ($in_db_conn === NULL and isset($conn))
  434.         $conn->close();
  435.       throw $e;
  436.     }
  437.  
  438.     // clean up and return.
  439.     if ($in_db_conn === NULL)
  440.       $conn->close();
  441.   }
  442.  
  443.  
  444.  
  445.   /**
  446.    * createAccount()
  447.    * Alpha code for create a new User entry for sql_auth
  448.    */
  449.   public function createAccount $in_uname$in_pw$in_fname$in_email
  450.                   $in_year$in_month$in_day)
  451.   {
  452.     // 0. quick input validation
  453.     if ($in_pw == '' or $in_fname == '' or !$this->isValidUserName($in_uname)) {
  454.       throw new InvalidArgumentException();
  455.     }
  456.  
  457.     // 1. get a database connection with which to work. throws on failure.
  458.     $conn $this->getConnection();
  459.  
  460.     try
  461.     {
  462.       // 2. make sure username doesn't already exist.
  463.       $exists FALSE;
  464.       $exists $this->userNameExists($in_uname$in_conn);
  465.       if ($exists === TRUE)
  466.         throw new UserAlreadyExistsException();
  467.  
  468.       // 3a. make sure the parameters are safe for insertion,
  469.       //      and encrypt the password for storage.
  470.       $uname $this->sqlescape($in_uname);
  471.       $fname $this->sqlescape($in_fname);
  472.       $email $this->sqlescape($in_email);
  473.       $pw md5($in_pw);
  474.  
  475.       // 3b. create query to insert new user.  we can be sure
  476.       //     the date values are SQL safe, or the checkdate
  477.       //     function call would have failed.
  478.       $qstr = <<<EOQ
  479. INSERT INTO Users (name,pass,full_name,user_email,birthdate)
  480.      VALUES ('$uname', '$pw', '$fname', '$email', '$in_year-$in_month-$in_day')
  481. EOQ;
  482.  
  483.       // 3c. insert new user
  484.       $results @$conn->query($qstr);
  485.       if ($results === FALSE)
  486.         throw new DatabaseErrorException($conn->error);
  487.  
  488.       // we want to return the newly created user ID.
  489.       $user_id $conn->insert_id;
  490.     }
  491.     catch (Exception $e{
  492.       if (isset($conn))
  493.         $conn->close();
  494.       throw $e;
  495.     }
  496.  
  497.     // clean up and exit
  498.     $conn->close();
  499.     return $user_id;
  500.   }
  501.  
  502.  
  503.  
  504.  
  505. }      // class
  506.  
  507.  
  508. ?>

Documentation generated on Mon, 17 Nov 2008 01:10:38 +0100 by phpDocumentor 1.4.0