我在登录时手动验证用户身份,这是我的完整登录功能
public function Login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
$email_host = explode('@', $credentials['email'])[1];
$company = Companies::where('email_host', $email_host)->first();
if ($company) {
try {
// Set up dynamic database configuration
Config::set("database.connections.$company->email_host", [
'driver' => $company['db_driver'],
'host' => $company['db_host'],
'port' => $company['db_port'],
'database' => $company['db_name'],
'username' => $company['db_user'],
'password' => $company['db_password'],
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
]);
Config::set("database.default", $company->email_host);
DB::purge();
DB::reconnect();
$user = User::where('email', $credentials['email'])->first();
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
$user = Auth::user();
session([
'username' => $user->username,
'company_id' => $user->company_id,
'warehouse' => $user->warehouse,
'company_database' => serialize($company),
]);
if ($user->role == 'basic') {
return redirect('/users/vaccations/set-vaccation');
}
return redirect()->intended('/');
}
} catch (\Exception $e) {
// Error occurred while configuring the database connection
return back()->withErrors([
'email' => 'Error occurred while configuring the database connection: ' . $e->getMessage(),
])->onlyInput('email');
}
} else {
// Company not found
return back()->withErrors([
'email' => 'The provided email does not belong to a valid company.',
])->onlyInput('email');
}
}
问题出在 Auth::attempt() 中。首先,我从主数据库中选择数据库凭据,然后切换数据库,然后登录用户,但身份验证似乎正在使用第一个(默认,主)数据库。我该如何解决?在环境中,我只有一个数据库凭据(master),其他数据库凭据存储在主数据库中,如上所述。
已解决,问题不在于Auth,而是在于中间件顺序,其中包括DatabaseConnectionMiddleware。