今日は、Laravel4の認証設定(その1)の続きを調べてみたいと思います。前回は、usersテーブルの作成とユーザーの登録までを作成しました。本日は、ログインフォームの作成とAuthフィルターの適用方法を調べてみたいと思います。
ログインフォームの作成
1. それでは、ログインフォームを下記のように作成します。
laravel4/app/views/login.blade.php
<!doctype html> <html lang="ja"> <head> <meta charset="utf-8"> <title>ログイン</title> <meta name="viewport" content="width=device-width,minimum-scale=1"> {{ Html::style('tbs/css/bootstrap.min.css') }} {{ Html::style('tbs/css/bootstrap-responsive.min.css') }} {{ Html::style('tbs/css/mystyle.css') }} </head> <body> <div class="container" id="login-container"> <div class="ribbon"> <div class="ribbon-stitches-top"> </div> <strong class="ribbon-content"> <h1>WinRoad徒然草</h1></strong> <div class="ribbon-stitches-bottom"></div></div> {{ Form::open(array('class'=>'form-container')) }} <div class="form-title"><h2>ログイン</h2></div> {{ Form::label('username','ユーザー名',array('class'=>'form-title')) }} {{ Form::text('username',Input::old('username',''),array('class'=>'form-field')) }} @if($errors->has('username')) <div class="form-title label label-important"> {{ $errors->first('username') }} </div> @endif {{ Form::label('password','パスワード',array('class'=>'form-title')) }} {{ Form::password('password',array('class'=>'form-field')) }} @if($errors->has('password')) <div class="form-title label label-important"> {{ $errors->first('password') }} </div> @endif @if($errors->has('warning')) <div class="alert alert-error" id="alert"> {{ $errors->first('warning') }} </div> @endif <div class="submit-container"> {{ Form::submit('Login',array('class'=>'submit-button')) }} </div> {{ Form::token() }} {{ Form::close() }} </div> <script src="http://code.jquery.com/jquery-1.9.1.min.js"> </script> {{ Html::script('tbs/js/bootstrap.min.js') }} </body> </html>
- 9行目:前回のこれは便利!CSSジェネレータ『Live tools』で作成したCSSファイル(スタイルシート)をmystyle.css名でtbs/cssフォルダに保存しました。
Authフィルターの適用
2. 次にコントローラにアクセス制限をかけます。UserController.phpの最初の方に下記のコードを追加します。
laravel4/app/controllers/UserController.php
//コンストラクター public function __construct() { $this->beforeFilter('auth'); $this->beforeFilter('csrf',array('on'=>'post')); }
- 4行目:authフィルターをUserController全体に適用します。
- 5行目:POST送信の時だけ、csrfフィルターを適用します。
3. index.blade.phpにログアウト用のリンクも作成します。尚、ここには記述しませんが、ceate.blade.phpにもログアウト用のリンクを作成します。
laravel4/app/views/user/index.blade.php
@extends('layouts.master') @section('navigation') @parent <li><a href={{ URL::to('user/create') }}>新規作成</a></li> <li><a href={{ URL::to('logout') }}>ログアウト</a></li> @stop @section('content') <table class="table table-striped table-bordered"> <tr> <th>id</th> <th>ユーザー名</th> <th>Eメールアドレス</th> <th>パスワード</th> <th>作成日</th> <th>更新日</th> <th>処理</th> </tr> @foreach($users as $user) <tr> <td>{{ $user->id }}</td> <td>{{ $user->username }}</td> <td>{{ $user->email }}</td> <td>{{ $user->password }}</td> <td>{{ $user->created_at }}</td> <td>{{ $user->updated_at }}</td> <td><i class="icon-pencil"></i> <a href="#">編集</a> <i class="icon-remove"></i> <a href="#">削除</a></td> </tr> @endforeach @stop
login,logoutルーターの作成
4. 尚、beforeFilterにexceptのチェーンメソッド(フィルターの例外設定)がなさそうなので、loginメソッドと、logoutメソッドはルーターで作成したいと思います。ルーターに下記のコードを追加します。※exceptメソッドも、onlyメソッドもありますので、UserController内で作成してもいいと思います。
laravel4/app/routes.php
/********************** * ログインページの表示 **********************/ Route::get('login',array('as'=>'login',function() { return View::make('login'); })); /********************** * ログイン処理 **********************/ Route::post( 'login',function() { //入力データの取得 $inputs = Input::only(array('username', 'password')); //バリデーションルールの作成 $rules = array ( 'username' => array ( 'required' ), 'password' => array ( 'required' ), ); //バリデーション処理 $val = Validator::make( $inputs, $rules ); //バリデーションNGなら if ($val->fails()) { //エラー値と一緒にバック return Redirect::back() ->withErrors( $val ) ->withInput(); } //認証NGなら if(!Auth::attempt($inputs)) { return Redirect::back() ->withErrors(array('warning'=>'ユーザー名かパスワードが違います。')) ->withInput(); } //TOPページへ return Redirect::to('/'); }); /************************* * ログアウト処理 *************************/ Route::get('logout',function(){ Auth::logout(); return Redirect::back(); });
5. それでは、実際にログインしてみましょう。下記のアドレスを入力すると、ログインページへ移動するはずです。
http://localhost/laravel4/public/user
6. 間違った値を入力してみます。エラーメッセージが表示されるはずです。
7. そして正しい値を入力すると、トップページへ移動すればOKです。
※トップページにはAuthフィルターをかけていませんので、ブラウザから直接入力しても、このページへ移動することが出来ます。但し、ログインしていないときは、ユーザー一覧やユーザー作成のリンクは表示されません。
8. トップページは、ログインしていないときは、ユーザー一覧、ユーザー作成、ログアウトのリンクの代わりにログインリンクを表示するように修正しましたので、下記にコードを記述しておきます。
laravel4/app/views/hello.blade.php
@extends('layouts.master') @section('navigation') @parent @if(Auth::check()) <li><a href={{ URL::to('user/index') }}>ユーザー一覧</a></li> <li><a href={{ URL::to('user/create') }}>ユーザー作成</a></li> <li><a href={{ URL::to('logout') }}>ログアウト</a></li> @else <li><a href={{ URL::to('login') }}>ログイン</a></li> @endif @stop @section('content') @if(Auth::check()) <h2>ようこそ{{ Auth::user()->username }}さん</h2> @endif <h1>Hello World!</h1> @stop
尚、Htmlクラスが復活していますので、5行目以下は、下記のようにすっきり記述することが出来ます。他も修正しておいてください。
<li>{{ Html::link('user/index','ユーザー一覧') }}</li> <li>{{ Html::link('user/create','ユーザ作成') }}</li> <li>{{ Html::link('logout','ログアウト') }}</li>
9. ログインしていないときは下記のように表示されます。
本日は以上です。