用户未登录时,Laravel重定向到特定路由

时间:2017-07-19 08:54:53

标签: php laravel

如果我转到http://www.yourdomain.com/admin/login,我会看到我的登录页面。

如果我转到http://www.yourdomain.com/admin/example我没有管理员重定向到http://www.yourdomain.com/login

我的网络路线:

rm ~/.gitkraken

当我在/ admin之前输入一些url而用户未登录时,我想重定向到/ admin / login。

感谢。

更多信息:

应用/ HTTP /控制器/认证/ AdminLoginController.php

Auth::routes();

Route::prefix('admin')->group(function() {
    Route::get('/login','Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login','Auth\AdminLoginController@login')->name('admin.login.submit');
    Route::get('/manifiesto','AdminController@getIndex')->name('admin.dashboard');
    Route::get('/logout','Auth\AdminLoginController@logout')->name('admin.logout');
    Route::get('/trabajadores','AdminController@showTrabajadores')->name('admin.trabajadores');
    Route::get('/clientes','AdminController@showClientes')->name('admin.clientes');
    Route::get('/proyectos','AdminController@showProyectos')->name('admin.proyectos');
    Route::get('/administradores','AdminController@showAdmins')->name('admin.administradores');
});

应用\ HTTP \中间件\ AdminAuthenticate.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class AdminLoginController extends Controller
{

    protected $loginPath = 'admin/login';

    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => ['logout']]);
    } 
    public function showLoginForm()
    {
        return view('backend.public.pages.login');
    }
    public function login(Request $request)
   {
       //validate the form data
       $this->validate($request, [
           'email' => 'required|email',
           'password' => 'required|min:6'
       ]);
       //attempt to log the user in
       if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
            //if successful, then redirect to their intended location
            return redirect()->intended(route('admin.dashboard'));
       }
       return redirect()->back()->withInput($request->only('email','remember'));
   } 

   public function logout()
   {
       Auth::guard('admin')->logout();

       return redirect('/');
   }
}

4 个答案:

答案 0 :(得分:1)

  1. 创建中间件
  2. php artisan make:middleware AuthAdmin
    
    1. 使用中间件的onSave(e) { e.preventDefault(); const { editorState } = this.state; const contentState = editorState.getCurrentContent(); editorState.getCurrentContent().getBlockMap().map((block) => { const type = block.getType(); if (type === 'atomic:image') { const rangeToReplace = new SelectionState({ anchorKey: block.getKey(), focusKey: block.getKey(), }); Modifier.replaceText(contentState, rangeToReplace, '/uploads-from-my-server/test.png'); const newContentState = editorState.getCurrentContent(); this.setState({ editorState: newContentState }); } return true; }); 方法检查来宾
    2. public function handle($request, Closure $next)
      {
          if (Auth::guest()) {
              if ($request->ajax() || $request->wantsJson()) {
                  return response('Unauthorized.', 401);
              } else {
                  return redirect()->guest('admin/login');
              }
          }
      
          return $next($request);
      }
      
      1. handle数组
      2. app/Http/Kernel.php中向中间件添加密钥
        'auth_admin' => \App\Http\Middleware\AuthAdmin::class
        
        1. $routeMiddleware中间件附加到群组
        2. Route::group(['prefix' => 'admin',  'middleware' => 'auth_admin'], function() {
              // Your admin routes except login
          });
          

答案 1 :(得分:0)

在route.php文件中写下以下代码

Route::group(array('prefix' => 'admin'), function() {
        Route::controller('login', 'AdminloginController');
    });
    Route::group(array('before' => 'admin_ajax', 'prefix' => 'admin'), function() 
    {
        //route for pages which are render after login
    });
    Route::get('/admin', function() {
        return View::make('admin.loginform');
    });

并在您的filter.php文件中写下以下代码

Route::filter('admin_ajax', function() {
    if (!Auth::admin()->check()) {
        return Redirect::to('admin/login');
    } else {  
    }
});

如果你正在使用laravel 5.4

Route::get('/manage', function () {
    return redirect('manage/login');
});
Route::group(['prefix' => 'manage'], function() {
    //login bypass for the below listed controllers    
    Route::resource('login', 'AdminLoginController@showLoginForm');
    Route::post('dologin', 'AdminLoginController@login');
});

答案 2 :(得分:0)

您所能做的就是添加auth这样的中间件:

Route::group(['prefix' => 'admin',  'middleware' => 'auth'], function() {
    Route::get('/login','Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login','Auth\AdminLoginController@login')->name('admin.login.submit');
    Route::get('/manifiesto','AdminController@getIndex')->name('admin.dashboard');
    Route::get('/logout','Auth\AdminLoginController@logout')->name('admin.logout');
    Route::get('/trabajadores','AdminController@showTrabajadores')->name('admin.trabajadores');
    Route::get('/clientes','AdminController@showClientes')->name('admin.clientes');
    Route::get('/proyectos','AdminController@showProyectos')->name('admin.proyectos');
    Route::get('/administradores','AdminController@showAdmins')->name('admin.administradores');
});

但默认情况下,这会重定向到/login,如果你想覆盖它,你有两个chocies,具体取决于你是否有其他类型的用户使用/login路由!!

  • 如果没有人使用/login路线

1-您需要修改App\Http\Middleware\Authenticate::handle()方法并将/login更改为admin/login

2-然后,您需要将$loginPath属性添加到\App\Http\Controllers\Auth\AuthController班级。

<强>身份验证

namespace App\Http\Middleware;
class Authenticate {
        /**
     * 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('admin/login'); // <--- here
            }
        }

        return $next($request);
    }
}

<强> AuthController

namespace App\Http\Controllers\Auth;
class AuthController extends Controller
{
    protected $loginPath = 'admin/login'; // <--- here

    // ... other properties, constructor, traits, etc 
}
  • 如果有人使用/login路线

您必须创建自己的middleware并执行handle方法中的身份验证所需的操作,并重定向到您的admin/liging路线:)

在这种情况下:

  1. $routeMiddleware文件

    app/Http/Kernel.php属性中添加以下行
    'adminAuth' => \App\Http\Middleware\YourNewMiddleware::class,
    
  2. 不要忘记在路由组中添加新的中间件,如下所示

     Route::group(['prefix' => 'admin',  'middleware' => 'adminAuth'], function() 
     {
        // your admin routes
     });
    

答案 3 :(得分:0)

为管理员制作另一个中间件。按照步骤

  1. AdminAuthenticate位置创建名为app/Http/Middleware的文件,并复制新文件中的验证内容 将班级名称更改为AdminAuthenticate

  2. 更改句柄功能的内容,如下所示

    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('/admin/login');
            }
        }
    
        return $next($request);
    }
    
  3. $routeMiddleware

    app/Http/Kernel.php file数组中添加以下行
    'AdminAuth' => \App\Http\Middleware\AdminAuthenticate::class,
    
  4. 现在一切都好。只需在路由组中添加新的中间件,如下所示

    Route::group(['prefix' => 'admin',  'middleware' => 'AdminAuth'], function() 
    {
       // all admin routes
    });
    

    或者您可以将新的中间件添加到每个管理控制器的构造函数中,如下所示

    $this->middleware('AdminAuth');