[CakePHP] シンプルな認証を実装する(準備)

シンプルな認証と承認のアプリケーション ? CakePHP Cookbook v2.x documentation
http://book.cakephp.org/2.0/ja/tutorials-and-examples/blog-auth-example/auth.html

を利用して、フォーム認証(普通のユーザー名とパスワードを使ったログイン)を実装する。

というか、チュートリアルのままで動かしてみるというテスト。

  1. テーブルを作る。
  2. cake bake して、CRUD を作る。
  3. ログイン認証部分を作る。
  4. ロールとユーザーでアクセスを制御する。

の流れになる。

■必要なテーブル

テストするための最低限のテーブルを用意する。

ブログチュートリアル ? CakePHP Cookbook v2.x documentation
http://book.cakephp.org/2.0/ja/tutorials-and-examples/blog/blog.html

□posts テーブル
[code lang=”sql”]
/* まず、postsテーブルを作成します: */
CREATE TABLE posts (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
body TEXT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
/* それから、テスト用に記事をいくつか入れておきます: */
INSERT INTO posts (title,body,created)
VALUES (‘タイトル’, ‘これは、記事の本文です。’, NOW());
INSERT INTO posts (title,body,created)
VALUES (‘またタイトル’, ‘そこに本文が続きます。’, NOW());
INSERT INTO posts (title,body,created)
VALUES (‘タイトルの逆襲’, ‘こりゃ本当にわくわくする!うそ。’, NOW());
[/code]

□users テーブル
[code lang=”csharp”]
CREATE TABLE users (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50),
role VARCHAR(20),
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
[/code]

※規約にしたがって、複数形「posts」と「users」で用意すると、$useTable しなくて済む…が、既存のテーブルを使っても可能。

※列名を created, modified としておくと、自動で作成日時、更新日時が入る。手作業でやる場合は別途調査。

■Config/database.php を書き換える

cake bake がデータベースに接続できるように detabase.php を書き換えておく。
[code lang=”php”]
class DATABASE_CONFIG {
public $default = array(
‘datasource’ => ‘Database/Mysql’,
‘persistent’ => false,
‘host’ => ‘localhost’,
‘login’ => ‘user’,
‘password’ => ‘password’,
‘database’ => ‘test_database_name’,
‘prefix’ => ”,
‘encoding’ => ‘utf8’,
);
}
[/code]

■cake bake all で MVC を作成する

Consolecake bake all で Post と User の MVC を作成する。

※面倒がなければ、phpunit のひな形も作成しまえばok。

■IE で確認

http://localhost:81/cakeu/Posts
http://localhost:81/cakeu/Users

にアクセスをして確認(フォルダ名とポートは適宜変更)


この状態で、自由に Post と User が編集できる状態になる。

■できあがった MVC

cake bake all すると同じものができるけど、あとから参照できるの自動生成される MVC ファイルを貼り付けておきます。ソースコードを見ると、$this->request->is(‘post’) な REST の部分とか、$this->Session->setFlash なセッション部分とかが生成されていて、御影上ややこしくなっているけど、マスターテーブルの編集なんかはこれで十分なので、そのまま活用してもよいと思う。

□Model/Post.php
[code lang=”php”]
※リンクとかしてないので空っぽ

□Controller/PostController.php
[code lang=”php”]
Post->recursive = 0;
$this->set(‘posts’, $this->paginate());
}

/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->Post->exists($id)) {
throw new NotFoundException(__(‘Invalid post’));
}
$options = array(‘conditions’ => array(‘Post.’ . $this->Post->primaryKey => $id));
$this->set(‘post’, $this->Post->find(‘first’, $options));
}

/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is(‘post’)) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__(‘The post has been saved’));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The post could not be saved. Please, try again.’));
}
}
$users = $this->Post->User->find(‘list’);
$this->set(compact(‘users’));
}

/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->Post->exists($id)) {
throw new NotFoundException(__(‘Invalid post’));
}
if ($this->request->is(‘post’) || $this->request->is(‘put’)) {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__(‘The post has been saved’));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The post could not be saved. Please, try again.’));
}
} else {
$options = array(‘conditions’ => array(‘Post.’ . $this->Post->primaryKey => $id));
$this->request->data = $this->Post->find(‘first’, $options);
}
$users = $this->Post->User->find(‘list’);
$this->set(compact(‘users’));
}

/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->Post->id = $id;
if (!$this->Post->exists()) {
throw new NotFoundException(__(‘Invalid post’));
}
$this->request->onlyAllow(‘post’, ‘delete’);
if ($this->Post->delete()) {
$this->Session->setFlash(__(‘Post deleted’));
$this->redirect(array(‘action’ => ‘index’));
}
$this->Session->setFlash(__(‘Post was not deleted’));
$this->redirect(array(‘action’ => ‘index’));
}
}
[/code]

□Model/User.php
[code lang=”php”]
※Post と同じようにリンクとかしてないので空っぽ

※外部キーを使うと、Post と User がリンクするようになる

□Controller/UserController.php
[code lang=”php”]
User->recursive = 0;
$this->set(‘users’, $this->paginate());
}

/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__(‘Invalid user’));
}
$options = array(‘conditions’ => array(‘User.’ . $this->User->primaryKey => $id));
$this->set(‘user’, $this->User->find(‘first’, $options));
}

/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is(‘post’)) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__(‘The user has been saved’));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The user could not be saved. Please, try again.’));
}
}
}

/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__(‘Invalid user’));
}
if ($this->request->is(‘post’) || $this->request->is(‘put’)) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__(‘The user has been saved’));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The user could not be saved. Please, try again.’));
}
} else {
$options = array(‘conditions’ => array(‘User.’ . $this->User->primaryKey => $id));
$this->request->data = $this->User->find(‘first’, $options);
}
}

/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__(‘Invalid user’));
}
$this->request->onlyAllow(‘post’, ‘delete’);
if ($this->User->delete()) {
$this->Session->setFlash(__(‘User deleted’));
$this->redirect(array(‘action’ => ‘index’));
}
$this->Session->setFlash(__(‘User was not deleted’));
$this->redirect(array(‘action’ => ‘index’));
}
}
[/code]

以下は、View

□View/Posts/index.ctp
[code lang=”html”]


Paginator->sort(‘id’); ?> Paginator->sort(‘title’); ?> Paginator->sort(‘body’); ?> Paginator->sort(‘created’); ?> Paginator->sort(‘modified’); ?>
          Html->link(__(‘View’), array(‘action’ => ‘view’, $post[‘Post’][‘id’])); ?>
Html->link(__(‘Edit’), array(‘action’ => ‘edit’, $post[‘Post’][‘id’])); ?>
Form->postLink(__(‘Delete’), array(‘action’ => ‘delete’, $post[‘Post’][‘id’]), null, __(‘Are you sure you want to delete # %s?’, $post[‘Post’][‘id’])); ?>

Paginator->counter(array(
‘format’ => __(‘Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}’)
));
?>

Paginator->prev(‘< ' . __('previous'), array(), null, array('class' => ‘prev disabled’));
echo $this->Paginator->numbers(array(‘separator’ => ”));
echo $this->Paginator->next(__(‘next’) . ‘ >’, array(), null, array(‘class’ => ‘next disabled’));
?>

  • Html->link(__(‘New Post’), array(‘action’ => ‘add’)); ?>
  • Html->link(__(‘List Users’), array(‘controller’ => ‘users’, ‘action’ => ‘index’)); ?>
  • Html->link(__(‘New User’), array(‘controller’ => ‘users’, ‘action’ => ‘add’)); ?>

[/code]

□View/Posts/view.ctp
[code lang=”html”]


 

 

 

 

 

  • Html->link(__(‘Edit Post’), array(‘action’ => ‘edit’, $post[‘Post’][‘id’])); ?>
  • Form->postLink(__(‘Delete Post’), array(‘action’ => ‘delete’, $post[‘Post’][‘id’]), null, __(‘Are you sure you want to delete # %s?’, $post[‘Post’][‘id’])); ?>
  • Html->link(__(‘List Posts’), array(‘action’ => ‘index’)); ?>
  • Html->link(__(‘New Post’), array(‘action’ => ‘add’)); ?>
  • Html->link(__(‘List Users’), array(‘controller’ => ‘users’, ‘action’ => ‘index’)); ?>
  • Html->link(__(‘New User’), array(‘controller’ => ‘users’, ‘action’ => ‘add’)); ?>

[/code]

□View/Posts/add.ctp
[code lang=”html”]

Form->create(‘Post’); ?>

Form->input(‘title’);
echo $this->Form->input(‘body’);
?>

Form->end(__(‘Submit’)); ?>

  • Html->link(__(‘List Posts’), array(‘action’ => ‘index’)); ?>

[/code]

□View/Posts/edit.ctp
[code lang=”html”]

Form->create(‘Post’); ?>

Form->input(‘id’);
echo $this->Form->input(‘title’);
echo $this->Form->input(‘body’);
?>

Form->end(__(‘Submit’)); ?>

  • Form->postLink(__(‘Delete’), array(‘action’ => ‘delete’, $this->Form->value(‘Post.id’)), null, __(‘Are you sure you want to delete # %s?’, $this->Form->value(‘Post.id’))); ?>
  • Html->link(__(‘List Posts’), array(‘action’ => ‘index’)); ?>

[/code]

□View/Users/index.ctp
[code lang=”html”]


Paginator->sort(‘id’); ?> Paginator->sort(‘username’); ?> Paginator->sort(‘password’); ?> Paginator->sort(‘role’); ?> Paginator->sort(‘created’); ?> Paginator->sort(‘modified’); ?>
            Html->link(__(‘View’), array(‘action’ => ‘view’, $user[‘User’][‘id’])); ?>
Html->link(__(‘Edit’), array(‘action’ => ‘edit’, $user[‘User’][‘id’])); ?>
Form->postLink(__(‘Delete’), array(‘action’ => ‘delete’, $user[‘User’][‘id’]), null, __(‘Are you sure you want to delete # %s?’, $user[‘User’][‘id’])); ?>

Paginator->counter(array(
‘format’ => __(‘Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}’)
));
?>

Paginator->prev(‘< ' . __('previous'), array(), null, array('class' => ‘prev disabled’));
echo $this->Paginator->numbers(array(‘separator’ => ”));
echo $this->Paginator->next(__(‘next’) . ‘ >’, array(), null, array(‘class’ => ‘next disabled’));
?>

  • Html->link(__(‘New User’), array(‘action’ => ‘add’)); ?>
  • Html->link(__(‘List Posts’), array(‘controller’ => ‘posts’, ‘action’ => ‘index’)); ?>
  • Html->link(__(‘New Post’), array(‘controller’ => ‘posts’, ‘action’ => ‘add’)); ?>

[/code]

※何回かテストしているので ID が 1 から始まってない。

※パスワードは、そのまま書き込まれている。これは後でハッシュ値にする。

□View/Users/view.ctp
[code lang=”html”]


 

 

 

 

 

  • Html->link(__(‘Edit Post’), array(‘action’ => ‘edit’, $post[‘Post’][‘id’])); ?>
  • Form->postLink(__(‘Delete Post’), array(‘action’ => ‘delete’, $post[‘Post’][‘id’]), null, __(‘Are you sure you want to delete # %s?’, $post[‘Post’][‘id’])); ?>
  • Html->link(__(‘List Posts’), array(‘action’ => ‘index’)); ?>
  • Html->link(__(‘New Post’), array(‘action’ => ‘add’)); ?>

[/code]

□View/Users/add.ctp
[code lang=”html”]

Form->create(‘Post’); ?>

Form->input(‘title’);
echo $this->Form->input(‘body’);
?>

Form->end(__(‘Submit’)); ?>

  • Html->link(__(‘List Posts’), array(‘action’ => ‘index’)); ?>

[/code]

□View/Users/edit.ctp
[code lang=”html”]

Form->create(‘Post’); ?>

Form->input(‘id’);
echo $this->Form->input(‘title’);
echo $this->Form->input(‘body’);
?>

Form->end(__(‘Submit’)); ?>

  • Form->postLink(__(‘Delete’), array(‘action’ => ‘delete’, $this->Form->value(‘Post.id’)), null, __(‘Are you sure you want to delete # %s?’, $this->Form->value(‘Post.id’))); ?>
  • Html->link(__(‘List Posts’), array(‘action’ => ‘index’)); ?>

[/code]

この状態から、

認証(ログインとログアウト)
http://book.cakephp.org/2.0/ja/tutorials-and-examples/blog-auth-example/auth.html#id3

を追加していく。

カテゴリー: CakePHP パーマリンク