CakePHP1.3.6:Authコンポーネントで認証する

Authコンポーネントを使って、以下のような認証を実装する。

Mainというプログラムを作成し、以下のようなメニュー画面をつくる。

ここにアクセスするためには、以下のようなログイン画面を通すようにする。

また、メニューからログアウトすると以下のような画面に遷移する。

ルートの設定

まず、インデックスにアクセスされたときにmainにアクセスするようにCakePHPでデフォルト定義されているルートを変更する。
/app/config/routes.phpを以下のようにする。

<?php
/**
 * Routes configuration
 *
 * In this file, you set up routes to your controllers and their actions.
 * Routes are very important mechanism that allows you to freely connect
 * different urls to chosen controllers and their actions (functions).
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       cake
 * @subpackage    cake.app.config
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
/**
 * Here, we are connecting '/' (base path) to controller called 'Pages',
 * its action called 'display', and we pass a param to select the view file
 * to use (in this case, /app/views/pages/home.ctp)...
 */
//	Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
	Router::connect('/', array('controller' => 'main', 'action' => 'index', 'home'));
/**
 * ...and connect the rest of 'Pages' controller's urls.
 */
//	Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));

テーブルの作成

Authはコンポーネントはデフォルトで、usersというテーブルのusernameとpasswordフィールドで認証を行う。
そのため、以下のようなテーブルを作成する。

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

モデル作成

/app/models/users.phpを作成する。

<?php 

class User extends AppModel {
	public $name = 'User';

	public $hasOne = array(
		"UserAttr" => array(
			'className' => 'UserAttr',
			'dependent' => true
		)
	);
	
	public $validate = array(
			'username'=>array(
							array(
								'rule' => 'notEmpty',
								'message' =>'入力してください'),
							array(
								'rule' => 'isUnique',
								'message' =>'すでに登録されています'),
							array(
								'rule' => 'alphaNumeric',
								'message' =>'半角英数字以外は入力できません')
					),
	);
}

?>

コントローラー

users_controller.phpにlogin()とlogout()アクションを作成する。

<?php
require_once '../vendors/MyConverter.class.php';

class UsersController extends AppController{
	public $name = 'Users';
	public $uses = array('User');
	public $components = array('Auth');
	public $layout 	= 'myznala';
	
	function beforeFilter(){
		$this->Auth->allow('add');
		$this->Auth->allow('logout');
		$this->Auth->authError= 'ログインしてください';
		$this->Auth->loginError = 'ログインに失敗しました';
	}
	
	/**
	 * 
	 * ログイン
	 */
	function login(){
		$this->set('title_for_layout', "ログイン");
	}
	
	/**
	 * 
	 * ログアウト
	 */
	function logout(){
		$this->set('title_for_layout', "ログアウト");
		$this->Session->destroy();
		$this->Auth->logout();
	}

}
?>
mainコントローラー

main_contoroler.phpを変更する。index()には、以下のようにセッションにusernameを保存するようにを設定してみる。

    // 以上略

	public $components = array('Auth');
	
	function beforeFilter(){
		$this->Auth->authError= 'ログインしてください';
	}
	
	/**
	 * 
	 * 初期画面
	 */
	function index(){
		$this->set('title_for_layout', "メインメニュー");
		$this->Session->write('Login.username',$this->Auth->user('username'));
	}

    // 以下略

他のコントローラーにも、以下を追加する。

    // 以上略

	public $components = array('Auth');
	
	function beforeFilter(){
		$this->Auth->authError= 'ログインしてください';
	}

    // 以下略

ビューの作成

/app/views/usersディレクトリにlogin.ctpとlogout.ctpを作成する。

login.ctp
<?php

if($session->check('Message.auth')){
	echo $session->flash('auth');
}

echo '<div style="width:450px;float:left;">';
echo $html->image('keyaki450.jpg');
echo '<br>
<p style="text-align:right;">
<small>
photo by <a href="http://www.flickr.com/photos/wanderingse/2094523276/" target="_blank">tetsuya_odaka</a></p>
</small>
<br>
<small>
Some rights reserved by <a href="http://ezogp.sourceforge.jp/hp/" target="_blank">EzoGP project.</a>
</small>
</div>
<div style="width:420px;float:right;">';

echo $form->create('User',array('action'=>'login'));
echo '<table border="1">
<tbody>
    <tr>
    	<th align="left">ユーザーID</th>
    	<td>';

echo $form->text('User.username',array('size'=>'30'));

echo '</td>
    </tr>
    <tr>
    	<th align="left">パスワード</th>
    	<td>';

echo $form->password('User.password',array('size'=>'30'));

echo '</td>
    </tr>
  	</tbody>
	</table>';

echo $form->end('ログイン');

?>
logout.ctp
<?php
echo '<h2>ログアウトしました</h2>';
echo '<br>';
echo $html->link('メニューへ戻る',
  array('controller'=>'main', 'action'=>'index'));

?>

続きはこちら