在Laravel中为控制器添加中间件

3
使用laravel 5.3及以上版本,过滤器的概念已被移除,转而使用中间件。我已将我的laravel 4项目迁移到了5.4。
我想修改DeviceLoginController,即当我未登录时,必须刷新到登录页面。其他细节可以在控制器页面中查看。 问题:控制器页面无用,因为即使我没有登录,任何人都可以访问此页面并填写任何内容。我一直在试图解决这个问题已经两天了,但还是毫无头绪。 DeviceLoginController页面看起来像这样:
    <?php

    namespace App\Http\Controllers;
    use App\Http\Controllers\BaseController;
    use Auth;
    use Format;
    use Input;
    use DB;
    use Session;
    use Validator;
    use Hash;
    use Redirect;
    use User;
    use App\Models\License;
    use App\Models\LicenseCount;
    use App\Models\Manufacturer;
    use App\Models\DeviceModel as Model;
    use App\Models\Device;
    use App\Models\Application;

    class DeviceLoginController extends BaseController {

     /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
       $this->middleware('auth');
    }


    public function attempt() 
    {
        $username = Format::ltr(Input::get("username"));
        $device_key = Input::get("device_key");
        $imei = Format::ltr(Input::get('imei'));
        $model = Format::utr(Input::get('model'));
        $manufacturer = Format::utr(Input::get('manufacturer'));
        $app_code = Format::ltr(Input::get('app_code'));

        $user = User::where('username', $username)->first();
        if(!Hash::check($device_key, $user->device_key)) {
            Event::fire('auth.login.fail', array($username, Request::getClientIp(), time()));
            die("1");
        }
        Auth::loginUsingId($user->id);

        // check if device is already registered under given user for given app
        $license = License::where('device_imei', $imei)->where('app_code', $app_code)->where('user_username', $username);

        // if device isn't registered, first check if device is registered by different user. If not, check if licenses are available or not with the user to register new device
        if(!$license->count()) {

            // checking if licenses are available or not
            $license_count = LicenseCount::where('user_username', $username)->where('app_code', $app_code)->first();
            // if licenses are left, register the device
            if((int) $license_count['left']) {
                $manufacturer = Manufacturer::firstOrCreate(array('name' => $manufacturer));
                $model = Model::firstOrCreate(array('name' => $model, 'manufacturer_code' => $manufacturer->code));
                $device = Device::where('imei', $imei)->first();
                if(!$device) {
                    $device = Device::firstOrCreate(array('imei' => $imei, 'model_code' => $model->code));
                }
                License::create(array('device_imei' => $imei, 'app_code' => $app_code, "user_username" => $username, "expiry_date" => date("Y-m-d H:i:s", strtotime("+1 year"))));

                $license_count->left = Format::itr($license_count->left) - 1;
                $license_count->save();
            } else {
                // Prints 3, if the device is not registered and user has no more licenses left for the given app
                die("3");
            }
            // Prints 2, if the device was not previously registered and it is now registered under given user for given app
            Session::put('login_response', '2');
        } else {
            // Prints 0, if device is already registered under given user for given app
            Session::put('login_response', '0');
        }

    }
}

我的 authenticate.php 文件看起来像这样

<?php

namespace Illuminate\Auth\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authenticate
{
    /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, $guards=null)
    {
        if($this->auth ->guest())
        {
            if($request->ajax())
            {
                return response('unauthorized',401);
            }
            else
            {
                return redirect()->guest('login');
            }
        }
        //$this->authenticate($guards);

        return $next($request);
    }

    /**
     * Determine if the user is logged in to any of the given guards.
     *
     * @param  array  $guards
     * @return void
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    protected function authenticate(array $guards)
    {
        if (empty($guards)) {
            return $this->auth->authenticate();
        }

        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        throw new AuthenticationException('Unauthenticated.', $guards);
    }
}

我是Laravel的新手,请原谅我如果问了一些愚蠢的问题。我现在不知道该怎么办了。请帮忙告诉我是否需要添加其他文件。

1个回答

3
很棒,你已经将迁移工作完成到Laravel 5.4。不过,我建议你先阅读文档或观看Laravel 5.4从头开始的系列视频。
针对你的问题,你需要将调用控制器函数的路由放在“auth”中间件下面。Laravel已经默认提供了这个中间件。如果用户未登录并调用路由,则可以更改路由到重定向用户的位置。
请查看文档
假设你的路由是'admin/profile',并且你已将其定义在web.php路由文件中,则可以像以下示例一样向其添加中间件(摘自文档)。
Route::get('admin/profile', function () {
    //
})->middleware('auth');

为了将多个路由放在同一中间件下,您可以使用路由组。

请从控制器构造函数中移除中间件。您在哪里使用 authenticate.php 文件?我认为它不是必要的。 - Himanshu Sharma
先生,我已经添加了路由 Route::get('login','DeviceLoginController@attempt')->middlew‌​are('auth'); - sameer
是的,在路由文件中添加了 middleware('auth')。在 web.php 中添加了另一个路由:Route::post('device',array('uses' => 'DeviceLoginController@attempt', 'as' => 'pages.device.')); - sameer
另外,你确定这应该是一个GET路由吗?改成POST。尝试在终端中运行composer dump-autoload。 - Himanshu Sharma
感谢您的回答,先生。 - sameer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接