public
Created

Auth problems with CakePHP 2.0 - migrating from 1.3 - 2.0

  • Download Gist
gistfile1.aw
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
/****************************************************************
* AppController.php
*****************************************************************/
<?
/**
* Most application-wide logic should be handled here
*
*/
class AppController extends Controller
{
 
protected $actionAuths;
 
/**
* CakePHP merges our controller options
* with all of the follow var's: $components, $uses, $helpers
* from AppController: http://book.cakephp.org/view/829/The-App-Controller
*/
public $components = array(
'Session',
'RequestHandler',
'TFBase',
'TFApi',
'TFLocalization',
'TFAjaxUrl',
'TFNotice',
'TFAuth'
);
 
public $helpers = array(
'Form',
'Html',
'Session',
'TFJavaScriptLang'
);
 
/**
* Must be set when rendering any ajax requests via the controller
* example: $this->render($this->ajax_layout);
*/
public $ajax_layout = '/layouts/ajax';
 
/**
* Any ajax urls used throughout the app
* 'url' => 'action'
*/
protected $_global_ajax_urls = array(
'remove_global_message' => 'ajax_remove_global_message',
'remove_admin_message' => 'ajax_remove_admin_message'
);
 
/**
* Setup some things before we actually
* render the page. Whenever you define a beforeFilter()
* always remember to call home to its parent.
*/
public function beforeFilter()
{
 
parent::beforeFilter();
 
$this->_rewritePluginRoutes();
$this->_assignCookieSettings();
$this->_setupAuth();
$this->_checkAccountExpired();
$this->_checkLoginPage();
 
}
 
/**
* Called after beforeFilter. Before we render the page
* do some awesomeness.
*/
public function beforeRender()
{
parent::beforeRender();
$this->_setupPageSpecificCSS();
$this->_checkAjax();
$this->_checkShowMessage();
$this->_checkShowAdminMessage();
//$this->_checkSetErrorLayout();
$this->_setPageHeading();
 
}
 
/**
* Since our plugin (telus) controllers are prefixed by x_, we need to strip
* that out as we are routing /:plugin/appointments -> /:plugin/x_appointments
* See routes.php
*/
protected function _rewritePluginRoutes()
{
if(isset($this->params['plugin']))
{
$this->params['controller'] = str_replace('x_', '', $this->params['controller']);
}
}
 
/**
* Assign some default settings for our cookies
*/
protected function _assignCookieSettings()
{
 
// We're not using the cookie component everywhere, so
// only call things where we need it.
if(isset($this->Cookie))
{
// Allows us to share cookies between subdomains
// The main reason is for the admin to hijack into
// accounts from Coco Tools. Don't do it for hosts like "localhost",
// taht just messes up Chrome.
if(stristr(env('HTTP_HOST'), '.'))
{
$this->Cookie->domain = env('HTTP_BASE');
}
}
 
}
 
/**
* If we're on the login/forgotpw page, set some vendor info to the view
*/
protected function _checkLoginPage()
{
 
if($this->params['controller'] == 'staff' && in_array($this->params['action'], array('login', 'forgotpassword')))
{
$this->layout = 'login';
}
 
}
 
/**
* If the persons account is expired, redirect them to the
* appropriate billings page
*/
protected function _checkAccountExpired()
{
 
$account_expired = $this->Session->read(Configure::read('SESSION_KEY_EXPIRED'));
$action = $this->params['action'];
$controller = $this->params['controller'];
 
// If the user is trying to log out, do not call the beforeFilter, they
// are trying to get away, let them go!
if($account_expired && $action != 'logout' && $controller != 'billing')
{
$this->redirect(Configure::read('EXPIRED_REDIRECT'));
}
 
}
 
/**
* Check to see if we have a global message set in the vendors table.
* If there is a message and the show_message flag is '1' in for this
* user, then we show them the message. They always have the option to
* get rid of it by clicking the [x]. This sets the flag to '0'. Everytime
* A new message is saved, all the show_message flags for users get set to
* '1'.
*/
protected function _checkShowMessage()
{
 
$global_message = null;
if (isset($this->TFUser))
{
$domain = $this->TFUser['Vendor']['domain'];
$vendor_info = ClassRegistry::init('Vendor')->findByDomain($domain);
$global_message = $vendor_info['Vendor']['global_message'];
}
// We use TFAuth->user() here because TFUser, for whatever reason, is not being set yet
$user = $this->TFAuth->user();
$show_user_message = $user['Staff']['show_message'];
 
if($global_message && $show_user_message)
{
// We want to use the staff controller to send this ajax update
$remove_global_message = $this->TFAjaxUrl->get(
$this->_global_ajax_urls['remove_global_message'],
'staff'
);
$this->set(compact(
'global_message',
'remove_global_message'
));
 
}
 
}
 
protected function _checkShowAdminMessage()
{
$user = $this->TFAuth->user();
$admin_show_message = $user['Staff']['admin_show_message'];
 
if ($admin_show_message)
{
$remove_admin_message = $this->TFAjaxUrl->get(
$this->_global_ajax_urls['remove_admin_message'],
'staff'
);
 
$MessageModel = ClassRegistry::init('Message');
$message = $MessageModel->find('first', array('order' => array('Message.updated DESC')));
$admin_message = $message['Message']['body'];
 
// Only show the message if it was kinda recent. No point on showing 3 month old messages.
if(strtotime($MessageModel->show_only_if_newer_than, strtotime($message['Message']['updated'])) >= time())
{
$this->set(compact('admin_message','remove_admin_message'));
}
}
}
 
/**
* We check if we're about to render an error, if we are, we don't
* want it meshed within our content. Show it on it's own - no extra
* broken styles, scripts etc.
*/
/*protected function _checkSetErrorLayout()
{
if($this->name == 'CakeError')
{
$this->layout = 'cake_error';
}
}*/
 
/**
* All of our ajax requests being with the action "ajax_", let's
* check that and make sure they're not requesting it illegally!
*/
protected function _checkAjax()
{
 
$act = $this->params['action'];
 
// Are we logged out? Session dead? Throw our 403 header
// that we use to detect expired sessions in views/DetectSessionExpired.js
if($this->RequestHandler->isAjax() && !$this->TFAuth->user('id'))
{
$this->TFAuth->logout();
$this->header('HTTP/1.1 403 Forbidden');
die;
}
 
// If we're editing, just show the modal dialog with some contents,
// we don't need a layout for it. The layout would be the rendered element.
if(in_array($act, array('edit', 'create', 'admin_edit', 'admin_create')))
{
// @TODO: Refactor this to behave like clients_bookings_controller.php
// Notice the $this->layout and $this->render is being done in the
// TFApi->render function? Use the same approach for TFAjaxUrl.
$this->layout = false;
}
 
// Are we grabbing data via ajax? and are they doing it via the address bar?
if(substr($act, 0, 5) == "ajax_" && !$this->RequestHandler->isAjax())
{
die("Invalid ajax request");
}
 
}
 
/**
* Setup some default auth behavior and pass the auth obj to the view
*/
protected function _setupAuth()
{
 
//pr($this->TFAuth->user());
//Deny access to everything by default
$this->TFAuth->deny("*");
 
// Set up auth error messages here, where they can actually be translated
$this->TFAuth->userScope = array('Staff.active' => 1);
$this->TFAuth->autoRedirect = false; // We'll take care of redirecting, we need to check for expiry first.
$this->TFAuth->loginError = __('Your username or password was incorrect');
$this->TFAuth->loginAction = '/login';
$this->TFAuth->loginRedirect = array('controller' => 'dashboard', 'action' => 'index');
$this->TFAuth->authError = 'do-not-show';
$this->TFAuth->flashElement = 'error';
$this->TFAuth->loginAction = array(
'controller' => 'staff',
'action' => 'login',
'plugin' => false,
'admin' => false
);
$this->TFAuth->authenticate = array(
'all' => array('userModel' => 'Staff'),
'Form' => array(
'fields' => array(
'username'=>'username',
'password'=>'password'
)
)
);
$this->TFAuth->authorize = array(
'Controller'
);
$this->TFAuth->userScope = array(
'Staff.active' => 1
);
 
// Allow access to any ajax request actions, this merges in anything called
// using TFAuth->allow('something', 'another');
$act = $this->params['action'];
if(strstr($act, 'ajax_') !== false || strstr($act, 'api_') !== false)
{
$this->TFAuth->allowedActions = array($act);
}
 
// Add a user helper object to the view so that we can use it to decide what parts to show
// haters gonna hate
$TFAuth = $this->TFAuth;
$TFUser = $this->TFAuth->user();
 
$this->TFUser = $TFUser;
 
// Set it to the view
$this->set(compact('TFAuth', 'TFUser'));
 
}
 
/**
* Called by auth system for each request. Returns true if the user is allowed to run the current action, false otherwise
* @return BOOL
*/
public function isAuthorized()
{
return $this->staffAuthorizedForAction($this->action);
}
 
/**
* Called on each request to determine whether or not the user is allowed to
* access the current action. Uses the $actionAuths property to map action names
* to the list of user roles allowed to access that action.
* @param String $actionName
* @return BOOL
*/
protected function staffAuthorizedForAction($actionName)
{
 
//Return true if the current staff member is authorized to view this action, false otherwise
if(isset($this->actionAuths))
{
//actionAuths maps action names to the list of roles allowed to access it.
if(isset($this->actionAuths[$actionName]))
{
if(is_array($this->actionAuths[$actionName]))
{
$val = $this->TFAuth->userHasRole($this->actionAuths[$actionName]);
return $val;
}
else
{
//actionAuths[actionName] can be a string *, which means allow everyone
if($this->actionAuths[$actionName] == '*')
{
return true;
}
}
}
}
return false;
}
 
/**
* Set up some page specific CSS (if we have some). To
* minimize loading un-used CSS, we have our generic
* stuff in global.css, then we load in anything page-specific
* using this method. The css files that are page-specific
* are found in webroot/css/pages/
*/
protected function _setupPageSpecificCSS()
{
 
$view = new View($this);
$this->Html = $view->loadHelper('Html');
$css_tag = '';
$controller = $this->params['controller'];
$css_path = 'css/pages/' . $controller . '.css';
$file_css = $this->base . '/' . $css_path;
$file_path = WWW_ROOT . $css_path;
 
if(file_exists($file_path)){
$css_tag = $this->Html->css($file_css);
}
 
$this->set('page_specific_css', $css_tag);
 
}
 
/**
* This is used in availability_controller and reports_controller, absences_controller.php
* No sense on duplicating it in those controllers.
*
* @param integer/array $location_id The location id
*/
public function ajax_fetch_staff_By_location_id($location_id)
{
$response = array();
 
if ($location_id)
{
$staff = ClassRegistry::init('Staff')->getAllByLocationId($location_id);
$staff = TFSet::createList('/Staff/id', '/Staff/full_name', $staff);
 
$response['status'] = 'success';
$response['data'] = $staff;
}
else
{
$response['message'] = 'Invalid location id';
}
 
$this->set(compact('response'));
 
$this->render($this->ajax_layout);
}
 
/**
* Set up the page heading to be used throughout each page.
* This is the one that gets put in the <h2>. Provides some
* default page headings with options to over-write them.
*/
protected function _setPageHeading()
{
 
// MAYBE WE'LL WANT THIS BACK? LATER?
/*
$c = $this->params['controller'];
$a = $this->params['action'];
 
$terms = array(
// controller
'billings' => array(
'actions' => array(
'index' => __('Billing')
)
),
'staff' => array(
'actions' => array(
'index' => __('Manage')
)
),
'services' => array(
'actions' => array(
'index' => __('Manage')
)
),
'locations' => array(
'actions' => array(
'index' => __('Manage')
)
)
);
 
// Default to the controller name if we're on the index action, otherwise, take the action
$page_heading = ($a == 'index') ? __(ucfirst($c)) : __(ucfirst($a));
 
if(isset($terms) && isset($terms[$c]))
{
if(isset($terms[$c]['actions']) && isset($terms[$c]['actions'][$a]))
{
$page_heading = $terms[$c]['actions'][$a];
}
}
 
$this->set(compact('page_heading'));
*/
 
}
/**
* API specific calls
* These calls do not make use of authenticated
* roles. The API object handles all the
* necessary heavy lifting
**********************************************/
public function api_index()
{
$this->TFApi->dispatch();
}
public function api_filter()
{
$this->TFApi->dispatch();
}
public function api_view()
{
$this->TFApi->dispatch();
}
public function api_add()
{
$this->TFApi->dispatch();
}
public function api_edit()
{
$this->TFApi->dispatch();
}
 
}
 
/****************************************************************
* StaffController.php (the one I login with)
*****************************************************************/
 
<?php
 
class StaffController extends AppController
{
 
public $components = array(
'TFNotification',
'TFArchiver',
'Cookie'
);
public $helpers = array(
'Form',
'Html',
'Session',
'TFICal',
'TFJavaScriptLang'
);
/**
* List of the form fields that should be saved (others will be ignored)
* @var array
*/
private $allFormFields = array(
'vendor_id',
'username',
'first_name',
'last_name',
'email',
'password',
'active',
'Role',
'lang',
'Service'
);
 
/**
* Array mapping this controller's actions to the users allowed to access them
* @var array
*/
protected $actionAuths = array(
'create'=>array('manager', 'admin'),
'delete'=>array('manager', 'admin'),
'edit'=>array('manager', 'admin'),
'forgotpassword'=>'*',
'index'=>'*',
'login'=>'*',
'logout'=>'*',
'sync' => '*',
'settings'=>array('staff','staff_advanced', 'manager', 'admin')
);
 
/**
* Any ajax urls used throughout this controller
* 'url' => 'action'
*/
protected $_ajax_urls = array(
'fetch_staff' => 'ajax_fetch_staff'
);
 
public $uses = array(
'Staff',
'Service',
'StaffRole'
);
 
public function beforeFilter()
{
parent::beforeFilter();
$this->TFAuth->allow('forgotpassword');
$this->TFAuth->allow('sync');
}
 
 
/**
* Login to the system. We take over the redirects by setting
* $this->TFAuth->autoRedirect = false;
*/
public function login()
{
 
$domain = TF::getDomain();
$vendor_info = $this->Staff->Vendor->findByDomain($domain);
 
$params = $this->TFAjaxUrl->getUrlParams();
 
// Username and token, means a super admin is probably logging in
if(isset($params['u']))
{
$this->request->data['Staff']['username'] = urldecode($params['u']);
}
 
// If they visit the login page and they've already logged in, boot 'em to the dashboard
if($this->TFUser && !$this->request->data)
{
$this->redirect($this->TFAuth->redirect());
}
 
if($this->TFAuth->login() && $this->request->data)
{
 
// @TODO: Figure out WHY we have to reset our TFUser here by calling TFAuth.. god.
$this->TFUser = $this->TFAuth->user();
$this->TFLocalization->setLanguage($this->TFUser['lang']);
 
$expired = $this->Staff->Vendor->isExpired($vendor_info);
 
if($expired)
{
$this->Session->write(Configure::read('SESSION_KEY_EXPIRED'), 1);
if($this->TFAuth->isAccountCreator())
{
$this->Session->write(Configure::read('SESSION_KEY_EXPIRED_IS_ADMIN'), 1);
$this->redirect(Configure::read('EXPIRED_REDIRECT'));
}
else
{
$logout_msg = __('This account is expired. Please notify your manager') . '.';
$this->logout($logout_msg, 'error');
}
}
 
$this->redirect($this->TFAuth->redirect());
 
}
 
$this->set(compact('vendor_info'));
 
}
 
/**
* Logout of the system
*/
public function logout($msg = '', $type = 'success')
{
if(!$msg)
{
$msg = __('"Goodbye. Buh bye now. Bye. G-bye."<br/>-Coconut Calendar Flight Attendant' );
}
 
$this->TFNotice->{$type}($msg);
$this->redirect($this->TFAuth->logout());
}
 
/**
* If the user forgot their password, they can simply supply an email
* and have a new one generated and sent to them
*
* @TODO: Make it so it sends them an email to confirm that they actually
* want to reset their password.
*/
public function forgotpassword()
{
 
$flash = '';
$domain = TF::getDomain();
$vendor_info = $this->Staff->Vendor->findByDomain($domain);
 
if (!empty($this->request->data))
{
// Make sure the email actually exists
if ($this->request->data['Staff']['email'] && $user_data = $this->Staff->findByEmail($this->request->data['Staff']['email']))
{
// Generate a new password and store it, while sending the clean one in an email
$new_pass = $this->Staff->generateRandomPassword();
$user_data['Staff']['password'] = $new_pass['hash'];
 
// Send it
if ($this->Staff->save($user_data, false) && $this->TFNotification->Staff->forgotPassword($this->request->data, $new_pass['clean']))
{
$flash = "Your password has been sent";
$type = "success";
} else
{
$flash = "An error occured while sending your new password";
$type = "error";
}
} else
{
$flash = "That email does not exist in our system";
$type = "error";
}
 
$this->TFNotice->{$type}(__($flash));
$this->redirect($this->referer());
}
$this->set(compact('vendor_info'));
}
 
}
 
/****************************************************************
* TFAuthComponent.php
*****************************************************************/
 
<?php
App::uses('AuthComponent', 'Controller/Component');
 
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class TFAuthComponent extends AuthComponent
{
 
public $components = array(
'Cookie',
'Session',
'RequestHandler'
);
 
/**
* Overridden login method copied from core, with changes so that user
* roles are saved to the session on login with the rest of the user data
* @param array $data If you figure out what this is, let me know
* @return boolean Whether or not the user is now logged in
*/
public function login($user = null)
{
 
$this->_setDefaults();
 
$current_domain = TF::getDomain();
$vendor = ClassRegistry::init('Vendor')->find('first', array(
'conditions' => array(
'domain' => $current_domain
),
'fields' => 'id',
'recursive' => -1
));
 
$vendor_id = $vendor['Vendor']['id'];
$this->userScope['Staff.vendor_id'] = $vendor_id;
 
if(empty($user))
{
$user = $this->identify($this->request, $this->response);
}
 
if($user)
{
// At this point, session doesn't contain roles, as $this->identify() doesn't do a recursive query.
// Just grab the roles and throw them in the session
$db_user = ClassRegistry::init('Staff')->findById($user['id']);
 
foreach($db_user['Location'] as $index => $location)
{
if ($location['active'] == 0)
{
unset($db_user['Location'][$index]);
}
}
 
// Roles comes back in user[Role] as a 0 indexed array with [id] and [name], we want an array of all of the
// values for id and name just to make things a little flexy for now
$user['_roles'] = $this->mergeRoles($db_user);
 
if($db_user['Staff']['id'] == $db_user['Vendor']['staff_id'])
{
$user['_roles'][] = 'account_creator';
}
 
unset($db_user['Staff']);
$user = array_merge($user, $db_user);
 
// Check if they're the vendor admin, if they are, stuff in
// all locations ever created under that vendor id
if($user['id'] == $user['Vendor']['staff_id'])
{
$user['Location'] = $this->attachAllLocationsByVendorId($user['Vendor']['id']);
}
 
$this->Session->renew();
$this->Session->write(self::$sessionKey, $user);
 
// If an admin is logging in, set a session
if($this->isAdmin())
{
$session_key = Configure::read('SESSION_KEY_ADMIN_TOKEN');
$token_val = md5(time());
$this->Cookie->write($session_key, $token_val, false);
}
}
 
return $this->loggedIn();
}
 
/**
* If the user that just logged in was the account creator, just stuff in all
* the locations into their session. They have access to everything and don't require
* an association
*
* @param integer $vendor_id The vendor id
*/
public function attachAllLocationsByVendorId($vendor_id)
{
 
$new_locations = array();
$locations = ClassRegistry::init('Location')->getAllActiveByVendorId($vendor_id);
foreach($locations as $loc)
{
$new_locations[] = $loc['Location'];
}
 
return $new_locations;
 
}
 
/**
* Function to check whether or not the currently logged in user
* is a member of at least one of the given roles.
*
* @param string/array $role The name of the first role (at least one required). If this is an array, it is assumed to contain an array of all of the roles to be checked
* @return boolean True if the user is a member of one of the given roles, else false
*/
public function userHasRole($role)
{
$roles = array();
if(is_array($role))
{
$roles = $role;
}
else
{
$roles = func_get_args();
}
$userRoles = $this->user('_roles');
if(!is_null($userRoles))
{
$intersect = array_intersect($roles, $userRoles);
if(count($intersect) > 0)
{
return true;
}
}
 
return false;
 
}
 
/**
* Merge in the roll ids and names
*
* @param array $db_user The user data
* @return array
*/
public function mergeRoles($db_user)
{
 
$roles = array();
 
if(isset($db_user['Role']))
{
foreach($db_user['Role'] as $role)
{
$roles[] = $role['id'];
$roles[] = $role['name'];
}
}
 
return $roles;
 
}
 
/**
* This method is called after we make an update to the users data.
* Call login again to re-store the data in the session.
*/
public function refresh()
{
$this->login(ClassRegistry::init('Staff')->findById($this->user('id')));
}
/**
* Determine if a user has a basic staff member role
*
* @return bool
*/
public function isStaff()
{
return $this->userHasRole('staff');
}
/**
* Determine if a user has an advanced staff member role
*
* @return bool
*/
public function isStaffAdvanced()
{
return $this->userHasRole('staff_advanced');
}
/**
* Determine if a user has a manager role
*
* @return bool
*/
public function isManager()
{
return $this->userHasRole('manager');
}
/**
* Determine if a user has an admin role
* @return bool
*/
public function isAdmin()
{
return $this->userHasRole('admin');
}
 
/**
* If they are the account creator.
*
* @return bool
*/
public function isAccountCreator()
{
return $this->userHasRole('account_creator');
}
 
/**
* Is the staff id the account creator?
*
* @param integer $id The staff id
* @return bool
*/
public function isStaffIdAccountCreator($id)
{
return ClassRegistry::init('Vendor')->findByStaffId($id);
}
 
/**
* Do some house keeping for when the user logs out.
*/
public function logout()
{
 
// If the super admin logs out, destroy their session to dopplegang
// into other accounts
if($this->isAdmin())
{
$this->Cookie->delete(Configure::read('SESSION_KEY_ADMIN_TOKEN'));
}
 
$this->Session->delete(Configure::read('SESSION_KEY_EXPIRED'));
return parent::logout();
}
 
}
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.