我在Laravel 5.3中使用委托来管理基于角色的权限,并且自然地使用手动/自定义登录不同的用户类型。Auth::attempt()
是否可以处理外表关系?基本上,我想这样做:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
但我一直得到错误,hasRole()
是一个未定义的函数。我已经包括了use ZizacoEntrustTraitsEntrustUserTrait;
和use EntrustUserTrait;
,我认为这将为我提供访问功能,但显然不是。
我欣赏hasRole()
是用户对象的方法这一事实,在检查的时候,我没有用户对象,但我不能在尝试成功后做角色检查,因为那时用户已经登录了,如果角色是错误的,我需要注销他们,因为他们的凭据是正确的,但不是角色;这看起来既缓慢又不务实。
我该如何处理这个问题?是否有Auth::attempt
的替代方案,我可以使用,将不登录用户,但检查用户存在与指定的输入,然后运行角色检查,然后使用另一个功能来启动一个身份验证的会话?
如果有用,我的LoginController在这里:
<?php
namespace AppHttpControllersTeacher;
use AppHttpControllersController;
use IlluminateSupportFacadesAuth;
use IlluminateHttpRequest;
use Validator;
use ZizacoEntrustTraitsEntrustUserTrait;
class LoginController extends Controller {
use EntrustUserTrait;
public function showLoginForm() {
return view('teacher/login');
}
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
return redirect('admin/login')->with('invalid', 'Invalid username or password');
}
}
任何帮助或指导将不胜感激。谢谢。
你可以做的是:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password)) {
if($user = Auth::user()->hasRole('teacher')) {
return redirect()->intended('teacher/dashboard');
} else {
return redirect()->intended('teacher/dashboard');
}
}
这就是我在login check role
上所做的$user = User::whereEmail($request->email)->first();
// I added this is because the customer
// are not suppose to login from here
if(!$user || $user->hasRole(['customer'])){
return $this->sendFailedLoginResponse($request);
}
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
如果你想根据用户角色改变路由你可以尝试用
替换redirectPath方法public function redirectPath()
{
$user = Auth::user();
if($user->hasRole(['admin', 'system_admin']))
return '/backend';
elseif($user->hasRole(['teacher']))
return '/teacher';
}
我最终手动执行身份验证检查并使用Auth::login($user)
创建经过身份验证的会话。通过这种方式,用户只有在满足特定登录门户和控制器的角色需求时才会登录。
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
$user = User::where('email', $request->email)->first();
if($user) {
if(Hash::check($request->password, $user->password) && $user->hasRole('teacher')) {
Auth::login($user);
return redirect()->intended('teacher/dashboard');
}
}
return redirect('teacher/login')->with('invalid', 'Invalid username or password');
}