扩展请求类的属性为空 - Laravel

时间:2017-11-16 11:03:47

标签: php laravel request

我为google 2fa创建了一个名为ValidateSecretRequest的自己的请求。但我只得到空的属性。

作为补充信息:我遵循了https://www.sitepoint.com/2fa-in-laravel-with-google-authenticator-get-secure/

的教程

在authenticate()方法之后,LoginController执行postValidateToken()方法。为了测试我只实现了请求输出。

的LoginController

public function postValidateToken(ValidateSecretRequest $request) {
      echo '<pre>'; print_r($request); echo '</pre>';
}

请求类

首先我认为扩展请求有错误?实际上它应该是这样的吗?

<?php

namespace App\Http\Requests;

use Cache;
use Crypt;
use Google2FA;
use App\User;
use Illuminate\Validation\Factory as ValidatonFactory;
use Illuminate\Http\Request;

class ValidateSecretRequest extends Request {
   /**
    *
    * @var \App\User
    */
   private $user;
   public $totp;

   /**
    * Create a new FormRequest instance.
    *
    * @param \Illuminate\Validation\Factory $factory
    * @return void
    */
   public function __construct(ValidatonFactory $factory) {
      $factory->extend(
         'valid_token',
         function ($attribute, $value, $parameters, $validator) {
            $secret = Crypt::decrypt($this->user->google2fa_secret);

            return Google2FA::verifyKey($secret, $value);
         },
         'Not a valid token'
      );

      $factory->extend(
         'used_token',
         function ($attribute, $value, $parameters, $validator) {
            $key = $this->user->id . ':' . $value;

            return !Cache::has($key);
         },
         'Cannot reuse token'
      );
   }

   /**
    * Determine if the user is authorized to make this request.
    *
    * @return bool
    */
   public function authorize() {
      try {
         $this->user = User::findOrFail(
            session('2fa:user:id')
         );
      } catch (Exception $exc) {
         return false;
      }

      return true;
   }

   /**
    * Get the validation rules that apply to the request.
    *
    * @return array
    */
   public function rules() {
      return [
         'totp' => 'bail|required|digits:6|valid_token|used_token',
      ];
   }
}

但函数postValidateToken()返回一个空数组。

App\Http\Requests\ValidateSecretRequest Object
(
    [user:App\Http\Requests\ValidateSecretRequest:private] => 
    [totp] => 
    [json:protected] => 
    [convertedFiles:protected] => 
    [userResolver:protected] => 
    [routeResolver:protected] => 
    [attributes] => 
    [request] => 
    [query] => 
    [server] => 
    ...
    [session:protected] => 
    [locale:protected] => 
    [defaultLocale:protected] => en
    [isHostValid:Symfony\Component\HttpFoundation\Request:private] => 1
    [isForwardedValid:Symfony\Component\HttpFoundation\Request:private] => 1
)

1 个答案:

答案 0 :(得分:0)

找到解决方案:

您必须使用FormRequest而不是Request

use Illuminate\Foundation\Http\FormRequest;