LoginSignup
97
96

More than 5 years have passed since last update.

【CakePHP】Authコンポーネント

Last updated at Posted at 2014-07-11

Authコンポーネントの使用宣言

まずはこれが必要。通常はAppControllerに設定する。

$components = array('Auth');

自動ログイン・ログアウト処理

規約通りにusersテーブルを作成と、POSTを行えば自動で認証を行ってくれる。

ユーザテーブル
create table `users` (
 id int(11),
 username varchar(255),
 password varchar(255)
)
自動ログイン
//POSTデータが、Users['username']とUsers['password']である場合、$this->Auth->login()で認証が可能。
if($this->Auth->login()){
  //ログイン成功したときの処理
  //$this->Auth->redirectUrl()でリダイレクト先を取得 2.3より前なら$this->Auth->redirect()
  $this->redirect($this->Auth->redirectUrl());
}else{
  //ログイン失敗したときの処理
}
ログアウト
$logoutUrl = $this->Auth->logout();
$this->redirect($logoutUrl);

手動ログイン

LDAP認証など他で認証を行う場合は、手動でログイン状態にする必要がある。

手動ログイン
$user = $this->User->findById(1);
//ログイン情報を渡すことで、自動ログインする。
$this->Auth->login($user['User']);

ユーザのログイン情報の取得

ユーザ情報の取得
$user = $this->Auth->user();

自動ログインの場合はusersテーブルの該当のレコードがfind('first')の結果と同じ形式で返る。
手動ログインの場合、$this->Auth->login()に渡す値によって戻り値が異なる。
以下のようにドット区切りで取得する値を指定することもできる。

ドット区切りで取得
$this->Auth->user('User.id')

また、$this->Auth->user()の戻り値がnullか判定することでユーザがログイン済みか判定することができる。

ログイン済み判定
$user = $this->Auth->user();

if(is_null($user)){
  //ログインしていない場合
}else{
  //ログインしている場合
}

ユーザの登録・編集

usersテーブルのパスワードは暗号化して保存する。
2.3以前と2.4移行でやり方が異なる。

2.3以前
$this->User->save(array(
  'username'=>$data['user'],
  'password'=>$this->Auth->password($data['pw'])
));
2.4以降
$passwordHasher = new SimplePasswordHasher();
$this->User->save(array(
  'username'=>$data['user'],
  'password'=>$passwordHasher->hash($data['pw'])
));

認証が必要な画面を直接指定されたときのリダイレクト先

デフォルトはUserControllerのlogin()アクション。

AppController
public $components = array(
  'Auth' => array(
    //リダイレクト先
   'loginAction'=>array(
      'controller'=>'Login',
      'action'=>'form'
    )
  )
);

ログイン後の遷移先

$this->Auth->redirectUrl()の戻り値は以下の順番になる。
1.セッションの設定値
2.loginRedirectの設定値
3.デフォルトURLは/

ログイン後の遷移先の設定
public $components = array(
    'Auth' => array(
        //ログイン後の遷移先
        'loginRedirect'  => array('controller' => 'Contacts', 'action' => 'top'),
    )
);

ログアウト後の遷移先

$this->Auth->logout()の戻り値の順番。
1.logoutRedirectの設定値
2.ログイン後の遷移先

ログアウト後の遷移先の設定
public $components = array(
    'Auth' => array(
        //ログアウト後の遷移先
        'logoutRedirect' => array('controller' => 'Users', 'action' => 'login')
    )
);

モデルでidを取得したい場合は、Sessionを使う。

//AppModel.php
protected function _getCurrentUser() {
    App::uses('CakeSession', 'Model/Datasource');
    $Session = new CakeSession();

    $user_id = $Session->read('Auth.User.User.id');
    return $user_id;
}

参考:モデルからログインしているユーザー情報を取得する

97
96
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
97
96