Pman/Login.php
[Pman.Base] / Pman / Login.php
1 <?php
2
3 require_once 'Pman.php';
4
5 /***
6
7 * Auth wrapper..
8
9 * User class must provide the following features.
10
11 * logout()
12 * isAuth() 
13 * getAuthUser();
14 * authUserArray() 
15 * active()  -- is user active. // or set prior to checking..
16 * authUserName(n) - sets the value prior to a find(true)
17 * checkPassword($_REQUEST['password'])) {
18 * login();
19 * lang(val) - to set the language..
20 */
21
22
23
24 class Pman_Login extends Pman
25
26     var $masterTemplate = 'login.html';
27     
28     var $ip_management = false;
29     
30     function getAuth() // everyone allowed in here..
31     {
32         parent::getAuth(); // load company..
33         
34         $ff = HTML_FlexyFramework::get();
35         
36         $this->ip_management = (empty($ff->Pman['ip_management'])) ? false : true;
37         
38         return true;
39     }
40     /**
41      * Accepts:
42      * logout =
43      * 
44      * 
45      */
46     function get($v, $opts=array()) 
47     {
48         $this->initErrorHandling();
49         
50          //DB_DataObject::DebugLevel(1);
51         if (!empty($_REQUEST['logout'])) {
52            return $this->logout();
53         }
54         
55         // general query...
56         if (!empty($_REQUEST['getAuthUser'])) {
57             //DB_Dataobject::debugLevel(5);
58             $this->sendAuthUserDetails();
59             exit;
60         }
61         
62         // might be an idea to disable this?!?
63         if (!empty($_REQUEST['username'])) {
64             $this->post();
65         }
66         
67         
68         if (!empty($_REQUEST['switch'])) {
69             $this->switchUser($_REQUEST['switch']);
70         }
71         
72         if (!empty($_REQUEST['loginPublic'])) {
73             $this->switchPublicUser($_REQUEST['loginPublic']);
74         }
75         
76         
77         $this->jerr("INVALID REQUEST");
78         exit;
79     }
80     
81     
82     function logout()
83     {
84         $ff = class_exists('HTML_FlexyFramework2') ?  HTML_FlexyFramework2::get()  :  HTML_FlexyFramework::get();
85         //DB_DAtaObject::debugLevel(1);
86         $u = $this->getAuthUser();
87         //print_r($u);
88         if ($u) {
89             
90             $this->addEvent('LOGOUT');
91             $e = DB_DataObject::factory('Events');
92           
93             
94             $u->logout();
95             session_regenerate_id(true);
96             session_commit(); 
97
98             if(!empty($ff->Pman['local_autoauth']) && !empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
99                 $this->jerr("you are using local autoauth!?");                
100             }
101             //echo '<PRE>';print_R($_SESSION);
102             $this->jok("Logged out - user ");
103         }
104         // log it..
105         
106         //$_SESSION['Pman_I18N'] = array(); << 
107         session_regenerate_id(true);
108         session_commit();
109         
110         $this->jok("Logged out - no user");
111         
112     }
113     
114     function sendAuthUserDetails()
115     {
116         // remove for normal use - it's a secuirty hole!
117         //DB_DataObject::debugLevel(1);
118         if (!empty($_REQUEST['_debug'])) {
119            // DB_DataObject::debugLevel(1);
120         }
121         // 
122         $ff = HTML_FlexyFramework::get();
123         $tbl = empty($ff->Pman['authTable']) ? 'core_person' : $ff->Pman['authTable'];
124         
125         $u = DB_DataObject::factory($tbl);
126         if (!$u->isAuth()) {
127              
128             $this->jok(array('id' => 0)); // not logged in..
129             exit;
130         }
131         //die("got here?");
132         $au = $u->getAuthUser();
133         
134          // might occur on shared systems.
135         $ff= HTML_FlexyFramework::get();
136         
137         if (!empty($ff->Pman['auth_comptype'])  && $au->id > 0 &&
138                 ($ff->Pman['auth_comptype'] != $au->company()->comptype)) {
139             $au->logout();
140             $this->jerr("Login not permited to outside companies - please reload");
141         }
142         
143         //$au = $u->getAuthUser();
144         
145         $aur = $au ?  $au->authUserArray() : array();
146         
147         /** -- these need modulizing somehow! **/
148         
149         
150         
151         // basically calls Pman_MODULE_Login::sendAuthUserDetails($aur) on all the modules
152         //echo '<PRE>'; print_r($this->modules());
153         // technically each module should only add properties to an array named after that module..
154         
155         foreach($this->modules() as $m) {
156             if (empty($m)) {
157                 continue;
158             }
159             if (!file_exists($this->rootDir.'/Pman/'.$m.'/Login.php')) {
160                 continue;
161             }
162             $cls = 'Pman_'.$m.'_Login';
163             require_once 'Pman/'.$m.'/Login.php';
164             $x = new $cls;
165             $x->authUser = $au;
166             $aur = $x->sendAuthUserDetails($aur);
167         }
168         
169                  
170 //        
171 //        echo '<PRE>';print_r($aur);
172 //        exit;
173         $this->jok($aur);
174         exit;
175         
176             
177     }
178
179     function switchUser($id)
180     {
181         $tbl = empty($ff->Pman['authTable']) ? 'core_person' : $ff->Pman['authTable'];
182         $u = DB_DataObject::factory($tbl);
183         if (!$u->isAuth()) {
184             $this->err("not logged in");
185         }
186         
187         $au = $u->getAuthUser();
188         
189         // first check they have perms to do this..
190         if (!$au|| ($au->company()->comptype != 'OWNER') || !$this->hasPerm('Core.Person', 'E')) {
191             $this->jerr("User switching not permitted");
192         }
193                 
194         $u = DB_DataObject::factory($tbl);
195         $u->get($id);
196         if (!$u->active()) {
197             $this->jerr('Account disabled');
198         }
199         $u->login();
200             // we might need this later..
201         $this->addEvent("SWITCH-USER", false, $au->name . ' TO ' . $u->name);
202         $this->jok("SWITCH");
203         
204     }
205     
206     function switchPublicUser($id)
207     {
208         $tbl = empty($ff->Pman['authTable']) ? 'core_person' : $ff->Pman['authTable'];
209         
210         $u = DB_DataObject::factory($tbl);
211         $u->get($id);
212         
213         if (!$u->active()) {
214             $this->jerr('Account disabled');
215         }
216         
217         if(!$u->loginPublic()){
218             $this->jerr('Switch fail');
219         }
220         
221         $this->jok('OK');
222     }
223     
224     var $domObj = false;
225     
226     function post($v)
227     {
228         //DB_DataObject::debugLevel(1);
229         
230         if (!empty($_REQUEST['getAuthUser'])) {
231             $this->sendAuthUserDetails();
232             exit;
233         }
234         
235         if (!empty($_REQUEST['logout'])) {
236            return $this->logout();
237         }
238         
239         if (!empty($_REQUEST['passwordRequest'])) { //|| (strpos($_REQUEST['username'], '@') < 1)) {
240             
241             return $this->passwordRequest($_REQUEST['passwordRequest']);
242             
243         }
244         
245         if (!empty($_REQUEST['changePassword'])) {
246             return $this->changePassword($_REQUEST);
247         }
248         
249         // login attempt..
250         
251         $ff = HTML_FlexyFramework::get();
252         $tbl = empty($ff->Pman['authTable']) ? 'core_person' : $ff->Pman['authTable'];
253         
254        
255         $u = DB_DataObject::factory($tbl);
256         
257         $ip = $this->ip_lookup();
258         // ratelimit
259         if (!empty($ip)) {
260             //DB_DataObject::DebugLevel(1);
261             $e = DB_DataObject::Factory('Events');
262             $e->action = 'LOGIN-BAD';
263             $e->ipaddr = $ip;
264             $e->whereAdd('event_when > NOW() - INTERVAL 10 MINUTE');
265             if ($e->count() > 5) {
266                 $this->jerror('LOGIN-RATE', "Login failures are rate limited - please try later");
267             }
268         }
269         
270         //$u->active = 1;
271         
272         // empty username = not really a hacking attempt.
273         
274         if (empty($_REQUEST['username'])) { //|| (strpos($_REQUEST['username'], '@') < 1)) {
275             $this->jerror('LOGIN-EMPTY', 'You typed the wrong Username or Password (0)');
276             exit;
277         }
278         
279         $u->authUserName($_REQUEST['username']);
280         
281         if ($u->count() > 1 || !$u->find(true)) {
282             $this->jerror('LOGIN-BAD','You typed the wrong Username or Password  (1)');
283             exit;
284         }
285         
286         if (!$u->active()) {
287             $this->jerror('LOGIN-BAD','Account disabled');
288         }
289         
290         if(!empty($u->oath_key) && empty($_REQUEST['oath_password'])){
291             $this->jerror('LOGIN-BAD','Your account require Two-Factor Authentication');
292         }
293         
294         // check if config allows non-owner passwords.
295         // auth_company = "OWNER" // auth_company = "CLIENT" or blank for all?
296         // perhaps it should support arrays..
297         $ff= HTML_FlexyFramework::get();
298         if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $u->company()->comptype) {
299             //print_r($u->company());
300             $this->jerror('LOGIN-BADUSER', "Login not permited to outside companies"); // serious failure
301         }
302         
303         
304         // note we trim \x10 -- line break - as it was injected the front end
305         // may have an old bug on safari/chrome that added that character in certian wierd scenarios..
306         if (!$u->checkPassword(trim($_REQUEST['password'],"\x10"))) {
307             $this->jerror('LOGIN-BAD', 'You typed the wrong Username or Password  (2)'); // - " . htmlspecialchars(print_r($_POST,true))."'");
308             exit;
309         }
310         
311         if(!empty($u->oath_key) && !$u->checkTwoFactorAuthentication(trim($_REQUEST['oath_password'],"\x10"))){
312             $this->jerror('LOGIN-BAD', 'You typed the wrong Username or Password  (3)');
313             exit;
314         }
315         
316         $this->ip_checking();
317         
318         $u->login();
319         // we might need this later..
320         $this->addEvent("LOGIN", false, session_id());
321         if (!empty($_REQUEST['lang'])) {
322             $u->lang($_REQUEST['lang']);
323         }
324          // log it..
325
326         $this->sendAuthUserDetails();
327         exit;
328          
329         
330     }
331     
332     function passwordRequest($n) 
333     {
334         $u = DB_DataObject::factory('core_person');
335         //$u->company_id = $this->company->id;
336         
337         $u->whereAdd('LENGTH(passwd) > 1');
338         $u->email = $n;
339         $u->active = 1;
340         if ($u->count() > 1 || !$u->find(true)) {
341             $this->jerr('invalid User (1)');
342         }
343         // got a avlid user..
344         if (!strlen($u->passwd)) {
345             $this->jerr('invalid User (2)');
346         }
347         // check to see if we have sent a request before..
348         
349         if ($u->no_reset_sent > 3) {
350             $this->jerr('We have issued to many resets - please contact the Administrator');
351         }
352         
353         
354         
355         
356         // sort out sender.
357         $cm = DB_DataObject::factory('core_email');
358         if (!$cm->get('name', 'ADMIN_PASSWORD_RESET')) {
359             $this->jerr("no template ADMIN_PASSWORD_RESET exists - please run importer ");
360             
361         }
362         /*
363         
364         $g = DB_DAtaObject::factory('Groups');
365         if (!$g->get('name', 'system-email-from')) {
366             $this->jerr("no group 'system-email-from' exists in the system");
367         }
368         $from_ar = $g->members();
369         if (count($from_ar) != 1) {
370             $this->jerr(count($from_ar) ? "To many members in the 'system-email-from' group " :
371                        "'system-email-from' group  does not have any members");
372         }
373         */
374         
375         
376         
377         // bcc..
378         $g = DB_DAtaObject::factory('core_group');
379         if (!$g->get('name', 'bcc-email')) {
380             $this->jerr("no group 'bcc-email' exists in the system");
381         }
382         $bcc = $g->members('email');
383         if (!count($bcc)) {
384             $this->jerr( "'bcc-email' group  does not have any members");
385         }
386         
387         
388         
389         $this->authFrom = time();
390         $this->authKey = $u->genPassKey($this->authFrom);
391         //$this->authKey = md5($u->email . $this->authFrom . $u->passwd);
392         $this->person = $u;
393         $this->bcc = $bcc;
394         $this->rcpts = $u->getEmailFrom();
395         
396         $ret = $cm->send($this);
397         //$this->jerr(print_r($r->toData(),true));
398         
399         if (is_object($ret)) {
400             $this->addEvent('SYSERR',false, $ret->getMessage());
401             $this->jerr($ret->getMessage());
402         }
403         $this->addEvent('PASSREQ',$u, $u->email);
404         $uu = clone($u);
405         $uu->no_reset_sent++;
406         $uu->update($u);
407         $this->jok("done");
408         
409     }
410     
411     function changePassword($r)
412     {   
413         $au = $this->getAuthUser();
414         if ($au) {
415             $uu = clone($au);
416             $au->setPassword($r['passwd1']);
417             $au->update($uu);
418             $this->addEvent("CHANGEPASS", $au);
419             $this->jok($au);
420         }
421         // not logged in -> need to validate 
422         if (empty($r['passwordReset'])) {
423             $this->jerr("invalid request");
424         }
425         // same code as reset pasword
426        
427         $bits = explode('/', $r['passwordReset']);
428         //print_R($bits);
429       
430         $res= $this->resetPassword(@$bits[0],@$bits[1],@$bits[2]);
431           
432         if ($res !== false) {
433             $this->jerr($res);
434         }
435         // key is correct.. let's change password...
436         
437         $u = DB_DataObject::factory('core_person');
438         
439         //$u->company_id = $this->company->id;
440         $u->whereAdd('LENGTH(passwd) > 1');
441         $u->active = 1;
442         if (!$u->get($bits[0])) {
443            $this->jerr("invalid id"); // should not happen!!!!
444         }
445         $uu = clone($u);
446         $u->setPassword($r['passwd1']);
447         $u->update($uu);
448         $u->login();
449         $this->addEvent("CHANGEPASS", $u);
450         $this->jok($u);
451     }
452     
453     function ip_checking()
454     {
455         if(empty($this->ip_management)){
456             return;
457         }
458         
459         $ip = $this->ip_lookup();
460         
461         if(empty($ip)){
462             $this->jerr('BAD-IP-ADDRESS', array('ip' => $ip));
463         }
464         
465         $core_ip_access = DB_DataObject::factory('core_ip_access');
466         
467         if(!DB_DataObject::factory('core_ip_access')->count()){ // first ip we always mark it as approved..
468             
469             $core_ip_access = DB_DataObject::factory('core_ip_access');
470             
471             $core_ip_access->setFrom(array(
472                 'ip' => $ip,
473                 'created_dt' => $core_ip_access->sqlValue("NOW()"),
474                 'authorized_key' => md5(openssl_random_pseudo_bytes(16)),
475                 'status' => 1,
476                 'email' => (empty($_REQUEST['username'])) ? '' : $_REQUEST['username'],
477                 'user_agent' => (empty($_SERVER['HTTP_USER_AGENT'])) ? '' : $_SERVER['HTTP_USER_AGENT']
478             ));
479             
480             $core_ip_access->insert();
481             
482             return;
483         }
484         
485         $core_ip_access = DB_DataObject::factory('core_ip_access');
486         
487         if(!$core_ip_access->get('ip', $ip)){ // new ip
488             
489             $core_ip_access->setFrom(array(
490                 'ip' => $ip,
491                 'created_dt' => $core_ip_access->sqlValue("NOW()"),
492                 'authorized_key' => md5(openssl_random_pseudo_bytes(16)),
493                 'status' => 0,
494                 'email' => (empty($_REQUEST['username'])) ? '' : $_REQUEST['username'],
495                 'user_agent' => (empty($_SERVER['HTTP_USER_AGENT'])) ? '' : $_SERVER['HTTP_USER_AGENT']
496             ));
497             
498             $core_ip_access->insert();
499             
500             $core_ip_access->sendXMPP();
501             
502             $this->jerr('NEW-IP-ADDRESS', array('ip' => $ip));
503             
504             return;
505         }
506         
507         if(empty($core_ip_access->status)){
508             $this->jerr('PENDING-IP-ADDRESS', array('ip' => $ip));
509         }
510         
511         if($core_ip_access->status == -1){
512             $this->jerr('BLOCKED-IP-ADDRESS', array('ip' => $ip));
513             return;
514         }
515         
516         if($core_ip_access->status == -2 && strtotime($core_ip_access->expire_dt) < strtotime('NOW')){
517             $this->jerr('BLOCKED-IP-ADDRESS', array('ip' => $ip));
518             return;
519         }
520         
521         return;
522     }
523     
524     function ip_lookup()
525     {
526
527         if (!empty($_SERVER['HTTP_CLIENT_IP'])){
528             return $_SERVER['HTTP_CLIENT_IP'];
529         }
530         
531         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
532             return $_SERVER['HTTP_X_FORWARDED_FOR'];
533         }
534         
535         return $_SERVER['REMOTE_ADDR'];
536     }
537     
538     
539 }
540