Laravel通过ajax认证

时间:2015-10-05 23:30:10

标签: php laravel laravel-5 laravel-5.1

我为管理员ajax请求编写Controller。我编写用于检查用户登录的构造方法是否if阻止工作正常,但始终返回user.setting视图并返回构造不起作用。

控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;

class AjaxController extends Controller {

    public function __construct() {
        if (Auth::check() == FALSE) {
            return view('errors.notLogin');
        }
    }

    public function settings() {
        return view('user.setting');
    }

}

路线:

Route::post('ajax/settings', 'AjaxController@settings');

JS:

acc_settings = function (url) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: url,
        type: 'POST',
        data: 'settings=settings',
        success: function (data) {
            $("#ajax").html(data);
        }
    });
};

3 个答案:

答案 0 :(得分:3)

You should use middleware instead of re-implement the functionality.

public function __construct()
{
    $this->middleware('auth');
}

then inside auth you could add both cases for ajax & regular http request -

public function handle($request, Closure $next)
{

    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return view('errors.notLogin');
        }
        else
        {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}

答案 1 :(得分:3)

This looks like a job for Middleware.

Laravel Docs on Middleware

You shouldn't do anything in the constructor of your AjaxController, instead you should register a middleware for the route you want to protect:

Route::post('ajax/settings', [
    'uses' => 'AjaxController@settings', 
    'middleware' => 'auth'
]);

Since you'll probably need many Ajax functions, you could instead group them all with the same middleware, and the "ajax" prefix while you are at it:

Route::group(['prefix' => 'ajax', 'middleware' => 'auth'], function () {
    Route::post('settings', 'AjaxController@settings');
    //Define more routes here...
});

'auth' is one of the preset middleware shipped with Laravel, you can find it at App\Http\Middleware\Authenticate and modify it as needed, or register your own "Ajax" middleware. In either case, your handle function would look like:

public function handle($request, Closure $next)
{
    if ($this->auth->guest()) {
        return view('errors.notLogin');
    }

    return $next($request);
}

答案 2 :(得分:0)

Why don't you use Middleware?

Your constructor should be:

 public function __construct() {
     $this->middleware('auth');
 }

You can also assign middleware to run on a route in routes.php:

Route::group(['middleware' => 'auth'], function () {
    Route::post('ajax/settings', 'AjaxController@settings');
}