· 7 years ago · Jan 08, 2019, 12:14 AM
1<?php
2namespace MyAppModels;
3
4use Exception;
5use MyAppCoreDatabase;
6use MyAppCoreConfig;
7use MyAppHelpersSession;
8use MyAppHelpersCookie;
9use MyAppHelpersToken;
10use MyAppHelpersGeneral;
11use MyAppHelpersHash;
12
13
14
15/**
16 *
17 * System User Class
18 *
19 */
20class System_user
21{
22
23/*=================================
24= Variables =
25=================================*/
26
27 # @object database Database instance
28 private $db;
29
30 # Users data
31 private $data;
32
33 # User user ID name
34 public $user_id;
35
36 # User first name
37 public $first_name;
38
39 # User last name
40 public $last_name;
41
42 # Username
43 public $user_name;
44
45 # User Email
46 public $email;
47
48 # User Last logged in
49 public $last_login;
50
51 # is user logged in
52 public $isLoggedIn;
53
54 # is user logged in
55 public $login_timestamp;
56
57 # is user IP
58 private $user_ip;
59
60
61/*===============================
62= Methods =
63================================*/
64
65 /**
66 *
67 * Construct
68 *
69 */
70 public function __construct($system_user = NULL)
71 {
72 # Get database instance
73 $this->db = Database::getInstance();
74
75 # If system_user isn't passed as a variable
76 if ( !$system_user ) {
77
78 # ...so check if there is a session user id set
79 if (Session::exists(Config::$session_name)) {
80
81 # Insert session data to system_user variable
82 $system_user = Session::get(Config::$session_name);
83
84 # Get user data
85 $this->find($system_user);
86 }
87
88 } else {
89 $this->find($system_user);
90 }
91 }
92
93
94 /**
95 *
96 * Find method: Find user by id or by username
97 * @param $user String/Init A username or user ID
98 *
99 */
100 public function find($system_user = NULL)
101 {
102 if ($system_user) {
103
104 // Enable search for a system_user by a string name or if numeric - so by id.
105 $field = ( is_numeric($system_user) ) ? 'system_user_id' : 'uname';
106
107 // Search for the system_user in the Database 'system_users' table.
108 $data = $this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$field} = :sys_user", array('sys_user' => $system_user));
109
110 // If there is a result
111 if ( $data ) {
112 // Set data
113 $this->setUserData($data);
114
115 return $this;
116 } else {
117 return false;
118 }
119 }
120 else{
121 return false;
122 }
123 }
124
125
126 /**
127 *
128 * Check if user exist in 'system_users' table
129 * @param $username String Get a username user input
130 * @param $password String Get a password user input
131 * @throws Array/Boolian Is this a signed System user?
132 *
133 */
134 private function system_user_login_validation($username, $password)
135 {
136 $user_data = $this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' => $username, 'password' => sha1($password)));
137
138 if ($user_data)
139 return $user_data;
140 else
141 return false;
142 }
143
144
145 /**
146 *
147 * Login method
148 * @param $customer_name String Get a customer_name user input
149 * @param $username String Get a username user input
150 * @param $password String Get a password user input
151 * @throws Boolian Is this a signed System user?
152 *
153 */
154 public function login($customer_name, $username, $password)
155 {
156
157 # Create a Customer Obj
158 $customer = new MyAppModelsCustomer($customer_name);
159
160 try {
161 # Check if the result is an array
162 # OR there is no row result:
163 if ( (!isset($customer)) || (!isset($customer->dbName)) || (!isset($customer->host)) )
164 throw new MyAppCoreExceptionHandlerLoginException("Bad company name: {$customer_name}");
165
166 # Change localhost string to 127.0.0.1 (prevent dns lookup)
167 $customer->host = ($customer->host === 'localhost') ? '127.0.0.1' : $customer->host;
168
169 # Connect to new database
170 $new_connection = $this->db->customer_connect($customer->host, $customer->dbName);
171
172 # If status is connected
173 if ($new_connection) {
174
175 # Check for user credentials data
176 $user_data = $this->system_user_login_validation($username, $password);
177
178 # If the result isn't a valid array - EXEPTION
179 if ( (!is_array($user_data)) || (empty($user_data)) )
180 throw new MyAppCoreExceptionHandlerLoginException("Customer: '{$customer_name}' - Invalid username ({$username}) or password ({$password})");
181
182 # Store Customer in the sesison
183 Session::put(Config::$customer, serialize($customer));
184
185 # Update host and db for the db object
186 # $this->db->update_host_and_db($customer->host, $customer->dbName);
187
188 # Set data for this System_user object
189 $this->setUserData($user_data);
190
191 # Set a login session for the user id:
192 Session::put(Config::$session_name, $this->user_id);
193
194 # Set logged in user sessions
195 $this->set_loggedin_user_sessions();
196
197 return $this;
198
199 } else {
200 # Connect back to backoffice (current db set)
201 $this->db->connect_to_current_set_db();
202 throw new MyAppCoreExceptionHandlerLoginException('User does not exist');
203 return false;
204 }
205
206 } catch (MyAppCoreExceptionHandlerLoginException $e) {
207 $e->log($e);
208 return false;
209 // die(General::toJson(array( 'status' => false, 'message' => 'Bad login credentials.' )));
210 }
211 }
212
213
214 /**
215 *
216 * Set sessions for the logged in user.
217 * Tutorial: http://forums.devshed.com/php-faqs-stickies/953373-php-sessions-secure-post2921620.html
218 *
219 */
220 public function set_loggedin_user_sessions()
221 {
222 # Generate security sessions
223 $this->generate_security_sessions();
224
225 # Set login timestamp
226 Session::put(Config::$login_timestamp, $this->login_timestamp);
227
228 # Set login flag to true
229 Session::put(Config::$is_logged_in, true);
230
231 # Set login IP
232 Session::put(Config::$login_user_ip, $this->user_ip);
233 }
234
235
236 /**
237 *
238 * Generate system user security sessions
239 * @param $new_session Boolean (optinal) Dedices if to delete the cookie session id [default is set to true]
240 *
241 */
242 public function generate_security_sessions($new_session = true)
243 {
244 if ($new_session)
245 # Generate a new session ID
246 session_regenerate_id(true);
247
248 # Fetch cookie session ID
249 $session_id = session_id();
250 # Set the session id to the session
251 Session::put(Config::$session_id, $session_id);
252
253 # Create a secret token
254 # Set it in session (does them both)
255 $secret = Token::generate_login_token();
256
257 # Combine secret and session_id and create a hash
258 $combined = Hash::make_from_array(array($secret, $session_id, $this->user_ip));
259 # Add combined to session
260 Session::put(Config::$combined, $combined);
261 }
262
263
264 /**
265 *
266 * Check if there is a logged in user
267 *
268 */
269 public function check_logged_in()
270 {
271 if ( Session::exists(Config::$secret) && # Secret session exists
272 Session::exists(Config::$session_id) && # Session_id session exists
273 Session::exists(Config::$session_name) && # User session exists
274 Session::exists(Config::$is_logged_in) && # Check if 'logged in' session exists
275 Session::exists(Config::$session_name) # Check if sys_user id is set in session
276 )
277 {
278 # Get users ip
279 $ip = $this->get_system_user_ip();
280
281 # if the saved bombined session
282 if (
283 (Session::get(Config::$combined) === Hash::make_from_array(array(Session::get(Config::$secret), session_id()), $ip)) &&
284 (Session::get(Config::$is_logged_in) === true )
285 )
286 {
287 # Set ip to system user object
288 $this->user_ip = $ip;
289
290 return true;
291
292 } else {
293 return false;
294 }
295 }
296 else {
297 return false;
298 }
299 }
300
301
302 /**
303 *
304 * Check if loggin session is timeout
305 *
306 */
307 public function check_timeout()
308 {
309 if (Session::exists(Config::$login_timestamp)){
310
311 # Calculate time
312 $session_lifetime_seconds = time() - Session::get(Config::$login_timestamp) ;
313
314 if ($session_lifetime_seconds > Config::MAX_TIME){
315 $this->logout();
316 return true;
317 } else {
318 return false;
319 }
320
321 } else {
322 $this->logout();
323 return false;
324 }
325 }
326
327
328 /**
329 *
330 * Get user IP
331 *
332 */
333 private function get_system_user_ip()
334 {
335 if (!empty($_SERVER['HTTP_CLIENT_IP']))
336 $ip = $_SERVER['HTTP_CLIENT_IP'];
337 elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
338 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
339 else
340 $ip = $_SERVER['REMOTE_ADDR'];
341
342 return $ip;
343 }
344
345
346 /**
347 *
348 * Set User data to (this) System_user object
349 * @param $user_data Array User data fetched from the db (usually by the find method)
350 *
351 */
352 private function setUserData($user_data)
353 {
354 // Set data for this user object
355 $this->user_id = $user_data['system_user_id'];
356 $this->first_name = $user_data['fname'];
357 $this->last_name = $user_data['lname'];
358 $this->user_name = $user_data['uname'];
359 $this->email = $user_data['email'];
360 $this->last_login = $user_data['last_login'];
361
362 $this->isLoggedIn = true;
363 $this->user_ip = $this->get_system_user_ip();
364 $this->login_timestamp = time();
365 }
366
367
368 /**
369 *
370 * Logout: Now guess what this method does..
371 *
372 */
373 public function logout()
374 {
375 $this->isLoggedIn = false;
376 Cookie::eat_cookies();
377 Session::kill_session();
378 session_destroy();
379 session_write_close();
380 }
381
382}
383
384<?php
385namespace MyAppModels;
386
387use MyAppCoreConfig;
388use MyAppHelpersSession;
389use MyAppCoreDatabase;
390
391
392/**
393 *
394 * System User Class
395 *
396 */
397class SystemUser
398{
399
400/*=================================
401= Variables =
402=================================*/
403
404 # @obj SystemUser profile information (fullname, profile picture... etc')
405 protected $systemUserDetatils;
406 # @obj SystemUser Login data
407 protected $systemUserLogin;
408 # @obj SystemUser Authenticator
409 protected $systemUserAuthenticator;
410
411
412/*===============================
413= Methods =
414================================*/
415
416
417 /**
418 *
419 * Construct
420 *
421 */
422 public function __construct($systemUserId = NULL)
423 {
424 # If system_user passed
425 if ( $systemUserId ) {
426
427 # Create systemUserDedatils obj
428 $this->systemUserDetatils = new MyAppModelsSystemUserSystemUserDetatils();
429
430 # Get SysUser data
431 $this->systemUserDetatils->get($systemUserId);
432
433 } else {
434
435 # Check for sysUser id in the session:
436 $systemUserId = $this->systemUserDetatils->getUserFromSession();
437
438 # Get user data from session
439 if ( $systemUserId ) {
440
441 # Create systemUserDedatils obj
442 $this->systemUserDetatils = new MyAppModelsSystemUserSystemUserDetatils();
443
444 # Get SysUser data
445 $this->systemUserDetatils->get($systemUserId);
446 }
447 }
448 }
449
450
451 /**
452 *
453 * Set Login: Sets the SystemUserLogin object to $systemUserLogin variable
454 * @param $_systemUserLogin SystemUserLogin Gets a SystemUserLogin object
455 *
456 */
457 public function setSystemUserLogin(SystemUserLogin $_systemUserLogin)
458 {
459 $this->systemUserLogin = $_systemUserLogin;
460 }
461
462
463 /**
464 *
465 * Login
466 *
467 */
468 public function login()
469 {
470 $this->systemUserAuthenticator($this);
471 }
472
473
474}
475
476
477
478
479
480
481
482
483<?php
484namespace MyAppModelsSystemUser;
485
486use MyAppCoreConfig;
487use MyAppHelpersSession;
488
489/**
490 *
491 * System User Details Class
492 *
493 */
494class SystemUserDetails
495{
496
497/*=================================
498= Variables =
499=================================*/
500
501 # @object database Database instance
502 private $db;
503
504 # Users data
505 private $data;
506
507 # User user ID name
508 public $userId;
509
510 # User first name
511 public $firstName;
512
513 # User last name
514 public $lastName;
515
516 # Username
517 public $userName;
518
519 # User Email
520 public $email;
521
522 # User Last logged in
523 public $lastLogin;
524
525 /*# is user logged in
526 public $isLoggedIn;
527
528 # is user logged in
529 public $login_timestamp;*/
530
531 # is user IP
532 private $user_ip;
533
534
535/*===============================
536= Methods =
537================================*/
538
539 /**
540 *
541 * Construct
542 *
543 */
544 public function __construct()
545 {
546 # Get database instance
547 $this->db = Database::getInstance();
548 }
549
550
551 /**
552 *
553 * Find method: Find user by id or by username
554 * @param $user String / Init A username or user ID
555 * @return
556 *
557 */
558 public function get(Int $systemUserId)
559 {
560 if ($systemUserId) {
561
562 # Enable search for a system_user by a string name or if numeric - so by id.
563 $field = ( is_numeric($systemUserId) ) ? 'system_user_id' : 'uname';
564
565 # Search for the system_user in the Database 'system_users' table.
566 $data = $this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$field} = :sys_user", array('sys_user' => $systemUserId));
567
568 # If there is a result
569 if ( $data ) {
570
571 # Set data
572 $this->setUserData($data);
573
574 return $this;
575 } else {
576 return false;
577 }
578 }
579 else {
580 return false;
581 }
582 }
583
584
585 /**
586 *
587 * Set User data to $this obj
588 * @param $userData Array User data fetched from the db (usually by the find method)
589 * @return
590 *
591 */
592 public function set(Array $userData)
593 {
594 // Set data for this user object
595 $this->userId = $userData['system_user_id'];
596 $this->firstName = $userData['fname'];
597 $this->lastName = $userData['lname'];
598 $this->userName = $userData['uname'];
599 $this->email = $userData['email'];
600 $this->lastLogin = $userData['last_login'];
601 }
602
603
604 /**
605 *
606 * Get User from session
607 * @param
608 * @return
609 *
610 */
611 public function getUserFromSession()
612 {
613 # Check if there is a session user id set
614 if (Session::exists(Config::$session_name)) {
615
616 # Insert session data to system_user variable
617 return Session::get(Config::$session_name);
618
619 } else {
620 # Returning false cause there is no user id session
621 return false;
622 }
623 }
624}
625
626
627
628
629
630<?php
631namespace MyAppModelsSystemUser;
632
633
634/**
635 *
636 * System User Details Class
637 *
638 */
639class systemUserLogin
640{
641
642/*=================================
643= Variables =
644=================================*/
645
646 # @str Customer name
647 public $customerName;
648
649 # @str UserName
650 public $userName;
651
652 # @str Password
653 public $password;
654
655 # @str user IP
656 public $userIp;
657
658
659/*===============================
660= Methods =
661================================*/
662
663
664 /**
665 *
666 * Construct - Set customer, username and password
667 * @param $_customerName String
668 * @param $_userName String
669 * @param $_password String
670 *
671 */
672 public function __construct(String $_customerName, String $_userName, String $_password)
673 {
674 $this->customerName = $_customerName;
675 $this->userName = $_userName;
676 $this->password = $_password;
677 $this->userIp = $this->getSystemUserIp();
678 }
679
680
681 /**
682 *
683 * Get user IP
684 * @return String Returns the user IP that is trying to connect.
685 *
686 */
687 private function getSystemUserIp()
688 {
689 if (!empty($_SERVER['HTTP_CLIENT_IP']))
690 $ip = $_SERVER['HTTP_CLIENT_IP'];
691 elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
692 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
693 else
694 $ip = $_SERVER['REMOTE_ADDR'];
695
696 return $ip;
697 }
698
699}
700
701
702
703
704
705<?php
706namespace MyAppModelsSystemUser;
707
708
709/**
710 *
711 * System User Details Class
712 *
713 */
714class systemUserAuthenticator
715{
716
717/*=================================
718= Variables =
719=================================*/
720
721 # @object Database instance
722 private $db;
723
724 # @bool Is logged in
725 public $isLoggedIn = false;
726
727 # @str Login Timestamp
728 public $loginTimestamp;
729
730
731/*===============================
732= Methods =
733================================*/
734
735
736 /**
737 *
738 * Construct
739 *
740 */
741 public function __construct()
742 {
743 # Get database instance
744 $this->db = Database::getInstance();
745 }
746
747
748 /**
749 *
750 * Login method
751 * @param $customer_name String Get a customer_name user input
752 * @param $username String Get a username user input
753 * @param $password String Get a password user input
754 * @throws Boolian Is this a signed System user?
755 *
756 */
757 public function login(User $user)
758 {
759 # Create a Customer Obj
760 $customer = new MyAppModelsCustomer($user->SystemUserLogin->customerName);
761
762 try {
763 # Check if the result is an array
764 # OR there is no row result:
765 if ( (!isset($customer)) || (!isset($customer->dbName)) || (!isset($customer->host)) )
766 throw new MyAppCoreExceptionHandlerLoginException("Bad company name: {$user->SystemUserLogin->customerName}");
767
768 # Change localhost string to 127.0.0.1 (prevent dns lookup)
769 $customer->host = ($customer->host === 'localhost') ? '127.0.0.1' : $customer->host;
770
771 # Connect to new database
772 $new_connection = $this->db->customer_connect($customer->host, $customer->dbName);
773
774 # If status is connected
775 if ($new_connection) {
776
777 # Check for user credentials data
778 $user_data = $this->system_user_login_validation($user->SystemUserLogin->userName, $user->SystemUserLogin->password);
779
780 # If the result isn't a valid array - EXEPTION
781 if ( (!is_array($user_data)) || (empty($user_data)) )
782 throw new MyAppCoreExceptionHandlerLoginException("Customer: '{$user->SystemUserLogin->customerName}' - Invalid username ({$user->SystemUserLogin->userName}) or password ({$user->SystemUserLogin->password})");
783
784 # Store Customer in the sesison
785 Session::put(Config::$customer, serialize($customer));
786
787 # Update host and db for the db object
788 # $this->db->update_host_and_db($customer->host, $customer->dbName);
789
790 # Set data for this System_user object
791 $this->setUserData($user_data);
792
793 # Set a login session for the user id:
794 Session::put(Config::$session_name, $this->user_id);
795
796 # Set logged in user sessions
797 $this->set_loggedin_user_sessions();
798
799 return $this;
800
801 } else {
802 # Connect back to backoffice (current db set)
803 $this->db->connect_to_current_set_db();
804 throw new MyAppCoreExceptionHandlerLoginException('User does not exist');
805 return false;
806 }
807
808 } catch (MyAppCoreExceptionHandlerLoginException $e) {
809 $e->log($e);
810 return false;
811 // die(General::toJson(array( 'status' => false, 'message' => 'Bad login credentials.' )));
812 }
813 }
814
815
816 /**
817 *
818 * Check if user exist in 'system_users' table
819 * @param $username String Get a username user input
820 * @param $password String Get a password user input
821 * @throws Array/Boolian Is this a signed System user?
822 *
823 */
824 private function systemUserLoginValidation($username, $password)
825 {
826 $userData = $this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' => $username, 'password' => sha1($password)));
827
828 if ($userData)
829 return $userData;
830 else
831 return false;
832 }
833
834
835
836
837}
838
839use PimpleContainer;
840
841$container = new Container();
842
843$container['db'] = function ($c) {
844 return Database::getInstance();
845};
846
847class System_user
848{
849 public function __construct(Pimple $container, $system_user = NULL)
850 {
851 $this->db = $container['db'];
852 }
853}