#25
続き
・すべての画面でログイン中のユーザー名を表示
users_controller.php
<?php class UsersController extends AppController { var $name = 'Users'; var $uses = array('User','Seminar'); function index (){ $this->checkSession(); $auth=$this->Session->read('auth'); $this->set('me', $this->User->findById($auth['id'])); } function login(){ $this->pageTitle = 'Welcome to Papazy!'; $this->set('error', false); if (!empty($this->data)){ $cond=array( 'email'=>$this->data['User']['email'], 'pwd'=>$this->data['User']['pwd'] ); $data=$this->User->findAll($cond); if(count($data)==0){//NG $this->log("LOGINエラー",LOG_ERROR); $this->set('error', true); } else{//OK //セッションにログイン情報を格納する。 $this->Session->write('auth', $data[0]['User']); $this->log("LOGINユーザー:".$data[0]['User']['email'],LOG_DEBUG); $this->flash("{$data[0]['User']['name']}さん、こんにちは。","/users/index/"); } /* $someone = $this->User->findByEmail($this->data['User']['email']); if(!empty($someone['User']['pwd']) && $someone['User']['pwd'] == $this->data['User']['pwd']){ $this->Session->write('my_id', $someone['User']['id']); $this->log("LOGINユーザー:".$this->data['User']['email'],LOG_DEBUG); $this->redirect('/users/index/'); } else{ $this->log("LOGINエラー",LOG_ERROR); $this->set('error', true); } */ } } function logout(){ $this->Session->delete('auth'); $this->flash("さようなら。","/users/login/"); } } ?>
app_controller.php
<?php class AppController extends Controller { function checkSession(){ // If the session info hasn't been set... if (!$this->Session->check('auth')){ // Force the user to login $this->redirect('/users/login'); exit(); } } function beforeFilter(){ //セッションから取り出したログイン情報をセット $auth=$this->Session->read('auth'); $this->set("auth",$auth); } } ?>
header.thtml
<div id="header"> <h1><a href="http://d.hatena.ne.jp/kappapa/"><img src="/work/yoyaku/app/webroot/img/papazy.gif" width="112" height="40" align="left" border="0" alt="papazy" /></a></h1> <?php if($auth){ echo $auth['name']."さん "; echo $html->link("ログアウト ","/users/logout"); } else{ echo $html->link("ログイン ","/users/login"); } ?> </div><!-- end of header -->
以上3つのファイルの修正を行いました。
ついでにログインチェックの方法も本に書いてある方法に変更しました。
app_controller.phpのbeforeFilterに処理を書くことで、当アプリのすべてのアクション実行前に、
セッション情報を取得するようになりました。
また、その情報を使ってレイアウトのヘッダ部分に名前を表示するようになりました。