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