Pman/Login.php
[Pman.Base] / Pman / Login.php
index f1cf949..002b18b 100644 (file)
@@ -23,14 +23,19 @@ require_once 'Pman.php';
 
 class Pman_Login extends Pman
 { 
-    
     var $masterTemplate = 'login.html';
     
+    var $ip_management = false;
+    
     function getAuth() // everyone allowed in here..
     {
         parent::getAuth(); // load company..
-        return true;
         
+        $ff = HTML_FlexyFramework::get();
+        
+        $this->ip_management = (empty($ff->Pman['ip_management'])) ? false : true;
+        
+        return true;
     }
     /**
      * Accepts:
@@ -41,7 +46,7 @@ class Pman_Login extends Pman
     function get($v, $opts=array()) 
     {
         $this->initErrorHandling();
-         
+        
          //DB_DataObject::DebugLevel(1);
         if (!empty($_REQUEST['logout'])) {
            return $this->logout();
@@ -52,7 +57,12 @@ class Pman_Login extends Pman
             //DB_Dataobject::debugLevel(5);
             $this->sendAuthUserDetails();
             exit;
-           
+        }
+        
+        if(!empty($_REQUEST['check_owner_company'])) {
+            $core_company = DB_DataObject::factory('core_company');
+            $core_company->comptype = 'OWNER';
+            $this->jok($core_company->count());
         }
         
         // might be an idea to disable this?!?
@@ -69,7 +79,6 @@ class Pman_Login extends Pman
             $this->switchPublicUser($_REQUEST['loginPublic']);
         }
         
-        
         $this->jerr("INVALID REQUEST");
         exit;
     }
@@ -78,7 +87,8 @@ class Pman_Login extends Pman
     function logout()
     {
         $ff = class_exists('HTML_FlexyFramework2') ?  HTML_FlexyFramework2::get()  :  HTML_FlexyFramework::get();
-        //DB_DAtaObject::debugLevel(1);
+        
+       //DB_DAtaObject::debugLevel(1);
         $u = $this->getAuthUser();
         //print_r($u);
         if ($u) {
@@ -119,11 +129,22 @@ class Pman_Login extends Pman
         $tbl = empty($ff->Pman['authTable']) ? 'core_person' : $ff->Pman['authTable'];
         
         $u = DB_DataObject::factory($tbl);
+        $s = DB_DataObject::factory('core_setting');
+        $require_oath_val = 1;
+        $require_oath = $s->lookup('core', 'two_factor_auth_required');
+        if(!empty($require_oath)) {
+            if($require_oath->val == 0) {
+                $require_oath_val = 0;
+            }
+        } 
+        
         if (!$u->isAuth()) {
-             
-            $this->jok(array('id' => 0)); // not logged in..
+            $this->jok(array(
+                'id' => 0
+            ));
             exit;
         }
+        
         //die("got here?");
         $au = $u->getAuthUser();
         
@@ -217,12 +238,12 @@ class Pman_Login extends Pman
         $this->jok('OK');
     }
     
-    
     var $domObj = false;
+    
     function post($v)
     {
-        
         //DB_DataObject::debugLevel(1);
+        
         if (!empty($_REQUEST['getAuthUser'])) {
             $this->sendAuthUserDetails();
             exit;
@@ -233,11 +254,38 @@ class Pman_Login extends Pman
         }
         
         if (!empty($_REQUEST['passwordRequest'])) { //|| (strpos($_REQUEST['username'], '@') < 1)) {
-            
-            return $this->passwordRequest($_REQUEST['passwordRequest']);
-            
-        }
-        
+            return $this->passwordRequest($_REQUEST['passwordRequest']);   
+        }
+        
+       if (!empty($_REQUEST['ResetPassword'])) {
+           if (empty($_REQUEST['id']) || 
+               empty($_REQUEST['ts']) ||
+               empty($_REQUEST['key']) ||
+               empty($_REQUEST['password1']) ||
+               empty($_REQUEST['password2']) ||
+               ($_REQUEST['password1'] != $_REQUEST['password2'])
+           ) {
+               $this->jerr("Invalid request to reset password");
+           }
+           
+           $this->resetPassword($_REQUEST['id'], $_REQUEST['ts'], $_REQUEST['key'], $_REQUEST['password1'] );
+       }
+       
+       
+       if (!empty($_REQUEST['_verifyCheckSum'])) {
+           if (empty($_REQUEST['id']) || 
+               empty($_REQUEST['ts']) ||
+               empty($_REQUEST['key'])
+                
+           ) {
+               $this->jerr("Invalid request to reset password");
+           }
+           
+           $this->verifyResetPassword($_REQUEST['id'], $_REQUEST['ts'], $_REQUEST['key']);
+           $this->jok("Checksum is ok");
+       }
+       
+       // this is 'classic' change password...
         if (!empty($_REQUEST['changePassword'])) {
             return $this->changePassword($_REQUEST);
         }
@@ -250,14 +298,13 @@ class Pman_Login extends Pman
        
         $u = DB_DataObject::factory($tbl);
         
-        
-        
+        $ip = $this->ip_lookup();
         // ratelimit
-        if (!empty($_SERVER['REMOTE_ADDR'])) {
+        if (!empty($ip)) {
             //DB_DataObject::DebugLevel(1);
             $e = DB_DataObject::Factory('Events');
             $e->action = 'LOGIN-BAD';
-            $e->ipaddr = $_SERVER['REMOTE_ADDR'];
+            $e->ipaddr = $ip;
             $e->whereAdd('event_when > NOW() - INTERVAL 10 MINUTE');
             if ($e->count() > 5) {
                 $this->jerror('LOGIN-RATE', "Login failures are rate limited - please try later");
@@ -285,7 +332,7 @@ class Pman_Login extends Pman
         }
         
         if(!empty($u->oath_key) && empty($_REQUEST['oath_password'])){
-            $this->jerror('LOGIN-BAD','Your account require Two-Factor Authentication');
+            $this->jerror('LOGIN-BAD','Your account requires Two-Factor Authentication');
         }
         
         // check if config allows non-owner passwords.
@@ -305,11 +352,19 @@ class Pman_Login extends Pman
             exit;
         }
         
-        if(!empty($u->oath_key) && !$u->checkTwoFactorAuthentication(trim($_REQUEST['oath_password'],"\x10"))){
+        if(
+            !empty($u->oath_key) &&
+           (
+               empty($_REQUEST['oath_password']) ||
+               !$u->checkTwoFactorAuthentication($_REQUEST['oath_password'])
+           )
+        ) {
             $this->jerror('LOGIN-BAD', 'You typed the wrong Username or Password  (3)');
             exit;
         }
         
+        $this->ip_checking();
+        
         $u->login();
         // we might need this later..
         $this->addEvent("LOGIN", false, session_id());
@@ -388,13 +443,18 @@ class Pman_Login extends Pman
         $this->bcc = $bcc;
         $this->rcpts = $u->getEmailFrom();
         
-        $ret = $cm->send($this);
-        //$this->jerr(print_r($r->toData(),true));
-        
-        if (is_object($ret)) {
-            $this->addEvent('SYSERR',false, $ret->getMessage());
+       
+       $mailer = $cm->toMailer($this, false);
+       if (is_a($mailer,'PEAR_Error') ) {
+           $this->addEvent('SYSERR',false, $mailer->getMessage());
+           $this->jerr($mailer->getMessage());
+       }
+        $sent = $mailer->send();
+       if (is_a($sent,'PEAR_Error') ) {
+           $this->addEvent('SYSERR',false, $sent->getMessage());
             $this->jerr($ret->getMessage());
         }
+       
         $this->addEvent('PASSREQ',$u, $u->email);
         $uu = clone($u);
         $uu->no_reset_sent++;
@@ -403,50 +463,149 @@ class Pman_Login extends Pman
         
     }
     
-    function changePassword($r)
+    function verifyResetPassword($id,$t, $key)
     {
-        
-        $au = $this->getAuthUser();
+       $au = $this->getAuthUser();
         if ($au) {
-            $uu = clone($au);
-            $au->setPassword($r['passwd1']);
-            $au->update($uu);
-            $this->addEvent("CHANGEPASS", $au);
-            $this->jok($au);
+            $this->jerr( "Already Logged in - no need to use Password Reset");
         }
-        // not logged in -> need to validate 
-        if (empty($r['passwordReset'])) {
-            $this->jerr("invalid request");
-        }
-        // same code as reset pasword
-       
-        $bits = explode('/', $r['passwordReset']);
-        //print_R($bits);
-      
-        $res= $this->resetPassword(@$bits[0],@$bits[1],@$bits[2]);
-          
-        if ($res !== false) {
-            $this->jerr($res);
-        }
-        // key is correct.. let's change password...
         
         $u = DB_DataObject::factory('core_person');
-        
         //$u->company_id = $this->company->id;
-        $u->whereAdd('LENGTH(passwd) > 1');
         $u->active = 1;
-        if (!$u->get($bits[0])) {
-           $this->jerr("invalid id"); // should not happen!!!!
+        if (!$u->get($id) || !strlen($u->passwd)) {
+            $this->jerr("Password reset link is not valid (id)");
+        }
+        
+        // validate key.. 
+        if ($key != $u->genPassKey($t)) {
+            $this->jerr("Password reset link is not valid ($key)");
+        }
+       
+       if ($t < strtotime("NOW - 1 DAY")) {
+            $this->jerr("Password reset link has expired");
         }
+       return $u;
+       
+       
+       
+    }
+    
+    
+    function resetPassword($id,$t, $key, $newpass )
+    {
+        
+        $u = $this->verifyResetPassword($id,$t,$k);
+       
+       
         $uu = clone($u);
-        $u->setPassword($r['passwd1']);
+        $u->no_reset_sent = 0;
+       if ($newpass != false) {
+           $u->setPassword($newpass);
+       }
         $u->update($uu);
         $u->login();
-        $this->addEvent("CHANGEPASS", $u);
-        $this->jok($u);
+        $this->jok("Password has been Updated");
     }
     
     
+    function changePassword($r)
+    {   
+        $au = $this->getAuthUser();
+        if (!$au) {
+           $this->jerr("Password change attempted when not logged in");
+       }
+       $uu = clone($au);
+       $au->setPassword($r['passwd1']);
+       $au->update($uu);
+       $this->addEvent("CHANGEPASS", $au);
+       $this->jok($au);
+         
+    }
+    
+    function ip_checking()
+    {
+        if(empty($this->ip_management)){
+            return;
+        }
+        
+        $ip = $this->ip_lookup();
+        
+        if(empty($ip)){
+            $this->jerr('BAD-IP-ADDRESS', array('ip' => $ip));
+        }
+        
+        $core_ip_access = DB_DataObject::factory('core_ip_access');
+        
+        if(!DB_DataObject::factory('core_ip_access')->count()){ // first ip we always mark it as approved..
+            
+            $core_ip_access = DB_DataObject::factory('core_ip_access');
+            
+            $core_ip_access->setFrom(array(
+                'ip' => $ip,
+                'created_dt' => $core_ip_access->sqlValue("NOW()"),
+                'authorized_key' => md5(openssl_random_pseudo_bytes(16)),
+                'status' => 1,
+                'email' => (empty($_REQUEST['username'])) ? '' : $_REQUEST['username'],
+                'user_agent' => (empty($_SERVER['HTTP_USER_AGENT'])) ? '' : $_SERVER['HTTP_USER_AGENT']
+            ));
+            
+            $core_ip_access->insert();
+            
+            return;
+        }
+        
+        $core_ip_access = DB_DataObject::factory('core_ip_access');
+        
+        if(!$core_ip_access->get('ip', $ip)){ // new ip
+            
+            $core_ip_access->setFrom(array(
+                'ip' => $ip,
+                'created_dt' => $core_ip_access->sqlValue("NOW()"),
+                'authorized_key' => md5(openssl_random_pseudo_bytes(16)),
+                'status' => 0,
+                'email' => (empty($_REQUEST['username'])) ? '' : $_REQUEST['username'],
+                'user_agent' => (empty($_SERVER['HTTP_USER_AGENT'])) ? '' : $_SERVER['HTTP_USER_AGENT']
+            ));
+            
+            $core_ip_access->insert();
+            
+            $core_ip_access->sendXMPP();
+            
+            $this->jerr('NEW-IP-ADDRESS', array('ip' => $ip));
+            
+            return;
+        }
+        
+        if(empty($core_ip_access->status)){
+            $this->jerr('PENDING-IP-ADDRESS', array('ip' => $ip));
+        }
+        
+        if($core_ip_access->status == -1){
+            $this->jerr('BLOCKED-IP-ADDRESS', array('ip' => $ip));
+            return;
+        }
+        
+        if($core_ip_access->status == -2 && strtotime($core_ip_access->expire_dt) < strtotime('NOW')){
+            $this->jerr('BLOCKED-IP-ADDRESS', array('ip' => $ip));
+            return;
+        }
+        
+        return;
+    }
     
+    function ip_lookup()
+    {
+
+        if (!empty($_SERVER['HTTP_CLIENT_IP'])){
+            return $_SERVER['HTTP_CLIENT_IP'];
+        }
+        
+        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
+            return $_SERVER['HTTP_X_FORWARDED_FOR'];
+        }
+        
+        return $_SERVER['REMOTE_ADDR'];
+    }
 }