程式功能研究 === ###### tags: `相關研究` [TOC] ### Laravel登入限制 使用[RateLimiter](https://blog.twjoin.com/laravel-%E9%99%90%E5%88%B6%E6%B5%81%E9%87%8F%E5%B7%A5%E5%85%B7-ratelimiter-throttlerequests-b8c418a13701),以公司系統為例,變動的檔案有UserController.php、login.blade.php。 RateLimiter — 簡介 RateLimiter 為 laravel 底層元件, 主要提供簡易的流量限制方法 > RateLimiter::tooManyAttempts 檢查 $key 對應的指定嘗試次數是否超過最大嘗試 ``` // 範例: call:123 是否已經超過 100 次 $result = RateLimiter::tooManyAttempts( "call:123", 100, ); if ($result === true) { return 'too many request'; } return $result; ``` > RateLimiter::hit 會設定 $key 以及其對應的 $decaySeconds (時間範圍) , 且主動對 $key 的嘗試次數 + 1 ``` // 範例: 嘗試次數從 0 開始 // 等同於觸發了 3 次嘗試. RateLimiter::hit("call:123"); RateLimiter::hit("call:123"); RateLimiter::hit("call:123"); ``` 詳細的其他應用可以參考連結文章,以下為使用公司系統實作 --- > UserController: > use Illuminate\Support\Facades\RateLimiter ``` public function login_send(Request $req) { //檢查是否超過登入嘗試次數限制 if (RateLimiter::tooManyAttempts($req->ip(), $perMinute = 3)) { $seconds = RateLimiter::availableIn($req->ip()); return redirect()->back() ->withInput($req->only('account')) ->withErrors(['message_error' => '登入嘗試次數過多,請在 ' . $seconds . ' 秒後再試']); } // 帳號錯誤 if (!$accontCheck) { RateLimiter::hit($req->ip(), $decaySeconds = 100); // 登入失敗時增加登入嘗試計數器(單位:秒) Session::put('message_error', '帳號錯誤'); return Redirect()->route('login'); } } // 密碼錯誤 if (!$passwordCheck) { RateLimiter::hit($req->ip(), $decaySeconds = 100); // 登入失敗時增加登入嘗試計數器(單位:秒) Session::put('message_error', '密碼錯誤'); return Redirect()->route('login'); } ``` > login.blade.php > 在原本include('admin.common.message')下再新增Error顯示區塊 ``` @if ($errors->any()) <div class="alert alert-danger"> @foreach ($errors->all() as $error) <p>{{ $error }}</p> @endforeach </div> @endif ``` --- #### Laravel 5版本 > 因教育系統使用Laravel 5.1,所以要先到[此網址](https://github.com/laravel/framework/blob/5.1/src/Illuminate/Cache/RateLimiter.php)copy Illuminate\Support\Facades\RateLimiter php檔到對應的資料夾下,才能引入這工具 > tomanyattempts則為3個參數,hit缺少increment function(8有 5沒有),要從8的相關檔案copy程式碼 ``` 1.Contracts\Cache\Repository.php要新增 public function increment($key, $value = 1); 2.Illuminate\Cache\Repository.php要新增 /** * Increment the value of an item in the cache. * * @param string $key * @param mixed $value * @return int|bool */ public function increment($key, $value = 1) { return $this->store->increment($key, $value); } ``` --- ### PDF相關 #### TCPDF 將程式生成PDF [說明](https://github.com/elibyy/tcpdf-laravel) [參考教學](https://tw511.com/a/01/50032.html) [指令](https://hackmd.io/@nfu-johnny/r1rGzagqY) > composer require elibyy/tcpdf-laravel ``` config.php要新增相關套件: 'providers' => [ //... Elibyy\TCPDF\ServiceProvider::class, ] //... 'aliases' => [ //... 'PDF' => Elibyy\TCPDF\Facades\TCPDF::class ] ``` #### PDF parser 解析PDF [說明](https://github.com/smalot/pdfparser) [進階語法](https://github.com/smalot/pdfparser/blob/master/doc/Usage.md) > composer require smalot/pdfparser