2015-12-23 2 views
1

Когда пользователь входит в систему и аутентифицируется, я использую Auth::user()->username;, чтобы показать имя пользователя на панели управления. Однако по какой-то причине, когда сеанс заканчивается, класс Auth, похоже, не работает, и страница панели мониторинга вызывает ошибку как trying to get property of non-object для Auth::user()->username;. Как я могу перенаправить пользователя на страницу входа в систему, когда он нажимает на любую ссылку или обновляет страницу после истечения срока действия сеанса?Сделать окончание сеанса перенаправить обратно для входа?

Я попробовал промежуточное программное обеспечение Authenticate.php, но он всегда перенаправляет обратно на страницу входа, независимо от того, что вы ввели учетные данные либо правильно, либо неверно. Однако, когда я не использую это промежуточное программное обеспечение, он вводит в систему пользователя.

Route.php

<?php 

/* 
|-------------------------------------------------------------------------- 
| Application Routes 
|-------------------------------------------------------------------------- 
| 
| Here is where you can register all of the routes for an application. 
| It's a breeze. Simply tell Laravel the URIs it should respond to 
| and give it the controller to call when that URI is requested. 
| 
*/ 

/* 
Actions Handled By Resource Controller 

Verb  Path     Action  Route Name 
GET   /photo     index  photo.index 
GET   /photo/create   create  photo.create 
POST  /photo     store  photo.store 
GET   /photo/{photo}   show  photo.show 
GET   /photo/{photo}/edit  edit  photo.edit 
PUT/PATCH /photo/{photo}   update  photo.update 
DELETE  /photo/{photo}   destroy  photo.destroy 


Adding Additional Routes To Resource Controllers 

If it becomes necessary to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource: 

Route::get('photos/popular', '[email protected]'); 

Route::resource('photos', 'PhotoController'); 

*/ 

// Display all SQL executed in Eloquent 
// Event::listen('illuminate.query', function($query) 
// { 
//  var_dump($query); 
// }); 



define('ADMIN','admin'); 
define('SITE','site'); 


Route::group(['namespace' => ADMIN], function() { 
    Route::get('/','[email protected]'); 
}); 


////////////////////////////////////Routes for backend/////////////////////////////////////////////////// 
Route::group(['prefix' => ADMIN,'middleware' => 'auth'], function() { 
    Route::group(['namespace' => ADMIN], function() { 
    //Route::get('/','[email protected]'); 

     //sumit routes for user registration 
     //Route::resource('users','UserController'); 
     Route::get('/users/destroy/{id}','[email protected]'); 
     Route::get('UserProf','[email protected]'); 
     Route::get('users','[email protected]'); 
     Route::get('/users/create','[email protected]'); 
     Route::get('/users/adminEdit/{id}','[email protected]'); 
     Route::post('/users/adminUpdate','[email protected]'); 
     Route::post('/users/store','[email protected]'); 
     Route::get('/users/edit/{id}','[email protected]'); 
     Route::post('/users/update/{id}','[email protected]'); 

     //airlines route 
     Route::get('airlines','[email protected]'); 
     Route::get('/airlines/create','[email protected]'); 
     Route::post('/airlines/store','[email protected]'); 
     Route::get('/airlines/edit/{id}','[email protected]'); 
     Route::post('/airlines/update','[email protected]'); 
     Route::get('/airlines/destroy/{id}','[email protected]'); 
     //end sumit routes 

     //flight routes 
     Route::get('flights','[email protected]'); 
     Route::get('showFlightBook','[email protected]'); 
     Route::get('flights/create','[email protected]'); 
     Route::post('flights/store','[email protected]'); 
     Route::get('flights/book','[email protected]'); 
     Route::get('flights/edit/{id}','[email protected]'); 
     Route::post('flights/update','[email protected]'); 
     Route::get('flights/destroy/{id}','[email protected]'); 

     //Route::resource('flight','FlightController'); 

     //hotels route 
     Route::get('hotels','[email protected]'); 
     Route::get('/hotels/create','[email protected]'); 
     Route::post('/hotels/store','[email protected]'); 
     Route::get('/hotels/edit/{id}','[email protected]'); 
     Route::post('/hotels/update','[email protected]'); 
     Route::get('/hotels/destroy/{id}','[email protected]'); 
     //end sumit routes 

     //book-hotel routes 
     Route::get('hotel-book','[email protected]'); 
     Route::get('showHotelBook','[email protected]'); 
     Route::get('hotel-book/create','[email protected]'); 
     Route::post('hotel-book/store','[email protected]'); 
     Route::get('hotel-book/book','[email protected]'); 
     Route::get('hotel-book/edit/{id}','[email protected]'); 
     Route::post('hotel-book/update','[email protected]'); 
     Route::get('hotel-book/destroy/{id}','[email protected]'); 


     //Route::resource('hotel','HotelController'); 
     //close flight routes 


     //for admin login 
     //Route::get('initlogin','[email protected]'); 
     Route::get('login','[email protected]'); 
     // Route::get('privilegeLogin','[email protected]'); 
     // Route::post('privilegeCheck','[email protected]'); 
     Route::post('login','[email protected]'); 
     Route::get('/dashboard','[email protected]'); 
     Route::get('logout','[email protected]'); 
     //user login 
     //Route::get('userLogin','[email protected]'); 
     //Route::post('userLogin','[email protected]'); 
     Route::get('/userDashboard','[email protected]'); 
     Route::get('Logout','[email protected]'); 
     //password reset 
     Route::get('forget-pass','[email protected]'); 
     //Route::get('home', '[email protected]'); 






    }); 
}); 

Route::controllers([ 
    'auth' => 'Auth\AuthController', 
    'password' => 'Auth\PasswordController', 
]); 

Authenticate.php:

<?php namespace App\Http\Middleware; 

use Closure; 
use Illuminate\Contracts\Auth\Guard; 

class Authenticate { 

    /** 
    * The Guard implementation. 
    * 
    * @var Guard 
    */ 
    protected $auth; 

    /** 
    * Create a new filter instance. 
    * 
    * @param Guard $auth 
    * @return void 
    */ 
    public function __construct(Guard $auth) 
    { 
     $this->auth = $auth; 
    } 

    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     if ($this->auth->guest()) 
     { 
      if ($request->ajax()) 
      { 
       return response('Unauthorized.', 401); 
      } 
      else 
      { 
       // return redirect()->guest('auth/login'); 
       return redirect()->guest('/'); 
      } 
     } 

     return $next($request); 
    } 

} 
+0

Это должно быть обработано в файле промежуточного слоя 'Authienticate.php'. См. Строки здесь: '{...} return redirect() -> guest ('auth/login');' Как выглядит ваш 'routes.php'? Все ли маршруты, требующие от вас входа в систему, сгруппированы этим промежуточным программным обеспечением? –

+0

@TimLewis нет, это не сгруппировано, Ok, если группировка маршрута этим промежуточным программным обеспечением Authenticate.php выполняется, я дам ему try.so on 'return redirect() -> guest ('auth/login');' путь перенаправления должен быть заменен на наш собственный путь к странице входа? – Sumit

+0

@Sumit да, это должен быть ваш путь к странице входа –

ответ

1

Если вы хотите промежуточный слой для запуска при каждом запросе HTTP к вашему приложению, просто указать класс промежуточного слоя в $ промежуточного программного обеспечения свойство вашего приложения/класс Http/Kernel.php. Таким образом, чтобы защитить каждый маршрут от доступа без проверки подлинности сделать это

protected $middleware = [ 
     'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode', 
     'Illuminate\Cookie\Middleware\EncryptCookies', 
     'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse', 
     'Illuminate\Session\Middleware\StartSession', 
     'Illuminate\View\Middleware\ShareErrorsFromSession', 
     'App\Http\Middleware\VerifyCsrfToken', 
     'App\Http\Middleware\Authenticate',// add this line according to your namespace 
    ]; 

он будет перенаправлять пользователя, если не вошли в систему. UPDATE Имейте в виду, что добавление auth промежуточного уровня, как глобальное создаст петлю перенаправлять так избежать ,

Или, если вы хотите конкретные маршруты, чтобы защитить затем прикрепить к промежуточным auth к этому маршруту

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

Я думаю, что вы не крепление аутентификации промежуточного уровня для ваших маршрутов.

+1

нет совсем не работает. – Sumit

+0

@Sumit посмотреть мой обновленный ответ –

3

Создать промежуточное программное обеспечение, как этот

<?php namespace App\Http\Middleware; 

use Closure; 
use Illuminate\Contracts\Auth\Guard; 

class Authenticate 
{ 
    /** 
    * The Guard implementation. 
    * 
    * @var Guard 
    */ 
    protected $auth; 

    /** 
    * Create a new filter instance. 
    * 
    * @param Guard $auth 
    * @return void 
    */ 
    public function __construct(Guard $auth) 
    { 
     $this->auth = $auth; 
    } 

    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     if ($this->auth->guest()) { 
      if ($request->ajax()) { 
       return response('Unauthorized.', 401); 
      } else { 
       return redirect()->guest('login'); 
      } 
     } 
     return $next($request); 
    } 
} 

Затем Группа маршрутов и защитить их как этот

Route::group(['middleware' => 'auth'], function() 
{ 
    Route::get(); 
    Route::get(); 
    Route::get(); 
    Route::get(); 
} 

Offcourse, на маршрутах вы должны указать ваши ссылки и т.д., это позволит только пользователь, если он аутентифицирован, а если нет, то будет отображаться страница входа в систему.

1

Чтобы сделать сеанс перенаправлен на ваш логин, просто добавьте -> промежуточное ПО ('auth') в файлы вашего маршрутизатора, как показано n ниже Я использую laravel 5.3

Ex: - Route :: post ('controllerName', 'folderName \ fileName @ fnNmae') -> middleware ('auth');

Или посетите https://laravel.com/docs/5.3/authentication

Смежные вопросы