You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.8 KiB
PHP
63 lines
1.8 KiB
PHP
<?php
|
|
|
|
|
|
namespace Gitlab\Api\Plugin;
|
|
|
|
|
|
use Http\Client\Common\Plugin;
|
|
use Http\Promise\Promise;
|
|
use Psr\Http\Message\RequestInterface;
|
|
|
|
class Authentication implements Plugin
|
|
{
|
|
public const TOKEN = 'token';
|
|
public const OAUTH = 'oauth';
|
|
|
|
private $method;
|
|
private $token;
|
|
private $sudo;
|
|
|
|
public function __construct(
|
|
string $method,
|
|
string $token,
|
|
bool $sudo = false
|
|
)
|
|
{
|
|
if ($method !== self::TOKEN && $method !== self::OAUTH) {
|
|
throw new \InvalidArgumentException('Method must be either TOKEN or OAUTH');
|
|
}
|
|
|
|
$this->method = $method;
|
|
$this->token = $token;
|
|
$this->sudo = $sudo;
|
|
}
|
|
|
|
/**
|
|
* Handle the request and return the response coming from the next callable.
|
|
*
|
|
* @see http://docs.php-http.org/en/latest/plugins/build-your-own.html
|
|
*
|
|
* @param RequestInterface $request
|
|
* @param callable $next Next middleware in the chain, the request is passed as the first argument
|
|
* @param callable $first First middleware in the chain, used to to restart a request
|
|
*
|
|
* @return Promise Resolves a PSR-7 Response or fails with an Http\Client\Exception (The same as HttpAsyncClient).
|
|
*/
|
|
public function handleRequest(RequestInterface $request, callable $next, callable $first)
|
|
{
|
|
if ($this->sudo === true) {
|
|
$request = $request->withAddedHeader('Sudo', 'yes');
|
|
}
|
|
|
|
switch ($this->method) {
|
|
case self::TOKEN:
|
|
$request = $request->withAddedHeader('Private-Token', $this->token);
|
|
break;
|
|
case self::OAUTH:
|
|
$request = $request->withAddedHeader('Authorization', 'Bearer ' . $this->token);
|
|
break;
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
} |