/
Authentication.php
87 lines (69 loc) · 2.54 KB
/
Authentication.php
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
<?php
namespace Github\HttpClient\Plugin;
use Github\Client;
use Github\Exception\RuntimeException;
use Http\Client\Common\Plugin;
use Psr\Http\Message\RequestInterface;
/**
* Add authentication to the request.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class Authentication implements Plugin
{
use Plugin\VersionBridgePlugin;
private $tokenOrLogin;
private $password;
private $method;
public function __construct($tokenOrLogin, $password, $method)
{
$this->tokenOrLogin = $tokenOrLogin;
$this->password = $password;
$this->method = $method;
}
/**
* {@inheritdoc}
*/
public function doHandleRequest(RequestInterface $request, callable $next, callable $first)
{
switch ($this->method) {
case Client::AUTH_HTTP_PASSWORD:
$request = $request->withHeader(
'Authorization',
sprintf('Basic %s', base64_encode($this->tokenOrLogin.':'.$this->password))
);
break;
case Client::AUTH_HTTP_TOKEN:
$request = $request->withHeader('Authorization', sprintf('token %s', $this->tokenOrLogin));
break;
case Client::AUTH_URL_CLIENT_ID:
$uri = $request->getUri();
$query = $uri->getQuery();
$parameters = [
'client_id' => $this->tokenOrLogin,
'client_secret' => $this->password,
];
$query .= empty($query) ? '' : '&';
$query .= utf8_encode(http_build_query($parameters, '', '&'));
$uri = $uri->withQuery($query);
$request = $request->withUri($uri);
break;
case Client::AUTH_URL_TOKEN:
$uri = $request->getUri();
$query = $uri->getQuery();
$parameters = ['access_token' => $this->tokenOrLogin];
$query .= empty($query) ? '' : '&';
$query .= utf8_encode(http_build_query($parameters, '', '&'));
$uri = $uri->withQuery($query);
$request = $request->withUri($uri);
break;
case Client::AUTH_JWT:
$request = $request->withHeader('Authorization', sprintf('Bearer %s', $this->tokenOrLogin));
break;
default:
throw new RuntimeException(sprintf('%s not yet implemented', $this->method));
break;
}
return $next($request);
}
}