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