ログイン認証

会員がログインできるようにします。 最初にログインする画面とログインした後の会員用のメニュー画面のテンプレを作っておきます。 それぞれこんな感じで適当に。 会員ログイン画面 login.ctp のファイル名で。

<div class="members form">
<?php echo $this->Form->create('Member', array('action' => 'login'));?>

    <h2><?php __('ログイン'); ?></h2>
    <?php
        echo $this->Form->input('email',array('label' => array('text'=>'メールアドレス')));
        echo $this->Form->input('password',array('label' => array('text'=>'パスワード')));
    ?>
    <?php echo $this->Form->end(__('ログイン', true));?>
</div>
<div class="actions">
    <ul>
        <li><?php echo $this->Html->link(__('新規登録はこちら', true), array('action'=>'add')); ?></li>
    </ul>
</div>

会員メニュー画面 menu.ctp のファイル名で。

<div class="members index">
    <h2><?php __('会員メニュー'); ?></h2>
</div>
<div class="actions">
    <ul>
        <li><?php echo $this->Html->link(__('会員情報の更新', true), array('action'=>'edit')); ?></li>
        <li><?php echo $this->Html->link(__('退会手続き', true), array('action'=>'leave')); ?> </li>
        <li><?php echo $this->Html->link(__('ログアウト', true), array('action'=>'logout')); ?> </li>
    </ul>
</div>

ログアウトの完了画面も作っておきます。logout.ctp のファイル名で。

<div class="members index">
    <h2><?php __('ログアウトしました'); ?></h2>
</div>

簡単なやつでいいです。 で、コントローラ members_controller.php にログイン、ログアウトそれぞれのアクションを入れます。 ログインがこんな感じで。

    function login() {
        $this->Member->recursive = 0;
        $this->Session->destroy();
        if (!empty($this->data)) {
            if ($this->data['Member']['email']) {
                $member = $this->Member->findbyEmail($this->data['Member']['email'], array('id','password'));
                if ($member['Member']['password'] === $this->data['Member']['password']) {
                    $this->Session->write('Member.id', $member['Member']['id']);
                    $this->redirect(array('action'=>'menu'));
                } else {
                    $this->Session->setFlash(__('ログインIDまたはパスワードが違います', true));
                }
            }
        }
    }

入力された email の値で、 findbyEmail を使ってクエリーを投げます。 実行されたクエリーはこのようなものです。

SELECT `Member`.`id`, `Member`.`password` FROM `members` AS `Member` LEFT JOIN `types` AS `Type` ON (`Member`.`type_id` = `Type`.`id`) WHERE `Member`.`email` = 'your@email' LIMIT 1

結果のパスワードと入力されたパスワードの値を比較します。 認証OKだったら、 ‘Member.id’ というセッションに結果の id を入れます。 メニュー画面へリダイレクトします。

ログアウトは、

function logout() {
    $this->Session->destroy();
}
ただセッションを破棄するだけです。

メニューは、

function menu() {
    if (!$this->Session->check('Member.id')) {
        $this->redirect(array('action'=>'login'));
    }
}
Member.id というセッションがあるかどうかチェックします。

なければログイン画面にリダイレクトします。 function edit() にも、以下のチェックを入れておきます。

    function edit($id = null) {
        if (!$this->Session->check('Member.id')) {
            $this->redirect(array('action'=>'login'));
        }

        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid member', true));