程式CODE

2018年2月23日 星期五

為laravel auth 增加 圖形認證登入

參考自:https://phperzh.com/articles/1262

使用官方 auth下

1.安裝 mews/captcha
composer require mews/captcha

2.設定 /config/app.php
'providers' => [
    // ...
    Mews\Captcha\CaptchaServiceProvider::class,
]
'aliases' => [
    // ...
    'Captcha' => Mews\Captcha\Facades\Captcha::class,
]

3.產生設定檔 config/captcha.php
php artisan vendor:publish
可更改認證的字數或樣式
# 例如 flat 的樣式
...
    'flat'   => [
        'length'    => 5,  #認證的字數
        'width'     => 160,
        'height'    => 46,
        'quality'   => 90,
        'lines'     => 20,
        'bgImage'   => false,
        'bgColor'   => '#ecf2f4',
        'fontColors'=> ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'],
        'contrast'  => -5,
    ],
...


4.修改登入頁面 /resources/views/auth/login.blade.php
在密碼的下方增加
...
<div class="form-group">
<label for="captcha" class="col-md-4 control-label">驗證碼</label>                 
    <div class="form-group">
<div class="col-md-3">
<input id="captcha"  class="form-control" type="captcha" name="captcha" value="{{ old('captcha')  }}" required>
             @if ($errors->has('captcha'))
                <span class="help-block">
                    <strong>驗證碼輸入錯誤</strong>
                </span>
            @endif
        </div>
<span class="col-md-1 refereshrecapcha">
        <a href="/login/refereshcapcha">{!! captcha_img('flat')  !!}</a>  #樣式 flat
</span>
    </div>
</div>
...

5.修改 /vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
要注意的是,因為修改的是 vendor 裡的檔案,有 clone 過來的,都要再去修改一次喔
...
protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|string',
        'password' => 'required|string',
        'captcha' => 'required|captcha',  #此行為新增
    ]);
}
...

6.對應路由
修改 /routes/web.php
新增
Route::get('/login/refereshcapcha', 'Auth\LoginController@refereshcapcha');

7.修改 LoginController
/app/Http/Controllers/Auth/LoginController.php
public function refereshcapcha()
{
     return captcha_img('flat');
}


沒有留言:

張貼留言