2015-06-07 228 views
1

在Laravel 5中,您如何定制默认身份验证?例如,我有多种类型的用户进行身份验证。每种类型的用户都是由一个角色定义的,例如求职者,招聘人员等。每种类型的用户都有不同类型的注册表格来捕获一些配置文件的细节。所以我有以下表格:Laravel 5自定义身份验证

users 
roles 
role_user 
jobseeker_profile 
recruiter_profile 

Laravel 5中的默认authcontroller和passwordcontroller使用所有身份验证方法的特征。你将如何去定制它 - 你们编辑现有的特征文件?例如,getRegister方法返回寄存器视图,但我希望它在决定显示哪个视图之前检查路由。

// default method 
public function getRegister() 
{ 
    return view('auth.register'); 
} 

// custom method 
public function getRegister() 
{ 
    if (Request::is('jobseeker/register')) 
    { 
    return view('auth.jobseeker_register'); 
    } 
    elseif (Request::is('recruiter/register')) 
    { 
    return view('auth.recruiter_register'); 
    } 

} 

同样默认postLogin方法如下:

public function postLogin(Request $request) 
{ 
    $this->validate($request, [ 
     'email' => 'required|email', 'password' => 'required', 
    ]); 

    $credentials = $request->only('email', 'password'); 

    if ($this->auth->attempt($credentials, $request->has('remember'))) 
    { 
     return redirect()->intended($this->redirectPath()); 
    } 

    return redirect($this->loginPath()) 
       ->withInput($request->only('email', 'remember')) 
       ->withErrors([ 
        'email' => 'These credentials do not match our records.', 
       ]); 
} 

但我想的方法还要检查用户角色如下:

public function postLogin(Request $request) 
{ 
    $this->validate($request, [ 
     'email' => 'required|email', 'password' => 'required', 
    ]); 

    $credentials = $request->only('email', 'password'); 

    if ($this->auth->attempt($credentials, $request->has('remember'))) 
    { 
     if(Auth::user()->role->name == 'recruiter') 
     { 
      return redirect()->to('/recruiter/dashboard'); 
     } 
     elseif(Auth::user()->role->name == 'jobseeker') 
     { 
      return redirect()->to('jobseeker/dashboard'); 
     } 

    } 

    return redirect($this->loginPath()) 
       ->withInput($request->only('email', 'remember')) 
       ->withErrors([ 
        'email' => 'These credentials do not match our records.', 
       ]); 
} 

所以我的问题是如何你去定制现有的身份验证?你们是否会创建一个新的控制器,或许是CustomAuthController,CustomPasswordController,并将所有特征从默认的身份验证控制器复制到这些自定义控制器中并根据需要进行编辑?我无法找到有关如何实现这一目标的Laravel 5教程 - 它们都只是谈论默认的开箱即用身份验证。如果任何人做过类似的事情,我很想听听你是如何处理它的,以及哪些文件被编辑来连接这个自定义身份验证。

回答

0

你有两个选择:

  1. 覆盖在现有的身份验证控制器的方法。
  2. 根本不执行AuthenticatesAndRegistersUsers特征,并且完全自己实现验证逻辑。

至于重定向,我会听的auth.login事件,请检查您的用户的类型出现,然后重定向到特定的仪表盘那里,然后。

+0

感谢您的建议。关于重定向,你如何在auth.login事件中听取 - 抱歉,我是laravel的新手,一些示例代码会很有用。另外,如果我自己实现身份验证逻辑,我是否也必须调整'passwordController','Authenticate'和'RedirectIfAuthenticated'中间件? – adam78