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