我的Laravel auth模块有问题。
我正在将旧工具重写为laravel,但必须保留旧的系统数据库结构。
系统使用多个DB(按部门分隔)并识别url应使用哪个DB,例如。
www.example.com/foo //use foo DB for foo department
www.example.com/bar //use bar DB for bar department
Foo和Bar DB有自己的用户表。两个DB中都存在一些帐户,但ID不同,用户名相同。例如:
//foo DB users table
ID username
1 xyz
2 abc
//bar DB users table
ID username
1 qwe
2 xyz
假设我使用foo deparment(和DB)作为用户xyz(id 1)登录系统。
我现在转到酒吧部门(和酒吧DB)。
因此,我以用户qwe的身份登录到bar部门(和DB),因为系统继续使用我登录到系统的id(1)。
如何更改该行为并强制系统使用username而不是id作为在DB之间区分用户的密钥?
我知道我可以在用户模型中使用用户名作为主键,但我必须更改与用户模型相关的所有关系以及Auth :: id()等其他内容。
有没有更简单的方法?
答案 0 :(得分:0)
Auth guards以这种方式引用用户ID字段:$user->getAuthIdentifier())
因此,您可以在用户模型中执行此操作:
class User extends Model {
...
public function getAuthIdentifier() {
return $this->username;
}
}
如果您害怕Auth :: id()更改,请查看它的会话保护实现:
public function id()
{
if ($this->user()) {
return $this->user()->getAuthIdentifier();
}
}
<强>更新强>
但是,解决任何自定义授权问题的最佳方法是使用您自己的用户提供程序和auth guard。
这可能听起来很困难,但它实现两个接口一样容易。在此处查看官方文档here和here。举个例子,你可以使用vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php
(顺便看看它的辅助特征GuardHelpers
)和vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php