認証処理に関連して、わからないことがあります。
以下のコードは「各ユーザーの投稿を個別に表示する」ページ(以降「個別ページ」)の処理です。
一般ユーザー ("role" = 1) と管理者ユーザー ("role" = 0) とで処理を分けています。
また、管理者ユーザーだけが、自分以外のユーザーの個別ページを閲覧できます。
問題は以下のような流れで発生します。
・ログアウト状態で個別ページのリンクをクリック
・ログイン画面に遷移し、管理者ユーザーでログイン
・ログインは成功するものの、個別ページに遷移しない($user = TableRegistry::get('users')->findByName($name)->firstOrFail()
が例外を投げる)
どうやら、ログイン処理を挟むことによって、view()の引数である$name(テンプレートでは$login_user_name = $this->request->session()->read('Auth.User.name')
)の値がnullになっているようです。
ログイン後も$nameの値を引き継ぐ方法があればお教えいただきたいです(代替案でも嬉しいです)。
どうぞよろしくお願いいたします。
lang
1// PostsController.php 2public function view($name = null) 3{ 4 5 if ($this->Auth->user('role') === 1) { 6 if ($this->Auth->user('name') !== $name) { 7 return $this->redirect(['action' => 'view', $this->Auth->user('name')]); 8 } 9 $query = $this->Posts->find() 10 ->where(['user_id' => $this->Auth->user('id')]); 11 } 12 13 if ($this->Auth->user('role') === 0) { 14 try { 15 $user = TableRegistry::get('users')->findByName($name)->firstOrFail(); 16 } catch(\Exception $e) { 17 $this->Flash->error(__('存在しないユーザーを参照しようとしています')); 18 return $this->redirect(['controller' => 'Users', 'action' => 'index']); 19 } 20 21 $query = $this->Posts->find() 22 ->where(['user_id' => $user['id']]); 23 } 24 25 $posts = $this->paginate($query); 26 $this->set(compact('name', 'posts')); 27} 28 29// UsersController.php 30public function login() { 31 if ($this->Auth->user('id')) { 32 $this->Flash->error(__('すでにログインしています')); 33 return $this->redirect(['controller' => 'Posts', 'action' => 'index']); 34 } 35 if ($this->request->is('post')) { 36 $user = $this->Auth->identify(); 37 if ($user) { 38 $this->Flash->success(__('ログインしました')); 39 $this->Auth->setUser($user); 40 return $this->redirect($this->Auth->redirectUrl()); 41 } else { 42 $this->Flash->error(__('ユーザー名またはパスワードが不正です')); 43 } 44 } 45} 46 47// header.ctp 48<div class="header"> 49 <div class="upper"> 50 <?= $this->Html->link( 51 "<h1>Let's Post</h1>", 52 ['controller' => 'Posts', 'action' => 'add'], 53 ['escape' => false] 54 ) ?> 55 </div> 56 <div class="lower"> 57 <?php 58 $login_user_name = $this->request->session()->read('Auth.User.name'); 59 if ($login_user_name) { 60 echo $this->Html->link( 61 'Logout', 62 ['controller' => 'Users', 'action' => 'logout'], 63 ['class' => 'logout'] 64 ); 65 } else { 66 echo $this->Html->link( 67 'SignUp', 68 ['controller' => 'Users', 'action' => 'add'], 69 ['class' => 'signup'] 70 ); 71 echo $this->Html->link( 72 'Login', 73 ['controller' => 'Users', 'action' => 'login'], 74 ['class' => 'login'] 75 ); 76 } 77 ?> 78 <?= $this->Html->link( 79 'Account', 80 ['controller' => 'Users', 'action' => 'view', $login_user_name], 81 ['class' => 'account'] 82 ) ?> 83 <?= $this->Html->link( 84 'MyPosts', 85 ['controller' => 'Posts', 'action' => 'view', $login_user_name], 86 ['class' => 'myposts'] 87 ) ?> 88 <?= $this->Html->link( 89 'Home', 90 ['controller' => 'Posts', 'action' => 'index'], 91 ['class' => 'home'] 92 ) ?> 93 </div> 94</div>
あなたの回答
tips
プレビュー