6月 05

17.ログイン認証

go @ 5:33 AM

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

<?php echo $javascript->link(array('jquery','form','util'), false); ?>
<div class="members form">
<?php echo $form->create('Member', array('action' => 'login')); ?>
	<h2><?php __('ログイン');?></h2>
	<?php
		echo $form->input('email', array('label' => 'メールアドレス'));
		echo $form->input('password', array('label' => 'パスワード'));
	?>
<?php echo $form->end('ログイン'); ?>
</div>
<div class="actions">
	<ul>
		<li><?php echo $html->link(__('新規登録はこちら', true), array('action'=>'add')); ?></li>
	</ul>
</div>

会員メニュー画面

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

ついでにログアウトの完了画面も作っておきますか。

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

簡単なやつでいいです。

で、コントローラ members_controller.php の上の方に

	var $components = array('Session');

を追加して、
あとはログイン、ログアウトそれぞれのアクションを入れます。
ログインがこんな感じで。

	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 を使ってクエリーを投げます。
結果のパスワードと入力されたパスワードの値を比較します。
認証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() にも、以下のチェックを入れておきます。

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

>>次のページ「画像アップロード」へ

Comments are closed.

here comes