Php Auth::login未登录新创建的用户
我试图允许用户使用Twitch的OAuth流登录到我的网站。整个获取访问令牌和随后的用户数据的过程都是有效的,但我还想在数据库中存储一些用户数据,以便可以为某些人分配角色。成功获取用户数据后,我在Php Auth::login未登录新创建的用户,php,laravel,laravel-6,Php,Laravel,Laravel 6,我试图允许用户使用Twitch的OAuth流登录到我的网站。整个获取访问令牌和随后的用户数据的过程都是有效的,但我还想在数据库中存储一些用户数据,以便可以为某些人分配角色。成功获取用户数据后,我在HomeController public function redirect(Request $request): RedirectResponse { // fetch data $this->authService->authenticateUser($respons
HomeController
public function redirect(Request $request): RedirectResponse
{
// fetch data
$this->authService->authenticateUser($response, $this->userRepository);
return redirect()->route('index');
}
authenticateUser()
这两个存储库功能也非常简单
findByTwitchId()
create()
用户
型号
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
protected $guarded = [];
protected $keyType = 'string';
protected $primaryKey = 'twitch_id';
}
在authenticateUser
中,直到Auth::login($user)
为止的所有操作都有效。如果用户已经存在,则返回该用户,否则将创建一个新用户并返回该用户
但是,我似乎无法让Auth::login($user)
与新创建的用户一起工作。只有当用户第二次通过登录流时(即当用户已保存到数据库时),才能进行登录工作。更奇怪的是,当我在Auth::login()
下面添加dd(Auth::check())
时,它返回true,但当我随后在HomeController@index
(用户登录后重定向到的位置),返回false
老实说,我完全不明白为什么它不起作用。在这两种情况下,打印$user,用于new和exist。让我们在Auth::login($user)函数之前检查新用户中是否缺少某些内容
public function authenticateUser(array $response, UserRepositoryInterface $userRepository): void
{
$data = $response['content']->data[0];
$user = $userRepository->findByTwitchId($data->id);
if (!$user) {
$user = $userRepository->create($data);
}
Auth::login($user);
}
由于我已将
protected$primaryKey
设置为非增量值(twitch\u id
),因此我必须将public$incrementing=false
添加到我的用户
模型中,如后文所述。可能与我在用户
模型中设置的主键有关吗?我已将其设置为twitch_id
,因为这是我网站的相关id,而不是数据库id。当我转储新创建的用户时,不会返回普通id字段,当我转储已存在的用户时,会返回该字段。这可能是问题吗?啊,我只是注意到我以前错过了一些东西。转储新创建的用户时,数组中的twitch\u id
值被设置为数据库id,而不是实际的twitch\u id,因此这就是出错的地方。
public function create($data): User
{
return User::create([
'twitch_id' => $data->id,
'login_name' => $data->login,
'display_name' => $data->display_name,
'email' => $data->email,
'profile_image' => $data->profile_image_url
]);
}
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
protected $guarded = [];
protected $keyType = 'string';
protected $primaryKey = 'twitch_id';
}
public function authenticateUser(array $response, UserRepositoryInterface $userRepository): void
{
$data = $response['content']->data[0];
$user = $userRepository->findByTwitchId($data->id);
if (!$user) {
$user = $userRepository->create($data);
}
Auth::login($user);
}