cakephp::securityコンポーネントの拡張方法
前回のエントリーでsecurityコンポーネントをいじりましたが、いい加減コアな機能を触る癖をやめてオーバーライドする方法を学べよオレ(汗)ってことで、調べてみました。
実際にsecurityコンポーネントをそのまま残しつつ、特定の関数をオーバーライドしてみます。
方法は、cakephperさんのCakeのコアコンポーネントを拡張する方法の記事を実践しただけですw 助かりました!
目的
securityコンポーネントの_generateTokenメソッドのオーバーライドが目的になります。
なので、上のブログを参考に、_generateTokenメソッドだけを定義したMySecurityComponentを作成しました。
<?php
App::import('Component', 'Security');
class MySecurityComponent extends SecurityComponent {
var $name = "MySecurity";
// SecurityComponent::_generateToken() を オーバーライド
function _generateToken(&$controller) {
if (isset($controller->params['requested']) && $controller->params['requested'] === 1) {
if ($this->Session->check('_Token')) {
$tokenData = unserialize($this->Session->read('_Token'));
$controller->params['_Token'] = $tokenData;
}
return false;
}
$authKey = Security::generateAuthKey();
$expires = strtotime('+' . Security::inactiveMins() . ' minutes');
$token = array(
'key' => $authKey,
'expires' => $expires,
'allowedControllers' => $this->allowedControllers,
'allowedActions' => $this->allowedActions,
'disabledFields' => $this->disabledFields
);
if (!isset($controller->data)) {
$controller->data = array();
}
if ($this->Session->check('_Token')) {
$tokenData = unserialize($this->Session->read('_Token'));
$valid = (
isset($tokenData['expires']) &&
$tokenData['expires'] > time() &&
isset($tokenData['key'])
);
if ($valid) {
// $token['key'] = $tokenData['key'];
}
}
$controller->params['_Token'] = $token;
$this->Session->write('_Token', serialize($token));
return true;
}
}
?>
これを使いたいコントローラーで、呼び出します。
class HogeController extends AppController {
var $name = 'Hoge';
var $components=array("MySecurity");
// Securityコンポーネントオーバーライド
public function constructClasses() {
parent::constructClasses();
$this->Security = $this->MySecurity;
}
(省略)
このconstructClassesってのがなんなのかよく分からなかったんですがw
とにかくこれで、コアコンポーネントのメソッドのオーバーライドできました。
(あ、securityコンポーネントですが、前回のエントリーで修正した部分はもとに戻してます。)