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

时间:2017-06-25 07:58:06

标签: php laravel controller laravel-middleware

随着laravel 5.3及更高版本,过滤器的概念已经消失,而中间件则被使用。我已将laravel 4迁移到5.4。

我想修改DeviceLoginController,当我没有登录时,必须刷新到登录页面。其他详细信息可以在控制器页面中看到。

问题:控制器页面没用,因为即使我没有登录,任何人都可以访问此页面并且任何人都可以填写任何内容。我一直试图解决这个问题2天仍然没有。

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 个答案:

答案 0 :(得分:2)

很高兴你完成了向Laravel 5.4的迁移。但是,我建议您首先阅读文档或从Scratch系列中观看Laravel 5.4。

对于你的问题,你需要把调用控制器功能的路线放在&#39; auth&#39;中间件。 Laravel提供开箱即用的中间件。如果用户未登录并调用该路由,您可以更改用户重定向的路由。

请仔细阅读documentation

假设您的路线是&#39; admin / profile&#39;并且您已经在web.php路由文件中定义了这个,您可以如图所示向其添加中间件(从DOC中选择此示例。)

Route::get('admin/profile', function () {
    //
})->middleware('auth');

要在同一中间件下放置多个路由,可以使用路由组。