· 7 years ago · Jan 15, 2019, 03:12 PM
1<?php
2namespace MyAppModels;
3
4
5/**
6 *
7 * System User Class
8 *
9 */
10class SystemUser
11{
12
13/*=================================
14= Variables =
15=================================*/
16
17 public $id;
18 public $firstName;
19 public $lastName;
20 public $userName;
21 public $email;
22 public $lastLogin;
23 public $customerName;
24 public $password;
25 public $ip;
26 public $loginTimestamp;
27 public $isLoggedIn;
28
29 # @obj SystemUser profile information (fullname, email, last_login, profile picture, etc')
30 public $systemUserDetatils;
31 # @obj SystemUser Login data (a template for a login insert)
32 public $systemUserLogin;
33 # @obj SystemUser Authenticator object
34 protected $systemUserAuthenticator;
35 # @obj SystemUser Logout handling
36 protected $systemUserLogout;
37 # @obj Handle SystemUser Sessions (Sets user sessions, Check if sessions are set, Check timeout, ect')
38 public $systemUserSessions;
39
40/*===============================
41= Methods =
42================================*/
43
44
45 /**
46 *
47 * Construct
48 * @param $systemUserId Int (optional) User Id
49 *
50 */
51 public function __construct($systemUserId = NULL)
52 {
53 # Create systemUserDedatils obj
54 $this->systemUserDetatils = new MyAppModelsSystemUserSystemUserDetails();
55
56 # If system_user passed
57 if ( $systemUserId ) {
58
59 # Create systemUserDedatils obj
60 // $this->systemUserDetatils = new MyAppModelsSystemUserSystemUserDetatils();
61
62 # Set system user ID
63 $this->id = $systemUserId;
64
65 # Get SysUser data
66 $this->systemUserDetatils->get($this);
67
68 } else {
69
70 # Check for sysUser id in the session:
71 $systemUserId = $this->systemUserDetatils->getUserFromSession();
72
73 # Get user data from session
74 if ( $systemUserId ) {
75
76 # Set system user ID
77 $this->id = $systemUserId;
78
79 # Create systemUserDedatils obj
80 // $this->systemUserDetatils = new MyAppModelsSystemUserSystemUserDetatils();
81
82 # Get SysUser data
83 $this->systemUserDetatils->get($this);
84 }
85 }
86 }
87
88
89 /**
90 *
91 * Set Login: Sets the SystemUserLogin object to $systemUserLogin variable.
92 * @param $_systemUserLogin SystemUserLogin Gets a SystemUserLogin object
93 *
94 */
95 public function setSystemUserLogin(MyAppModelsSystemUserSystemUserLogin $_systemUserLogin)
96 {
97 $this->systemUserLogin = $_systemUserLogin;
98 }
99
100
101 /**
102 *
103 * System User Login
104 * @return
105 *
106 */
107 public function login()
108 {
109 $this->systemUserAuthenticator = new MyAppModelsSystemUserSystemUserAuthenticator();
110 return $this->systemUserAuthenticator->login($this);
111 }
112
113
114 /**
115 *
116 * Logout: Now guess what this method does..
117 *
118 */
119 public function logout()
120 {
121 $this->systemUserLogout = new MyAppModelsSystemUserSystemUserLogout($this);
122 }
123
124
125 /**
126 *
127 * Checks if a user is logged in
128 * @return
129 *
130 */
131 public function isLoggedIn()
132 {
133 return $this->systemUserSessions->isLoggedIn($this);
134 }
135
136
137 /**
138 *
139 * Checks if a system user has a timeout
140 * @return
141 *
142 */
143 public function checkTimeout()
144 {
145 return $this->systemUserSessions->isTimeout($this);
146 }
147}
148
149<?php
150namespace MyAppModelsSystemUser;
151
152use MyAppCoreDatabase;
153use MyAppCoreConfig;
154use MyAppHelpersSession;
155
156
157/**
158 *
159 * System User Details Class
160 *
161 */
162class SystemUserDetails
163{
164
165/*=================================
166= Variables =
167=================================*/
168
169 private $db;
170
171
172/*===============================
173= Methods =
174================================*/
175
176 /**
177 *
178 * Construct
179 *
180 */
181 public function __construct(/*Database $db*/)
182 {
183 # Get database instance
184 $this->db = Database::getInstance();
185 // $this->db = $db;
186 }
187
188
189 /**
190 *
191 * Find method: Find user by id or by username
192 * @param $user String / Init A username or user ID
193 * @return
194 *
195 */
196 public function get(MyAppModelsSystemUser $systemUser)
197 {
198 if ($systemUser->id) {
199
200 # Enable search for a system_user by a string name or if numeric - so by id
201 $field = ( is_numeric($systemUser->id) ) ? 'system_user_id' : 'uname';
202
203 # Search for the system_user in the Database 'system_users' table.
204 $result = $this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$field} = :sys_user", array('sys_user' => $systemUser->id));
205
206 # If there is a result
207 if ( $result ) {
208
209 # Set result
210 $this->set($systemUser, $result);
211
212 return true;
213 } else {
214 return false;
215 }
216 }
217 else {
218 return false;
219 }
220 }
221
222
223 /**
224 *
225 * Set User data to $this obj
226 * @param $userData Array User data fetched from the db (usually by the find method)
227 * @return
228 *
229 */
230 public function set(MyAppModelsSystemUser $systemUser, Array $userData)
231 {
232 $systemUser->id = $userData['system_user_id'];
233 $systemUser->firstName = $userData['fname'];
234 $systemUser->lastName = $userData['lname'];
235 $systemUser->userName = $userData['uname'];
236 $systemUser->email = $userData['email'];
237 $systemUser->lastLogin = $userData['last_login'];
238 }
239
240
241 /**
242 *
243 * Get User from session
244 * @param
245 * @return
246 *
247 */
248 public function getUserFromSession()
249 {
250 # Check if there is a session user id set
251 if (Session::exists(Config::$systemUserId)) {
252
253 # Insert session data to system_user variable
254 return Session::get(Config::$systemUserId);
255
256 } else {
257 # Returning false cause there is no user id session
258 return false;
259 }
260 }
261}
262
263<?php
264namespace MyAppModelsSystemUser;
265
266
267/**
268 *
269 * System User Login - Prepare a user for login with this class.
270 *
271 */
272class SystemUserLogin
273{
274
275/*=================================
276= Variables =
277=================================*/
278
279 public $customerName;
280 public $userName;
281 public $password;
282 public $userIp;
283
284
285/*===============================
286= Methods =
287================================*/
288
289
290 /**
291 *
292 * Construct - Set customer, username and password
293 * @param $_customerName String
294 * @param $_userName String
295 * @param $_password String
296 *
297 */
298 public function __construct(String $_customerName, String $_userName, String $_password)
299 {
300 $this->customerName = $_customerName;
301 $this->userName = $_userName;
302 $this->password = $_password;
303 $this->userIp = MyAppHelpersGeneral::getIp();
304 }
305
306}
307
308<?php
309namespace MyAppModelsSystemUser;
310
311use MyAppCoreDatabase;
312use MyAppCoreConfig;
313use MyAppHelpersSession;
314
315/**
316 *
317 * System User Details Class
318 *
319 */
320class SystemUserAuthenticator
321{
322
323/*=================================
324= Variables =
325=================================*/
326
327 private $db;
328
329 # @obj Handle SystemUser security sessions (tokens/secret/session_id() ect')
330 // protected $systemUserSecuritySession;
331
332/*===============================
333= Methods =
334================================*/
335
336
337 /**
338 *
339 * Construct
340 *
341 */
342 public function __construct(/*Database $db*/)
343 {
344 # Get database instance
345 $this->db = Database::getInstance();
346 // $this->db = $db;
347 }
348
349
350
351 /**
352 *
353 * Login method
354 * @param $customer_name String Get a customer_name user input
355 * @param $username String Get a username user input
356 * @param $password String Get a password user input
357 * @return Boolian Is this a signed System user?
358 *
359 */
360 public function login(MyAppModelsSystemUser $systemUser)
361 {
362 # Create a Customer Obj
363 $customer = new MyAppModelsCustomer($systemUser->systemUserLogin->customerName);
364
365 try {
366
367 # Check customer result
368 if ( (!isset($customer)) || (!isset($customer->dbName)) || (!isset($customer->host)) )
369 throw new MyAppCoreExceptionHandlerLoginException("Bad company name: {$systemUser->systemUserLogin->customerName}");
370
371 # Connect to new database
372 $newConnection = $this->db->customer_connect($customer->host, $customer->dbName);
373
374 # If status is connected
375 if ($newConnection) {
376
377 # Check for user credentials data
378 $userData = $this->systemUserLoginValidation($systemUser->systemUserLogin->userName, $systemUser->systemUserLogin->password);
379
380 # If the result isn't a valid array - EXEPTION
381 if ( (!is_array($userData)) || (empty($userData)) )
382 throw new MyAppCoreExceptionHandlerLoginException("Customer: '{$systemUser->SystemUserLogin->customerName}' - Invalid username ({$systemUser->SystemUserLogin->userName}) or password ({$systemUser->SystemUserLogin->password})");
383
384 # Store Customer in the sesison
385 Session::put(Config::$customer, serialize($customer));
386
387 # Set data for this System_user object
388 $this->set($systemUser, $userData);
389
390 # Set a login session for the user id:
391 Session::put(Config::$systemUserId, $systemUser->id);
392
393 # Set logged in user sessions
394 // $this->setLoggedinUserSessions($systemUser);
395 $systemUser->systemUserSessions = new MyAppModelsSystemUserSystemUserSessions();
396
397 $systemUser->systemUserSessions->setSecuritySession($systemUser);
398 # Update last_login for this user
399 $this->updateLastLogin($systemUser->id, $systemUser->loginTimestamp);
400
401 // return $this;
402 return true;
403
404 } else {
405 # Connect back to backoffice (current db set)
406 $this->db->connect_to_current_set_db();
407 throw new MyAppCoreExceptionHandlerLoginException('User does not exist');
408 return false;
409 }
410
411 } catch (MyAppCoreExceptionHandlerLoginException $e) {
412 $e->log($e);
413 return false;
414 // die(General::toJson(array( 'status' => false, 'message' => 'Bad login credentials.' )));
415 }
416 }
417
418
419 /**
420 *
421 * Set User data to $this obj
422 * @param $userData Array User data fetched from the db (usually by the find method)
423 * @return
424 *
425 */
426 public function set(MyAppModelsSystemUser $systemUser, Array $userData)
427 {
428 # Sets basic user data using SystemUserDetails
429 $systemUser->systemUserDetatils->set($systemUser, $userData);
430
431 # Set Login data
432 $systemUser->loginTimestamp = date("Y-m-d H:i:s");
433 $systemUser->isLoggedIn = true;
434 $systemUser->ip = $systemUser->systemUserLogin->userIp;
435 }
436
437
438 /**
439 *
440 * Check if user exist in 'system_users' table
441 * @param $username String Get a username user input
442 * @param $password String Get a password user input
443 * @return Array/Boolian Is this a signed System user?
444 *
445 */
446 private function systemUserLoginValidation(String $username, String $password)
447 {
448 $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)));
449
450 if ($userData)
451 return $userData;
452 else
453 return false;
454 }
455
456
457 /**
458 *
459 * Updates the system users "last logged in" field in db
460 * @param $id Int System User ID
461 * @param $date String Current login timestamp (set to $systemUser->loginTimestamp)
462 *
463 */
464 private function updateLastLogin(Int $id, String $date)
465 {
466 $this->db->row("UPDATE system_users SET last_login = :newLastLogin WHERE system_user_id = :systemUserId", array('newLastLogin' => $date, 'systemUserId' => $id));
467 }
468}
469
470<?php
471namespace MyAppModelsSystemUser;
472
473use MyAppCoreConfig;
474use MyAppHelpersSession;
475use MyAppHelpersToken;
476use MyAppHelpersHash;
477use MyAppHelpersGeneral;
478use MyAppModelsSystemUser;
479
480/**
481 *
482 * System User Security Session: Handle the system user security session / token / secret / ect.
483 *
484 */
485class SystemUserSessions
486{
487
488 /**
489 *
490 * Sets SystemUser security session
491 * @param $ystemUser Obj SystemUser object
492 *
493 */
494 public function setSecuritySession(SystemUser $systemUser)
495 {
496 $this->setLoggedinUserSessions($systemUser);
497 }
498
499
500 /**
501 *
502 * Check if there is a logged in user
503 * @param $ystemUser Obj SystemUser object
504 *
505 */
506 public function isLoggedIn(SystemUser $systemUser)
507 {
508 if ( Session::exists(Config::$secret) && # Secret session exists
509 Session::exists(Config::$session_id) && # Session_id session exists
510 Session::exists(Config::$systemUserId) && # User session exists
511 Session::exists(Config::$is_logged_in) # Check if 'logged in' session exists
512 )
513 {
514 # Get users ip
515 $ip = General::getIp();
516
517 # if the saved bombined session
518 if (
519 (Session::get(Config::$combined) === Hash::make_from_array(array(Session::get(Config::$secret), session_id()), $ip)) &&
520 (Session::get(Config::$is_logged_in) === true )
521 )
522 {
523 # Set ip to system user object
524 $systemUser->ip = $ip;
525
526 return true;
527
528 } else {
529 return false;
530 }
531 }
532 else {
533 return false;
534 }
535 }
536
537
538 /**
539 *
540 * Check if loggin session is timeout
541 * @param $ystemUser Obj SystemUser object
542 *
543 */
544 public function isTimeout(SystemUser $systemUser)
545 {
546 if (Session::exists(Config::$login_timestamp)){
547
548 # Calculate time
549 $session_lifetime_seconds = time() - Session::get(Config::$login_timestamp) ;
550
551 if ($session_lifetime_seconds > Config::MAX_TIME){
552 $systemUser->logout();
553 return true;
554 } else {
555 return false;
556 }
557
558 } else {
559 $systemUser->logout();
560 return false;
561 }
562 }
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578 /**
579 *
580 * Set sessions for the logged in user.
581 * Tutorial: http://forums.devshed.com/php-faqs-stickies/953373-php-sessions-secure-post2921620.html
582 * @param $systemUser Object Gets the main SystemUser class object
583 *
584 */
585 private function setLoggedinUserSessions(SystemUser $systemUser)
586 {
587 # Generate security sessions
588 $this->generateSecuritySessions($systemUser);
589
590 # Set login timestamp
591 Session::put(Config::$login_timestamp, $systemUser->loginTimestamp);
592
593 # Set login flag to true
594 Session::put(Config::$is_logged_in, true);
595
596 # Set login IP
597 Session::put(Config::$login_user_ip, $systemUser->ip);
598 }
599
600
601 /**
602 *
603 * Generate system user security sessions
604 * @param $new_session Boolean (optinal) Dedices if to delete the cookie session id [default is set to true]
605 *
606 */
607 public function generateSecuritySessions(SystemUser $systemUser, bool $newSession = true)
608 {
609 if ($newSession)
610 # Generate a new session ID
611 session_regenerate_id(true);
612
613 # Fetch cookie session ID
614 $sessionId = session_id();
615 # Set the session id to the session
616 Session::put(Config::$session_id, $sessionId);
617
618 # Create a secret token
619 # Set it in session (does them both)
620 $secret = Token::generate_login_token();
621
622 # Combine secret and session_id and create a hash
623 $combined = Hash::make_from_array(array($secret, $sessionId, $systemUser->ip));
624 # Add combined to session
625 Session::put(Config::$combined, $combined);
626 }
627
628
629
630}
631
632<?php
633namespace MyAppModelsSystemUser;
634
635use MyAppHelpersSession;
636use MyAppHelpersCookie;
637
638/**
639 *
640 * System User Logout - Prepare a user for Logout with this class.
641 *
642 */
643class SystemUserLogout
644{
645
646/*=================================
647= Variables =
648=================================*/
649
650/*===============================
651= Methods =
652================================*/
653
654
655 /**
656 *
657 * Construct - Set customer, username and password
658 *
659 */
660 public function __construct()
661 {
662 # Delete cookies
663 Cookie::eat_cookies();
664 # Delete all sessions
665 Session::kill_session();
666 # Re-generate SESSIONID
667 session_regenerate_id(true);
668 }
669
670
671}