handle empty companies
[Pman.Core] / DataObjects / Core_person.php
index 02d42ea..5160b4e 100644 (file)
@@ -50,10 +50,14 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
     
     /* the code above is auto generated do not remove the tag below */
     ###END_AUTOCODE
+    
+    static $authUser = false;
+    
  
     function owner()
     {
-        $p = DB_DataObject::Factory($this->tableName());
+        // this might be a Person in some old code? 
+        $p = DB_DataObject::Factory('core_person');
         $p->get($this->owner_id);
         return $p;
     }
@@ -172,18 +176,13 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
             // h embeds images here..
             $body = $mime->get();
             $headers = $mime->headers($headers);
-            
         }
         
-         
-        
         return array(
             'recipients' => $recipents,
             'headers'    => $headers,
             'body'      => $body
         );
-        
-        
     }
     
     
@@ -195,10 +194,8 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
      */
     function sendTemplate($templateFile, $args)
     {
-        
         $ar = $this->buildMail($templateFile, $args);
       
-        
         //print_r($recipents);exit;
         $mailOptions = PEAR::getStaticProperty('Mail','options');
         $mail = Mail::factory("SMTP",$mailOptions);
@@ -211,7 +208,6 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         error_reporting($oe);
        
         return $ret;
-    
     }
     
   
@@ -240,6 +236,7 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
             
             $sesPrefix = $this->sesPrefix();
        
+            self::$authUser = false;
             $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
             
             return false;
@@ -260,22 +257,26 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
        
         $sesPrefix = $this->sesPrefix();
         
+        if (self::$authUser) {
+            return self::$authUser;
+        }
+        
+        
         if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
             // in session...
             $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
-             
             $u = DB_DataObject::factory($this->tableName());
+            $u->autoJoin();
             if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
-              
-                return $u->verifyAuth();  // got authentication...
-                
-    
+                if ($u->verifyAuth()) {
+                    self::$authUser = $u;
+                    return true;
+                }
             }
-            
             unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
             unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
             setcookie('Pman.timeout', -1, time() + (30*60), '/');
-            
+            return false;
         }
         
         // http basic auth..
@@ -289,7 +290,10 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
             &&
             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
            ) {
-            $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
+            // logged in via http auth
+            // http auth will not need session... 
+            //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
+            self::$authUser = $u;
             return true; 
         }
         //die("test init");
@@ -298,24 +302,39 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
             return false;
         }
         
-         // local auth - 
-        $default_admin = false;
-        if (!empty($ff->Pman['local_autoauth']) && 
-            ($ff->Pman['local_autoauth'] === true) &&
-            (!empty($_SERVER['SERVER_ADDR'])) &&
-            (
-                (
-                    $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
-                    $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
-                )
-                ||
+        
+        $auto_auth_allow = false;
+        if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
+            $auto_auth_allow  = true;
+        }
+        if  ( !empty($ff->Pman['local_autoauth'])
+             &&
+                !empty($_SERVER['SERVER_ADDR']) &&
+                !empty($_SERVER['REMOTE_ADDR']) &&
                 (
-                    $_SERVER['SERVER_ADDR'] == '::1' &&
-                    $_SERVER['REMOTE_ADDR'] == '::1'
+                    (
+                       $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
+                       $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
+                   )
+                   ||
+                   (
+                       $_SERVER['SERVER_ADDR'] == '::1' &&
+                       $_SERVER['REMOTE_ADDR'] == '::1'
+                   )
                 )
-            )
-        ) {
-            
+                
+            ){
+            $auto_auth_allow  = true;
+        }
+        
+        
+        if (empty($_SERVER['PATH_INFO']) ||  $_SERVER['PATH_INFO'] == '/Login') {
+            $auto_auth_allow  = false;
+        }
+        //var_dump($auto_auth_allow);
+        // local auth - 
+        $default_admin = false;
+        if ($auto_auth_allow) {
             $group = DB_DataObject::factory('core_group');
             $group->get('name', 'Administrators');
             
@@ -327,6 +346,7 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
             ");
             if($member->find(true)){
                 $default_admin = DB_DataObject::factory($this->tableName());
+                $default_admin->autoJoin();
                 if(!$default_admin->get($member->user_id)){
                     $default_admin = false;
                 }
@@ -335,27 +355,18 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         
         //var_dump($ff->Pman['local_autoauth']);         var_dump($_SERVER); exit;
         $u = DB_DataObject::factory($this->tableName());
+        $u->autoJoin();
         $ff = HTML_FlexyFramework::get();
         
-        if (!empty($ff->Pman['local_autoauth']) && 
-            (!empty($_SERVER['SERVER_ADDR'])) &&
-            (
-                (
-                    $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
-                    $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
-                )
-                ||
-                (
-                    $_SERVER['SERVER_ADDR'] == '::1' &&
-                    $_SERVER['REMOTE_ADDR'] == '::1'
-                )
-            ) &&
+        if ($auto_auth_allow && 
             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
         ) {
             
             $user = $default_admin ? $default_admin->toArray() : $u->toArray();
             
-            $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
+            // if we request other URLS.. then we get auto logged in..
+            self::$authUser = $default_admin ? $default_admin : $u;;
+            //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
             return true;
         }
         
@@ -378,10 +389,9 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
             }
         }
         if (!$n){ // authenticated as there are no users in the system...
-            return true;
+             return true;
         }
-        
-        return false;
+         return false;
         
     }
     
@@ -403,23 +413,15 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         
         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
        
-        if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
-            $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
-            
-            $u = DB_DataObject::factory($this->tableName()); // allow extending this ...
-            $u->autoJoin();
-            if ($u->get($a->id)) { /// && strlen($u->passwd)) {  // should work out the pid .. really..
-                
+        if (self::$authUser) {
+             
+            if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
                 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
                 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
-                
-                $user = clone ($u);
-                return clone($user);
-            
             }
-            unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
-            unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
-            setcookie('Pman.timeout', -1, time() + (30*60), '/');
+            // not really sure why it's cloned..
+            return   clone (self::$authUser);
+             
             
         }
         
@@ -499,6 +501,12 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         
         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
+        
+        $pp = DB_DAtaObject::Factory($this->tableName());
+        $pp->get($this->pid());
+        $pp->autoJoin();
+        
+        self::$authUser = $pp;
         // ensure it's written so that ajax calls can fetch it..
         
         
@@ -514,6 +522,8 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         
         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
         
+        self::$authUser = false;
+        
     }    
     function genPassKey ($t) 
     {
@@ -528,18 +538,24 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
     
     function checkTwoFactorAuthentication($val)
     {
+        
+        
+        // also used in login
         require_once 'System.php';
         
+        if(
+            empty($this->id) ||
+            empty($this->oath_key)
+        ) {
+            return false;
+        }
+        
         $oathtool = System::which('oathtool');
         
         if (!$oathtool) {
             return false;
         }
         
-        if(empty($this->oath_key)) {
-            return true;
-        }
-        
         $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
         
         $password = exec($cmd);
@@ -586,6 +602,9 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
     
     function company()
     {
+        if (empty($this->company_id)) {
+            return false;
+        }
         $x = DB_DataObject::factory('core_company');
         $x->autoJoin();
         $x->get($this->company_id);
@@ -611,7 +630,8 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         if (!func_num_args()) {
             return $this->lang;
         }
-        $val = array_shift(func_get_args());
+        $ar = func_get_args();
+        $val = array_shift($ar);
         if ($val == $this->lang) {
             return;
         }
@@ -624,14 +644,12 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
     
     function authUserArray()
     {
-        
         $aur = $this->toArray();
         
         if ($this->id < 1) {
             return $aur;
         }
         
-        
         //DB_DataObject::debugLevel(1);
         $c = DB_Dataobject::factory('core_company');
         $im = DB_Dataobject::factory('Images');
@@ -675,6 +693,20 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         $aur['oath_key'] = '';
         
         $aur['oath_key_enable'] = !empty($this->oath_key);
+        $aur['require_oath'] = 1;
+        
+        $s = DB_DataObject::Factory('core_setting');
+        $oath_require = $s->lookup('core', 'two_factor_auth_required');
+        $aur['require_oath'] = $oath_require ?  $oath_require->val : 0;
+        
+        $aur['core_person_settings'] = array();
+                
+        $core_person_settings = DB_DataObject::factory('core_person_settings');
+        $core_person_settings->setFrom(array(
+            'person_id' => $this->id
+        ));
+        
+        $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
         
         return $aur;
     }
@@ -766,48 +798,47 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
     function applyFilters($q, $au, $roo)
     {
         //DB_DataObject::DebugLevel(1);
-        if(!empty($q['_generate_oath_key'])){
-            $o = clone($this);
-            $this->generateOathKey();
-            $this->update($o);
-            $roo->jok('OK');
-        }
-        
-        // missing id for core_person mgmt
         if(!empty($q['_to_qr_code'])){
+            $person = DB_DataObject::factory('Core_person');
+            $person->id = $q['id']; 
             
-            if($q['id'] == 'is_auth') {
-                $person = $this->getAuthUser();
-            } else {
-                $person = DB_DataObject::factory('Core_person');
-                $person->get($q['id']);
+            if(!$person->find(true)) {
+                $roo->jerr('_invalid_person');
             }
             
-            $o = clone($person);
-            
-            $person->generateOathKey();
-            
-            $person->update($o);
+            $hash = $this->generateOathKey();
             
-            $qrcode = $person->generateQRCode();
+            $_SESSION[__CLASS__] = 
+                isset($_SESSION[__CLASS__]) ? 
+                    $_SESSION[__CLASS__] : array();
+            $_SESSION[__CLASS__]['oath'] = 
+                isset($_SESSION[__CLASS__]['oath']) ? 
+                    $_SESSION[__CLASS__]['oath'] : array();
+                
+            $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
+
+            $qrcode = $person->generateQRCode($hash);
             
             if(empty($qrcode)){
                 $roo->jerr('Fail to generate QR Code');
             }
             
-            $roo->jok($qrcode);
+            $roo->jdata(array(
+                'secret' => $hash,
+                'image' => $qrcode,
+                'issuer' => $person->qrCodeIssuer()
+            ));
         }
         
         if(!empty($q['two_factor_auth_code'])) {
-            
-            $person = $this;
-            
-            if(isset($q['id'])) {
-                $person = DB_DataObject::factory('core_person');
-                $person->get($q['id']);
-            }
+            $person = DB_DataObject::factory('core_person');
+            $person->get($q['id']);
+            $o = clone($person);
+            $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
             
             if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
+                $person->update($o);
+                unset($_SESSION[__CLASS__]['oath'][$person->id]);
                 $roo->jok('DONE');
             }
             
@@ -815,22 +846,12 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         }
         
         if(!empty($q['oath_key_disable'])) {
-            
-            $person = $this->getAuthUser();
-            
-            if(!empty($q['id'])) {
-                $person = DB_DataObject::factory('core_person');
-                $person->get($q['id']);
-            }
-            
-            if(empty($person)) {
-                $roo->jerr('Please login to the system');
-            }
+            $person = DB_DataObject::factory('core_person');
+            $person->get($q['id']);
             
             $o = clone($person);
             
             $person->oath_key = '';
-            
             $person->update($o);
             
             $roo->jok('DONE');
@@ -1116,16 +1137,36 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
                 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
             ");
         }
-        
+        if (isset($q['_with_group_membership'])) {
+            $this->selectAddGroupMemberships();
+        }
         
     }
     
+    function selectAddGroupMemberships()
+    {
+        $this->selectAdd("
+            
+            COALESCE((
+                SELECT
+                    GROUP_CONCAT(  core_group.name separator  '\n')
+                FROM
+                    core_group_member
+                LEFT JOIN
+                    core_group
+                ON
+                    core_group.id = core_group_member.group_id
+                WHERE
+                    core_group_member.user_id = core_person.id
+            ), '')  as member_of");
+    }
+    
     function setFromRoo($ar, $roo)
     {
-        $this->setFrom($ar);
+        $this->setFrom($ar); 
         
         if(!empty($ar['_enable_oath_key'])){
-            $this->generateOathKey();
+            $oath_key = $this->generateOathKey();
         }
         
         if (!empty($ar['passwd1'])) {
@@ -1143,7 +1184,7 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         }
         // this only applies to our owner company..
         $c = $this->company();
-        if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
+        if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
             return true;
         }
         
@@ -1420,7 +1461,7 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         return $sesPrefix;
     }
     
-    function loginPublic()
+    function loginPublic() // used where???
     {
         $this->isAuth(); // force session start..
          
@@ -1449,30 +1490,25 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
     
     function generateOathKey()
     {
-        $hex = bin2hex(openssl_random_pseudo_bytes(10));
-        
         require 'Base32.php';
         
         $base32 = new Base32();
         
-        $this->oath_key = $base32->base32_encode($hex);
-        
-        return $this->oath_key;
+        return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
     }
     
-    function generateQRCode()
+    function generateQRCode($hash)
     {
         if(
             empty($this->email) &&
-            empty($this->oath_key)
+            empty($hash)
         ){
             return false;
         }
         
-        $issuer = (empty($this->name)) ? 
-            rawurlencode('ROOJS') : rawurlencode($this->name);
+        $issuer = rawurlencode($this->qrCodeIssuer());
         
-        $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$this->oath_key}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
+        $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
         
         require_once 'Image/QRCode.php';
         
@@ -1490,4 +1526,32 @@ class Pman_Core_DataObjects_Core_person extends DB_DataObject
         return "data:image/png;base64,{$base64}";
     }
     
+    function qrCodeIssuer()
+    {
+        $pg= HTML_FlexyFramework::get()->page;
+        
+        $issuer = (empty($pg->company->name)) ?  'ROOJS' : "{$pg->company->name}";
+        
+        return $issuer;
+    }
+    
+    static function test_ADMIN_PASSWORD_RESET($pg, $to)
+    {
+        $ff = HTML_FlexyFramework::get();
+        $person = DB_DataObject::Factory('core_person');
+        $person->id = -1;
+        
+        return array(
+            'HTTP_HOST' => $_SERVER['SERVER_NAME'],
+            'person' => $person,
+            'authFrom' => 'FAKE_LINK',
+            'authKey' => 'FAKE_KEY',
+
+            'rcpts' => $to->email,
+        );
+        
+        return $content;
+    }
+    
+    
  }