ACLを使わない簡単なアクセス制御

http://mojaie.hatenablog.jp/entry/2012/05/19/170024

bakeするときはgroupは後からカラム追加すると良いよ ※

[php]
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL,
`username` varchar(100) NOT NULL,
`group` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
);
INSERT INTO `users` (`id`, `username`, `group`, `password`) VALUES(‘1’, ‘admin’, ‘admin’, ‘adminpassword’);
INSERT INTO `users` (`id`, `username`, `group`, `password`) VALUES(‘2’, ‘user’, ‘user’, ‘userpassword’);
[/php]

AppController

[php]
class AppController extends Controller {
public $helpers = array(
‘Html’,
‘Form’,
‘Session’,
);
public $components = array(
‘Session’,
‘Auth’ => array(

),
);
public function beforeFilter() {
$this->Auth->authorize = array(‘Controller’); //これを使うときはコントローラにbeforeFilterをからでも書くこと
$this->Auth->loginRedirect = ‘/’;
$this->Auth->logoutRedirect = ‘/’;
if ($this->Auth->loggedIn()) {
$this->set(‘authUser’, $this->Auth->user());
}
}
}
[/php]

UsersController

[php]
public function beforeFilter() {
}
/**
* login method
*/
public function login() {
$this->layout = ”;
/** POST送信時にログイン認証処理を行う */
if ($this->request->is(‘post’)) {
/** ログイン認証処理 */
if ($this->Auth->login()) {
/** 認証後のリダイレクト処理 */
$this->redirectlogin();
} else {
/** 認証エラーメッセージ出力 */
$this->Session->setFlash(__(‘ログインに失敗しました。’));
}
}else{
/** ログイン認証済の場合、顧客画面へ遷移 */
if ($this->Auth->login()) {
$this->redirectlogin();
}
}
}

/**
* redirectlogin method
*/
public function redirectlogin() {
try {
/** 顧客一覧ページのURLを格納 */
$redirectUrl = $this->Auth->redirect();
/** 顧客一覧ページにリダイレクト */
$this->redirect($redirectUrl);
} catch (Exception $e) {
/** エラー(ログアウト) */
$this->Auth->logout();
/** 認証エラーメッセージ出力 */
$this->Session->setFlash(__(‘ログインに失敗しました。’));
}
}

/**
* logout method
*/
public function logout() {
$this->Session->destroy();
$this->redirect($this->Auth->logout());
}
[/php]

権限をつけたいコントローラーに書くよ 

※これを書くと基本adminしかアクセスできなくなる

[php]
public function beforeFilter(){
//openaccessには誰でもアクセスできる
$this->Auth->allowedActions = array(‘openaccess’);
//親クラス(AppController)読み込み
parent::beforeFilter();
}

public function isAuthorized() {
if ($this->Auth->user(‘group’) == ‘admin’) {
//admin権限を持つユーザは全てのページにアクセスできる
return true;
} elseif ($this->Auth->user(‘group’) == ‘user’) {
if ($this->action == ‘useronly’) {
//user権限を持つユーザはuseronlyにアクセスできる
return true;
}
}
return false;
}

//誰でもアクセスできる
public function openaccess() {
}

//会員だけアクセスできる
public function useronly() {

}

//管理者だけアクセスできる
public function adminonly() {
}
[/php]

openaccess.ctpは誰でもアクセスできる

useronly.ctpは会員だけアクセスできる

adminonly.ctpは会員だけアクセスできる

Authで暗号化してたらログインできなかったので、暗号化解除したよ

http://aman.sakura.ne.jp/?p=782

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です