Repository navigation
Expand file tree
/
Copy pathAuthentication.php
More file actions
102 lines (88 loc) · 2.51 KB
/
Copy pathAuthentication.php
File metadata and controls
102 lines (88 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
declare(strict_types=1);
/*
* This file is part of the Gitlab API library.
*
* (c) Matt Humphrey <matth@windsor-telecom.co.uk>
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Gitlab\HttpClient\Plugin;
use Gitlab\Client;
use Gitlab\Exception\RuntimeException;
use Http\Client\Common\Plugin;
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;
/**
* Add authentication to the request.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
* @author Fabien Bourigault <bourigaultfabien@gmail.com>
*
* @internal
*/
final class Authentication implements Plugin
{
/**
* @var array<string,string>
*/
private $headers;
/**
* @param string $method
* @param string $token
* @param string|null $sudo
*
* @return void
*/
public function __construct(string $method, string $token, string $sudo = null)
{
$this->headers = self::buildHeaders($method, $token, $sudo);
}
/**
* Handle the request and return the response coming from the next callable.
*
* @param RequestInterface $request
* @param callable $next
* @param callable $first
*
* @return Promise
*/
public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
{
foreach ($this->headers as $header => $value) {
$request = $request->withHeader($header, $value);
}
return $next($request);
}
/**
* Build the headers to be attached to the request.
*
* @param string $method
* @param string $token
* @param string|null $sudo
*
* @throws RuntimeException
*
* @return array<string,string>
*/
private static function buildHeaders(string $method, string $token, string $sudo = null): array
{
$headers = [];
switch ($method) {
case Client::AUTH_HTTP_TOKEN:
$headers['PRIVATE-TOKEN'] = $token;
break;
case Client::AUTH_OAUTH_TOKEN:
$headers['Authorization'] = \sprintf('Bearer %s', $token);
break;
default:
throw new RuntimeException(\sprintf('Authentication method "%s" not implemented.', $method));
}
if (null !== $sudo) {
$headers['SUDO'] = $sudo;
}
return $headers;
}
}