LoginSignup
3
3

More than 5 years have passed since last update.

laravel4でユーザー認証を行う

Last updated at Posted at 2015-05-15

セッションサーバーの設定

memcachedをセッションサーバーに指定する場合

app/config/session.php
<?php
...
'driver' => 'memcached',
'lifetime' => 60 * 30,
'expire_on_close' => false, // ブラウザを閉じた時にセッションを終了させるかどうか
...

サーバーのhost名などを指定

app/config/cache.php
<?php
...
/*  
|--------------------------------------------------------------------------
| Memcached Servers
|--------------------------------------------------------------------------
|
| Now you may specify an array of your Memcached servers that should be
| used when utilizing the Memcached cache driver. All of the servers
| should contain a value for "host", "port", and "weight" options.
|
*/

'memcached' => array(                                                                                                                                   
    array('host' => 100.000.1.00, 'port' => 99999, 'weight' => 100),
),  
...

Userモデルの設定

Authクラスを使用するためには、UserInterfaceを実装する必要があり、下記のコードにある5つのメソッドが必要になります。今回はReminderやパスワードは必要ないため、処理は空にしてあります。

user.php
class User extends Eloquent implements UserInterface
{
    // テーブル名
    protected $table = 'users';

    public function getAuthIdentifier ()
    {   
        return $this->getKey();
    }   

    public function getAuthPassword ()
    {   
        return null;
    }   

    public function getRememberToken()
    {   
        return null;
    }   

    public function getRememberTokenName()
    {   
        return null;
    }   

    public function setRememberToken($value)                                                                                                                  
    {   
        //  
    }   
}

ログイン/ログアウトの実装

ログインとログアウトの部分のみ記載

AuthController.php
<?php
...
public function login()
{
    // ソーシャルログインなどを行う
    ...
    $user = User::create('name' => 'hogehoge', 'twitter_id' => 'hogehoge', facebook_id => 'bokeboke');
    Auth::login($user);
    ...
}

public function logout()
{
    Auth::logout();

    // トップへ飛ばすなど
    ...
}

routesなどでの認証処理

デフォルトでauthやguestなどのfilterが用意されているので、routes内で認証チェックを行うようにします。

routes.php
<?php
Route::group(['before' => 'auth'], function() {
    Route::get('/profile', 'ProfileController@index');
    ...
}); 
3
3
0

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
3
3