【问题标题】:Laravel 5 customizing authenticationLaravel 5 自定义身份验证
【发布时间】:2015-06-07 14:12:11
【问题描述】:

在 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 教程——它们都只是谈论默认的开箱即用身份验证。如果有人在我之前做过类似的事情,我很想听听你是怎么做的,以及编辑了哪些文件来连接这个自定义身份验证。

【问题讨论】:

    标签: authentication laravel-5 customization


    【解决方案1】:

    你有几个选择:

    1. 覆盖现有身份验证控制器中的方法。
    2. 根本不实现AuthenticatesAndRegistersUsers trait,完全自己实现身份验证逻辑。

    关于重定向,我会监听 auth.login 事件,在那里检查您的用户类型,然后在那里重定向到特定的仪表板。

    【讨论】:

    • 感谢您的建议。关于重定向,您如何收听 auth.login 事件 - 对不起,但我是 laravel 的新手,一些示例代码会很有用。另外,如果我自己实现身份验证逻辑,是否还需要调整passwordControllerAuthenticateRedirectIfAuthenticated 中间件?
    猜你喜欢
    • 2015-08-02
    • 2017-02-20
    • 2015-02-23
    • 2015-07-01
    • 2014-11-15
    • 2014-03-30
    • 2016-04-18
    • 1970-01-01
    相关资源
    最近更新 更多