Skip to content

Commit

Permalink
refactor: Quita ServiceProvider y ClaveUnicaGetUser. Mejora de except…
Browse files Browse the repository at this point in the history
…ions
  • Loading branch information
Jose Rodriguez committed Aug 29, 2022
1 parent 372d759 commit ebba8df
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 73 deletions.
25 changes: 16 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,14 @@ ClaveÚnica mediante [josecl/emulador-claveunica](https://github.com/josecl/emul

## Instalación y configuración

Se utiliza de manera similar a los provider de [Socialite](https://socialiteproviders.com/).

Instalar dependencia:

```shell
composer require josecl/claveunica
```


### Configuración

Se utiliza de manera similar a los provider de [Socialite](https://socialiteproviders.com/).
El evento `SocialiteWasCalled` ya viene configurado, por lo que no es necesario
realizar dicho paso.

Agregar configuración al archivo `config/services.php`:

```php
Expand All @@ -38,8 +33,20 @@ Agregar configuración al archivo `config/services.php`:
],
```

### Uso
Agregar *event listener* para los eventos `SocialiteWasCalled` en tu archivo
`app/Providers/EventServiceProvider.php`:

```php
protected $listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
// ...
\Josecl\ClaveUnica\ClaveUnicaExtendSocialite::class . '@handle',
],
];
```


### Uso

Para redireccianar al servicio OAuth usar un contoller que haga redirect con:

Expand All @@ -55,7 +62,7 @@ de sesión en tu aplicación. Puedes obtener los datos del usuario autenticado
mediante este ejemplo:

```php
$claveUnicaUser = app(ClaveUnicaGetUser::class)->user();
$claveUnicaUser = Socialite::driver('claveunica')->user();

dump($claveUnicaUser->run);
dump($claveUnicaUser->dv);
Expand Down
4 changes: 1 addition & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@
},
"extra": {
"laravel": {
"providers": [
"Josecl\\ClaveUnica\\ClaveUnicaServiceProvider"
],
"providers": [],
"aliases": []
}
},
Expand Down
24 changes: 0 additions & 24 deletions src/ClaveUnicaGetUser.php

This file was deleted.

48 changes: 29 additions & 19 deletions src/ClaveUnicaProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Josecl\ClaveUnica;

use Exception;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;

Expand All @@ -30,30 +31,39 @@ protected function getTokenUrl(): string
return config('services.claveunica.token_uri');
}

/**
* @throws ClaveUnicaException
*/
protected function getUserByToken($token): array
{
$response = $this->getHttpClient()->post(config('services.claveunica.user_uri'), [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);

if ($response->getStatusCode() >= 400) {
throw new ClaveUnicaException('Request de user a ' . config('services.claveunica.user_uri') . ' con HTTP status ' . $response->getStatusCode());
}
$url = config('services.claveunica.user_uri');

try {
$response = $this->getHttpClient()->post($url, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);

return json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
return json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
} catch (Exception $exception) {
throw new ClaveUnicaException('ClaveÚnica getUserByToken fallido: ' . $exception->getMessage(), previous: $exception);
}
}

protected function mapUserToObject(array $user)
protected function mapUserToObject(array $user): User
{
return (new User())->setRaw($user)->map([
'id' => $user['RolUnico']['numero'],
'name' => $user['name'],
'first_name' => implode(' ', $user['name']['nombres']),
'last_name' => implode(' ', $user['name']['apellidos']),
'run' => $user['RolUnico']['numero'],
'dv' => $user['RolUnico']['DV'],
]);
try {
return (new User())->setRaw($user)->map([
'id' => $user['RolUnico']['numero'],
'name' => $user['name'],
'first_name' => implode(' ', $user['name']['nombres']),
'last_name' => implode(' ', $user['name']['apellidos']),
'run' => $user['RolUnico']['numero'],
'dv' => $user['RolUnico']['DV'],
]);
} catch (Exception $exception) {
throw new ClaveUnicaException('ClaveÚnica datos de User inválidos: ' . $exception->getMessage(), previous: $exception);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace Josecl\ClaveUnica;
namespace Josecl\ClaveUnica\Tests;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

Expand Down
37 changes: 21 additions & 16 deletions tests/ClaveUnicaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Psr7\Response as GuzzleHttpResponse;
use Josecl\ClaveUnica\ClaveUnicaException;
use Josecl\ClaveUnica\ClaveUnicaGetUser;
use Laravel\Socialite\Facades\Socialite;

beforeEach(function () {
Expand All @@ -15,6 +14,7 @@




test('redirect', function () {
$redirect = Socialite::driver('claveunica')->stateless()->redirect();

Expand All @@ -26,6 +26,7 @@




test('user', function () {
$user = [
'RolUnico' => [
Expand Down Expand Up @@ -54,9 +55,7 @@
body: json_encode($user, JSON_THROW_ON_ERROR)
));

Socialite::driver('claveunica')->stateless();

$claveUnicaUser = app(ClaveUnicaGetUser::class)->user();
$claveUnicaUser = Socialite::driver('claveunica')->stateless()->user();

expect($claveUnicaUser)
->user->toBe($user)
Expand All @@ -68,7 +67,10 @@
;
});

test('user failed', function () {



test('user throws ClaveUnicaException', function (mixed $responseBody) {
Mockery::mock('overload:' . GuzzleHttpClient::class)
->shouldReceive('post')
->withSomeOfArgs(config('services.claveunica.token_uri'))
Expand All @@ -81,14 +83,17 @@
))
->shouldReceive('post')
->withSomeOfArgs(config('services.claveunica.user_uri'))
->andReturn(new GuzzleHttpResponse(
401
))
;

Socialite::driver('claveunica')->stateless();

test()->expectException(ClaveUnicaException::class);

app(ClaveUnicaGetUser::class)->user();
});
->andReturn(new GuzzleHttpResponse(body: $responseBody));

$exception = rescue(
fn () => Socialite::driver('claveunica')->stateless()->user(),
rescue: fn ($exception) => $exception,
);

expect($exception)
->toBeInstanceOf(ClaveUnicaException::class);
})->with([
[''],
['{}'],
['::json-malformed::'],
]);
1 change: 0 additions & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Josecl\ClaveUnica\Tests;

use Josecl\ClaveUnica\ClaveUnicaServiceProvider;
use SocialiteProviders\Manager\ServiceProvider;

abstract class TestCase extends \Orchestra\Testbench\TestCase
Expand Down

0 comments on commit ebba8df

Please sign in to comment.