Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Auth problems with CakePHP 2.0 - migrating from 1.3 - 2.0
/****************************************************************
* 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();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.