Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like LocalAuthentication often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use LocalAuthentication, and based on these observations, apply Extract Interface, too.
1 | <?php namespace Myth\Auth; |
||
53 | class LocalAuthentication implements AuthenticateInterface { |
||
54 | |||
55 | protected $ci; |
||
56 | |||
57 | protected $user = null; |
||
58 | |||
59 | public $user_model = null; |
||
60 | |||
61 | public $error = null; |
||
62 | |||
63 | //-------------------------------------------------------------------- |
||
64 | |||
65 | public function __construct( $ci=null ) |
||
66 | { |
||
67 | if ($ci) |
||
68 | { |
||
69 | $this->ci= $ci; |
||
70 | } |
||
71 | else |
||
72 | { |
||
73 | $this->ci =& get_instance(); |
||
74 | } |
||
75 | |||
76 | // Get our compatibility password file loaded up. |
||
77 | if (! function_exists('password_hash')) |
||
78 | { |
||
79 | require_once dirname(__FILE__) .'password.php'; |
||
80 | } |
||
81 | |||
82 | if (empty($this->ci->session)) |
||
83 | { |
||
84 | $this->ci->load->library('session'); |
||
85 | } |
||
86 | |||
87 | $this->ci->config->load('auth'); |
||
88 | $this->ci->load->model('auth/login_model'); |
||
89 | $this->ci->load->language('auth/auth'); |
||
90 | } |
||
91 | |||
92 | //-------------------------------------------------------------------- |
||
93 | |||
94 | /** |
||
95 | * Attempt to log a user into the system. |
||
96 | * |
||
97 | * $credentials is an array of key/value pairs needed to log the user in. |
||
98 | * This is often email/password, or username/password. |
||
99 | * |
||
100 | * @param array $credentials |
||
101 | * @param bool $remember |
||
102 | * @return bool|mixed |
||
103 | */ |
||
104 | public function login($credentials, $remember=false) |
||
125 | |||
126 | //-------------------------------------------------------------------- |
||
127 | |||
128 | /** |
||
129 | * Validates user login information without logging them in. |
||
130 | * |
||
131 | * $credentials is an array of key/value pairs needed to log the user in. |
||
132 | * This is often email/password, or username/password. |
||
133 | * |
||
134 | * @param $credentials |
||
135 | * @param bool $return_user |
||
136 | * @return mixed |
||
137 | */ |
||
138 | public function validate($credentials, $return_user=false) |
||
229 | |||
230 | //-------------------------------------------------------------------- |
||
231 | |||
232 | /** |
||
233 | * Logs a user out and removes all session information. |
||
234 | * |
||
235 | * @return mixed |
||
236 | */ |
||
237 | public function logout() |
||
238 | { |
||
239 | $this->ci->load->helper('cookie'); |
||
240 | |||
241 | if (! Events::trigger('beforeLogout', [$this->user])) |
||
242 | { |
||
243 | return false; |
||
244 | } |
||
245 | |||
246 | // Destroy the session data - but ensure a session is still |
||
247 | // available for flash messages, etc. |
||
248 | if (isset($_SESSION)) |
||
249 | { |
||
250 | foreach ( $_SESSION as $key => $value ) |
||
251 | { |
||
252 | $_SESSION[ $key ] = NULL; |
||
253 | unset( $_SESSION[ $key ] ); |
||
254 | } |
||
255 | } |
||
256 | // Also, regenerate the session ID for a touch of added safety. |
||
257 | $this->ci->session->sess_regenerate(true); |
||
258 | |||
259 | // Take care of any rememberme functionality. |
||
260 | if (config_item('auth.allow_remembering')) |
||
261 | { |
||
262 | $token = get_cookie('remember'); |
||
263 | |||
264 | $this->invalidateRememberCookie($this->user['email'], $token); |
||
265 | } |
||
266 | } |
||
267 | |||
268 | //-------------------------------------------------------------------- |
||
269 | |||
270 | /** |
||
271 | * Checks whether a user is logged in or not. |
||
272 | * |
||
273 | * @return bool |
||
274 | */ |
||
275 | public function isLoggedIn() |
||
276 | { |
||
277 | $id = $this->ci->session->userdata('logged_in'); |
||
278 | |||
279 | if (! $id) |
||
280 | { |
||
281 | return false; |
||
282 | } |
||
283 | |||
284 | // If the user var hasn't been filled in, we need to fill it in, |
||
285 | // since this method will typically be used as the only method |
||
286 | // to determine whether a user is logged in or not. |
||
287 | if (! $this->user) |
||
288 | { |
||
289 | $this->user = $this->user_model->as_array() |
||
290 | ->find_by('id', (int)$id); |
||
291 | |||
292 | if (empty($this->user)) |
||
293 | { |
||
294 | return false; |
||
295 | } |
||
296 | } |
||
297 | |||
298 | // If logged in, ensure cache control |
||
299 | // headers are in place |
||
300 | $this->setHeaders(); |
||
301 | |||
302 | return true; |
||
303 | } |
||
304 | |||
305 | //-------------------------------------------------------------------- |
||
306 | |||
307 | /** |
||
308 | * Attempts to log a user in based on the "remember me" cookie. |
||
309 | * |
||
310 | * @return bool |
||
311 | */ |
||
312 | public function viaRemember() |
||
313 | { |
||
314 | if (! config_item('auth.allow_remembering')) |
||
315 | { |
||
316 | return false; |
||
317 | } |
||
318 | |||
319 | $this->ci->load->helper('cookie'); |
||
320 | |||
321 | if (! $token = get_cookie('remember')) |
||
322 | { |
||
323 | return false; |
||
324 | } |
||
325 | |||
326 | // Attempt to match the token against our auth_tokens table. |
||
327 | $query = $this->ci->db->where('hash', $this->ci->login_model->hashRememberToken($token)) |
||
328 | ->get('auth_tokens'); |
||
329 | |||
330 | if (! $query->num_rows()) |
||
331 | { |
||
332 | return false; |
||
333 | } |
||
334 | |||
335 | // Grab the user |
||
336 | $email = $query->row()->email; |
||
337 | |||
338 | $user = $this->user_model->as_array() |
||
339 | ->find_by('email', $email); |
||
340 | |||
341 | $this->loginUser($user); |
||
342 | |||
343 | // We only want our remember me tokens to be valid |
||
344 | // for a single use. |
||
345 | $this->refreshRememberCookie($user, $token); |
||
346 | |||
347 | return true; |
||
348 | } |
||
349 | |||
350 | //-------------------------------------------------------------------- |
||
351 | |||
352 | /** |
||
353 | * Registers a new user and handles activation method. |
||
354 | * |
||
355 | * @param $user_data |
||
356 | * @return bool |
||
357 | */ |
||
358 | public function registerUser($user_data) |
||
359 | { |
||
360 | // Anything special needed for Activation? |
||
361 | $method = config_item('auth.activation_method'); |
||
362 | |||
363 | $user_data['active'] = $method == 'auto' ? 1 : 0; |
||
364 | |||
365 | // If via email, we need to generate a hash |
||
366 | $this->ci->load->helper('string'); |
||
367 | $token = random_string('alnum', 24); |
||
368 | $user_data['activate_hash'] = hash('sha1', config_item('auth.salt') . $token); |
||
369 | |||
370 | // Email should NOT be case sensitive. |
||
371 | if (! empty($user_data['email'])) |
||
372 | { |
||
373 | $user_data['email'] = strtolower($user_data['email']); |
||
374 | } |
||
375 | |||
376 | // Save the user |
||
377 | if (! $id = $this->user_model->insert($user_data)) |
||
378 | { |
||
379 | $this->error = $this->user_model->error(); |
||
380 | return false; |
||
381 | } |
||
382 | |||
383 | $data = [ |
||
384 | 'user_id' => $id, |
||
385 | 'email' => $user_data['email'], |
||
386 | 'token' => $token, |
||
387 | 'method' => $method |
||
388 | ]; |
||
389 | |||
390 | Events::trigger('didRegisterUser', [$data]); |
||
391 | |||
392 | return true; |
||
393 | } |
||
394 | |||
395 | //-------------------------------------------------------------------- |
||
396 | |||
397 | /** |
||
398 | * Used to verify the user values and activate a user so they can |
||
399 | * visit the site. |
||
400 | * |
||
401 | * @param $data |
||
402 | * @return bool |
||
403 | */ |
||
404 | public function activateUser($data) |
||
405 | { |
||
406 | $post = [ |
||
407 | 'email' => $data['email'], |
||
408 | 'activate_hash' => hash('sha1', config_item('auth.salt') . $data['code']) |
||
409 | ]; |
||
410 | |||
411 | $user = $this->user_model->where($post) |
||
412 | ->first(); |
||
413 | |||
414 | if (! $user) { |
||
415 | $this->error = $this->user_model->error() ? $this->user_model->error() : lang('auth.activate_no_user'); |
||
416 | |||
417 | return false; |
||
418 | } |
||
419 | |||
420 | View Code Duplication | if (! $this->user_model->update($user->id, ['active' => 1, 'activate_hash' => null])) |
|
421 | { |
||
422 | $this->error = $this->user_model->error(); |
||
423 | return false; |
||
424 | } |
||
425 | |||
426 | Events::trigger('didActivate', [(array)$user]); |
||
427 | |||
428 | return true; |
||
429 | } |
||
430 | |||
431 | //-------------------------------------------------------------------- |
||
432 | |||
433 | /** |
||
434 | * Used to allow manual activation of a user with a known ID. |
||
435 | * |
||
436 | * @param $id |
||
437 | * @return bool |
||
438 | */ |
||
439 | public function activateUserById($id) |
||
440 | { |
||
441 | View Code Duplication | if (! $this->user_model->update($id, ['active' => 1, 'activate_hash' => null])) |
|
442 | { |
||
443 | $this->error = $this->user_model->error(); |
||
444 | return false; |
||
445 | } |
||
446 | |||
447 | Events::trigger('didActivate', [$this->user_model->as_array()->find($id)]); |
||
448 | |||
449 | return true; |
||
450 | } |
||
451 | |||
452 | //-------------------------------------------------------------------- |
||
453 | |||
454 | /** |
||
455 | * Grabs the current user object. Returns NULL if nothing found. |
||
456 | * |
||
457 | * @return array|null |
||
458 | */ |
||
459 | public function user() |
||
460 | { |
||
461 | return $this->user; |
||
462 | } |
||
463 | |||
464 | //-------------------------------------------------------------------- |
||
465 | |||
466 | /** |
||
467 | * A convenience method to grab the current user's ID. |
||
468 | * |
||
469 | * @return int|null |
||
470 | */ |
||
471 | public function id() |
||
472 | { |
||
473 | if (! is_array($this->user) || empty($this->user['id'])) |
||
474 | { |
||
475 | return null; |
||
476 | } |
||
477 | |||
478 | return (int)$this->user['id']; |
||
479 | } |
||
480 | |||
481 | //-------------------------------------------------------------------- |
||
482 | |||
483 | /** |
||
484 | * Checks to see if the user is currently being throttled. |
||
485 | * |
||
486 | * - If they are NOT, will return FALSE. |
||
487 | * - If they ARE, will return the number of seconds until they can try again. |
||
488 | * |
||
489 | * @param $user |
||
490 | * @return mixed |
||
491 | */ |
||
492 | public function isThrottled($user) |
||
593 | |||
594 | //-------------------------------------------------------------------- |
||
595 | |||
596 | /** |
||
597 | * Sends a password reset link email to the user associated with |
||
598 | * the passed in $email. |
||
599 | * |
||
600 | * @param $email |
||
601 | * @return mixed |
||
602 | */ |
||
603 | public function remindUser($email) |
||
604 | { |
||
605 | // Emails should NOT be case sensitive. |
||
606 | $email = strtolower($email); |
||
607 | |||
608 | // Is it a valid user? |
||
609 | $user = $this->user_model->find_by('email', $email); |
||
610 | |||
611 | if (! $user) |
||
612 | { |
||
613 | $this->error = lang('auth.invalid_email'); |
||
614 | return false; |
||
615 | } |
||
616 | |||
617 | // Generate/store our codes |
||
618 | $this->ci->load->helper('string'); |
||
619 | $token = random_string('alnum', 24); |
||
620 | $hash = hash('sha1', config_item('auth.salt') .$token); |
||
621 | |||
622 | $result = $this->user_model->update($user->id, ['reset_hash' => $hash]); |
||
623 | |||
624 | if (! $result) |
||
625 | { |
||
626 | $this->error = $this->user_model->error(); |
||
627 | return false; |
||
628 | } |
||
629 | |||
630 | Events::trigger('didRemindUser', [(array)$user, $token]); |
||
631 | |||
632 | return true; |
||
633 | } |
||
634 | |||
635 | //-------------------------------------------------------------------- |
||
636 | |||
637 | /** |
||
638 | * Validates the credentials provided and, if valid, resets the password. |
||
639 | * |
||
640 | * The $credentials array MUST contain a 'code' key with the string to |
||
641 | * hash and check against the reset_hash. |
||
642 | * |
||
643 | * @param $credentials |
||
644 | * @param $password |
||
645 | * @param $passConfirm |
||
646 | * @return mixed |
||
647 | */ |
||
648 | public function resetPassword($credentials, $password, $passConfirm) |
||
717 | |||
718 | //-------------------------------------------------------------------- |
||
719 | |||
720 | /** |
||
721 | * Provides a way for implementations to allow new statuses to be set |
||
722 | * on the user. The details will vary based upon implementation, but |
||
723 | * will often allow for banning or suspending users. |
||
724 | * |
||
725 | * @param $newStatus |
||
726 | * @param null $message |
||
727 | * @return mixed |
||
728 | */ |
||
729 | public function changeStatus($newStatus, $message=null) |
||
730 | { |
||
731 | // todo actually record new users status! |
||
732 | } |
||
733 | |||
734 | //-------------------------------------------------------------------- |
||
735 | |||
736 | /** |
||
737 | * Allows the consuming application to pass in a reference to the |
||
738 | * model that should be used. |
||
739 | * |
||
740 | * The model MUST extend Myth\Models\CIDbModel. |
||
741 | * |
||
742 | * @param $model |
||
743 | * @param bool $allow_any_parent |
||
744 | * @return mixed |
||
745 | */ |
||
746 | public function useModel($model, $allow_any_parent=false) |
||
747 | { |
||
748 | if (! $allow_any_parent && get_parent_class($model) != 'Myth\Models\CIDbModel') |
||
749 | { |
||
750 | throw new \RuntimeException('Models passed into LocalAuthenticate MUST extend Myth\Models\CIDbModel'); |
||
751 | } |
||
752 | |||
753 | $this->user_model =& $model; |
||
754 | |||
755 | return $this; |
||
756 | } |
||
757 | |||
758 | //-------------------------------------------------------------------- |
||
759 | |||
760 | public function error() |
||
761 | { |
||
762 | if (validation_errors()) |
||
763 | { |
||
764 | return validation_errors(); |
||
765 | } |
||
766 | |||
767 | return $this->error; |
||
768 | } |
||
769 | |||
770 | //-------------------------------------------------------------------- |
||
771 | |||
772 | //-------------------------------------------------------------------- |
||
773 | // Login Records |
||
774 | //-------------------------------------------------------------------- |
||
775 | |||
776 | /** |
||
777 | * Purges all login attempt records from the database. |
||
778 | * |
||
779 | * @param null $ip_address |
||
780 | * @param null $user_id |
||
781 | */ |
||
782 | public function purgeLoginAttempts($ip_address = null, $user_id = null) |
||
789 | |||
790 | //-------------------------------------------------------------------- |
||
791 | |||
792 | /** |
||
793 | * Purges all remember tokens for a single user. Effectively logs |
||
794 | * a user out of all devices. Intended to allow users to log themselves |
||
795 | * out of all devices as a security measure. |
||
796 | * |
||
797 | * @param $email |
||
798 | */ |
||
799 | public function purgeRememberTokens($email) |
||
800 | { |
||
801 | // Emails should NOT be case sensitive. |
||
802 | $email = strtolower($email); |
||
803 | |||
804 | $this->ci->login_model->purgeRememberTokens($email); |
||
805 | |||
806 | // todo record activity of remember me purges. |
||
807 | Events::trigger('didPurgeRememberTokens', [$email]); |
||
808 | } |
||
809 | |||
810 | //-------------------------------------------------------------------- |
||
811 | |||
812 | //-------------------------------------------------------------------- |
||
813 | // Protected Methods |
||
814 | //-------------------------------------------------------------------- |
||
815 | |||
816 | /** |
||
817 | * Check if Allow Persistent Login Cookies is enable |
||
818 | * |
||
819 | * @param $user |
||
820 | */ |
||
821 | protected function rememberUser($user) |
||
822 | { |
||
823 | if (! config_item('auth.allow_remembering')) |
||
824 | { |
||
825 | log_message('debug', 'Auth library set to refuse "Remember Me" functionality.'); |
||
826 | return false; |
||
827 | } |
||
828 | |||
829 | $this->refreshRememberCookie($user); |
||
830 | } |
||
831 | |||
832 | //-------------------------------------------------------------------- |
||
833 | |||
834 | /** |
||
835 | * Invalidates the current rememberme cookie/database entry, creates |
||
836 | * a new one, stores it and returns the new value. |
||
837 | * |
||
838 | * @param $user |
||
839 | * @param null $token |
||
840 | * @return mixed |
||
841 | */ |
||
842 | protected function refreshRememberCookie($user, $token=null) |
||
843 | { |
||
844 | $this->ci->load->helper('cookie'); |
||
845 | |||
846 | // If a token is passed in, we know we're removing the |
||
847 | // old one. |
||
848 | if (! empty($token)) |
||
849 | { |
||
850 | $this->invalidateRememberCookie($user['email'], $token); |
||
851 | } |
||
852 | |||
853 | $new_token = $this->ci->login_model->generateRememberToken($user); |
||
854 | |||
855 | // Save the token to the database. |
||
856 | $data = [ |
||
857 | 'email' => $user['email'], |
||
858 | 'hash' => sha1(config_item('auth.salt') . $new_token), |
||
859 | 'created' => date('Y-m-d H:i:s') |
||
860 | ]; |
||
861 | |||
862 | $this->ci->db->insert('auth_tokens', $data); |
||
863 | |||
864 | // Create the cookie |
||
865 | set_cookie( |
||
866 | 'remember', // Cookie Name |
||
867 | $new_token, // Value |
||
868 | config_item('auth.remember_length'), // # Seconds until it expires |
||
869 | config_item('cookie_domain'), |
||
870 | config_item('cookie_path'), |
||
871 | config_item('cookie_prefix'), |
||
872 | false, // Only send over HTTPS? |
||
873 | true // Hide from Javascript? |
||
874 | ); |
||
875 | |||
876 | return $new_token; |
||
877 | } |
||
878 | |||
879 | //-------------------------------------------------------------------- |
||
880 | |||
881 | /** |
||
882 | * Deletes any current remember me cookies and database entries. |
||
883 | * |
||
884 | * @param $email |
||
885 | * @param $token |
||
886 | * @return string The new token (not the hash). |
||
887 | */ |
||
888 | protected function invalidateRememberCookie($email, $token) |
||
889 | { |
||
890 | // Emails should NOT be case sensitive. |
||
891 | $email = strtolower($email); |
||
892 | |||
893 | // Remove from the database |
||
894 | $this->ci->login_model->deleteRememberToken($email, $token); |
||
895 | |||
896 | // Remove the cookie |
||
897 | delete_cookie( |
||
898 | 'remember', |
||
899 | config_item('cookie_domain'), |
||
900 | config_item('cookie_path'), |
||
901 | config_item('cookie_prefix') |
||
902 | ); |
||
903 | } |
||
904 | |||
905 | //-------------------------------------------------------------------- |
||
906 | |||
907 | /** |
||
908 | * Handles the nitty gritty of actually logging our user into the system. |
||
909 | * Does NOT perform the authentication, just sets the system up so that |
||
910 | * it knows we're here. |
||
911 | * |
||
912 | * @param $user |
||
913 | */ |
||
914 | protected function loginUser($user) |
||
947 | |||
948 | //-------------------------------------------------------------------- |
||
949 | |||
950 | /** |
||
951 | * Sets the headers to ensure that pages are not cached when a user |
||
952 | * is logged in, helping to protect against logging out and then |
||
953 | * simply hitting the Back button on the browser and getting private |
||
954 | * information because the page was loaded from cache. |
||
955 | */ |
||
956 | protected function setHeaders() |
||
957 | { |
||
958 | $this->ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate'); |
||
959 | $this->ci->output->set_header('Cache-Control: post-check=0, pre-check=0'); |
||
960 | $this->ci->output->set_header('Pragma: no-cache'); |
||
961 | } |
||
962 | |||
963 | //-------------------------------------------------------------------- |
||
964 | |||
965 | |||
966 | } |
||
967 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.