Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions ProcessMaker/Mail/MicrosoftGraphTokenProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace ProcessMaker\Mail;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use RuntimeException;

class MicrosoftGraphTokenProvider
{
private const TOKEN_URL = 'https://login.microsoftonline.com/%s/oauth2/v2.0/token';

private const DEFAULT_SCOPE = 'https://graph.microsoft.com/.default';

public function __construct(
private array $config,
private int|string $serverIndex = 0,
private ?Client $httpClient = null,
) {
}

public function getAccessToken(): string
{
$cacheKey = 'microsoft_graph_access_token_' . ($this->serverIndex ?: 'default');

return Cache::remember($cacheKey, now()->addMinutes(50), function () {
return $this->requestAccessToken();
});
}

private function requestAccessToken(): string
{
$tenantId = $this->config['tenant_id'] ?? null;
$clientId = $this->config['key'] ?? null;
$clientSecret = $this->config['secret'] ?? null;

if (!$tenantId || !$clientId || !$clientSecret) {
throw new RuntimeException('Microsoft Graph credentials are not configured.');
}

$client = $this->httpClient ?? new Client();
$response = $client->post(sprintf(self::TOKEN_URL, $tenantId), [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'scope' => self::DEFAULT_SCOPE,
'grant_type' => 'client_credentials',
],
'http_errors' => false,
]);

$body = json_decode($response->getBody()->getContents(), true);

if ($response->getStatusCode() >= 400) {
$message = $body['error_description'] ?? $body['error']['message'] ?? 'Unknown error';

throw new RuntimeException('Failed to get Microsoft Graph access token: ' . $message);
}

return $body['access_token'];
}
}
65 changes: 65 additions & 0 deletions tests/unit/ProcessMaker/Mail/MicrosoftGraphTokenProviderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace Tests\Unit\ProcessMaker\Mail;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Facades\Cache;
use Mockery;
use ProcessMaker\Mail\MicrosoftGraphTokenProvider;
use RuntimeException;
use Tests\TestCase;

class MicrosoftGraphTokenProviderTest extends TestCase
{
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}

public function testGetAccessTokenThrowsWhenCredentialsAreMissing()
{
$provider = new MicrosoftGraphTokenProvider([
'tenant_id' => '',
'key' => 'client-id',
'secret' => 'client-secret',
]);

$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Microsoft Graph credentials are not configured.');

$provider->getAccessToken();
}

public function testGetAccessTokenRequestsTokenFromMicrosoft()
{
Cache::flush();

$tokenResponse = new Response(200, [], json_encode(['access_token' => 'token-from-azure']));

$guzzle = Mockery::mock(Client::class);
$guzzle->shouldReceive('post')
->once()
->with(
'https://login.microsoftonline.com/tenant-id-123/oauth2/v2.0/token',
Mockery::on(function ($options) {
return $options['form_params']['client_id'] === 'client-id-123'
&& $options['form_params']['client_secret'] === 'client-secret-123'
&& $options['form_params']['scope'] === 'https://graph.microsoft.com/.default'
&& $options['form_params']['grant_type'] === 'client_credentials'
&& $options['http_errors'] === false;
})
)
->andReturn($tokenResponse);

$provider = new MicrosoftGraphTokenProvider([
'tenant_id' => 'tenant-id-123',
'key' => 'client-id-123',
'secret' => 'client-secret-123',
], 1, $guzzle);

$this->assertSame('token-from-azure', $provider->getAccessToken());
$this->assertSame('token-from-azure', $provider->getAccessToken());
}
}
Loading