Add provider info to the session data for OAuth2 token auth

This commit is contained in:
Aditya Oberai
2025-10-22 22:21:56 +00:00
parent 72c608bf3b
commit 255c0ac866
+41 -12
View File
@@ -201,19 +201,48 @@ $createSession = function (string $userId, string $secret, Request $request, Res
default => throw new Exception(Exception::USER_INVALID_TOKEN)
});
$sessionData = [
'$id' => ID::unique(),
'userId' => $user->getId(),
'userInternalId' => $user->getSequence(),
'provider' => Auth::getSessionProviderByTokenType($verifiedToken->getAttribute('type')),
'secret' => Auth::hash($sessionSecret), // One way hash encryption to protect DB leak
'userAgent' => $request->getUserAgent('UNKNOWN'),
'ip' => $request->getIP(),
'factors' => [$factor],
'countryCode' => ($record) ? \strtolower($record['country']['iso_code']) : '--',
'expire' => DateTime::addSeconds(new \DateTime(), $duration)
];
// For OAuth2 tokens, retrieve and add provider tokens from identity
if ($verifiedToken->getAttribute('type') === Auth::TOKEN_TYPE_OAUTH2) {
// Find the most recently updated identity for this user with an access token
// This will be the identity that was just used in the OAuth2 flow
$identities = $dbForProject->find('identities', [
Query::equal('userInternalId', [$user->getSequence()]),
Query::orderDesc('$updatedAt'),
Query::limit(100)
]);
// Find the first identity with a non-empty access token
$latestIdentity = null;
foreach ($identities as $identity) {
if (!empty($identity->getAttribute('providerAccessToken'))) {
$latestIdentity = $identity;
break;
}
}
if ($latestIdentity && !$latestIdentity->isEmpty()) {
$sessionData['providerUid'] = $latestIdentity->getAttribute('providerUid', '');
$sessionData['providerAccessToken'] = $latestIdentity->getAttribute('providerAccessToken', '');
$sessionData['providerRefreshToken'] = $latestIdentity->getAttribute('providerRefreshToken', '');
$sessionData['providerAccessTokenExpiry'] = $latestIdentity->getAttribute('providerAccessTokenExpiry', '');
}
}
$session = new Document(array_merge(
[
'$id' => ID::unique(),
'userId' => $user->getId(),
'userInternalId' => $user->getSequence(),
'provider' => Auth::getSessionProviderByTokenType($verifiedToken->getAttribute('type')),
'secret' => Auth::hash($sessionSecret), // One way hash encryption to protect DB leak
'userAgent' => $request->getUserAgent('UNKNOWN'),
'ip' => $request->getIP(),
'factors' => [$factor],
'countryCode' => ($record) ? \strtolower($record['country']['iso_code']) : '--',
'expire' => DateTime::addSeconds(new \DateTime(), $duration)
],
$sessionData,
$detector->getOS(),
$detector->getClient(),
$detector->getDevice()