Skip to content

Commit

Permalink
Refactored refreshToken trait to not require the use of sessions to p…
Browse files Browse the repository at this point in the history
…ull user, now accepts an optional parameter of $user
  • Loading branch information
Paul Brennan committed Nov 15, 2024
1 parent 0c3e36f commit 091ad81
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/Auth/RefreshToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

use Exception;
use Illuminate\Validation\ValidationException;
use Ellaisys\Cognito\Exceptions\AwsCognitoException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Aws\CognitoIdentityProvider\Exception\CognitoIdentityProviderException;

Expand Down Expand Up @@ -56,9 +55,10 @@ public function __construct(AwsCognito $cognito) {
*
* @return mixed
*/
public function refresh(Request $request, string $paramUsername='email', string $paramRefreshToken='refresh_token')
public function refresh(Request $request, string $paramUsername='email', string $paramRefreshToken='refresh_token', string $authGuard = 'api', mixed $user = null)
{
try {
$userSubId = null;

if ($request instanceof Request) {
//Validate request
Expand All @@ -74,24 +74,32 @@ public function refresh(Request $request, string $paramUsername='email', string
//Create AWS Cognito Client
$client = app()->make(AwsCognitoClient::class);

//Get Authenticated user
$authUser = Auth::guard('api')->user();
if($user === null) {
//Get Authenticated user
$authUser = Auth::guard($authGuard)->user();

//Get User Data
$user = $client->getUser($authUser[$paramUsername]);
//Get User Data
if($user = $client->getUser($authUser[$paramUsername])) {
$userSubId = $user['Username'];
}
} else {
$userSubId = $user?->{config('cognito.user_subject_uuid')};
}

//Use username from AWS to refresh token, not email from login!
if (!empty($user['Username'])) {
$response = $client->refreshToken($user['Username'], $request[$paramRefreshToken]);
if (!empty($userSubId)) {
$response = $client->refreshToken($userSubId, $request[$paramRefreshToken]);
if (empty($response) || empty($response['AuthenticationResult'])) {
throw new HttpException(400);
} //End if

//Authenticate User
$claim = new AwsCognitoClaim($response, $authUser, 'email');
$claim = new AwsCognitoClaim($response, $authUser ?? $user, 'email');
if ($claim && $claim instanceof AwsCognitoClaim) {
//Store the token
$this->cognito->setClaim($claim)->storeToken();
//Revoke old refresh token
$client->revokeToken($request[$paramRefreshToken]);

//Return the response object
return $claim->getData();
Expand Down

0 comments on commit 091ad81

Please sign in to comment.