Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
namespace Aws\Rds;
3
 
4
use Aws\Credentials\CredentialsInterface;
5
use Aws\Credentials\Credentials;
6
use Aws\Signature\SignatureV4;
7
use GuzzleHttp\Psr7\Request;
8
use GuzzleHttp\Psr7\Uri;
9
use GuzzleHttp\Promise;
10
use Aws;
11
 
12
/**
13
 * Generates RDS auth tokens for use with IAM authentication.
14
 */
15
class AuthTokenGenerator
16
{
17
 
18
    private $credentialProvider;
19
 
20
    /**
21
     * The constructor takes an instance of Credentials or a CredentialProvider
22
     *
23
     * @param callable|Credentials $creds
24
     */
25
    public function __construct($creds)
26
    {
27
        if ($creds instanceof CredentialsInterface) {
28
            $promise = new Promise\FulfilledPromise($creds);
29
            $this->credentialProvider = Aws\constantly($promise);
30
        } else {
31
            $this->credentialProvider = $creds;
32
        }
33
    }
34
 
35
    /**
36
     * Create the token for database login
37
     *
38
     * @param string $endpoint The database hostname with port number specified
39
     *                         (e.g., host:port)
40
     * @param string $region The region where the database is located
41
     * @param string $username The username to login as
42
     * @param int $lifetime The lifetime of the token in minutes
43
     *
44
     * @return string Token generated
45
     */
46
    public function createToken($endpoint, $region, $username, $lifetime = 15)
47
    {
48
        if (!is_numeric($lifetime) || $lifetime > 15 || $lifetime <= 0) {
49
            throw new \InvalidArgumentException(
50
                "Lifetime must be a positive number less than or equal to 15, was {$lifetime}",
51
                null
52
            );
53
        }
54
 
55
        $uri = new Uri($endpoint);
56
        $uri = $uri->withPath('/');
57
        $uri = $uri->withQuery('Action=connect&DBUser=' . $username);
58
 
59
        $request = new Request('GET', $uri);
60
        $signer = new SignatureV4('rds-db', $region);
61
        $provider = $this->credentialProvider;
62
 
63
        $url = (string) $signer->presign(
64
            $request,
65
            $provider()->wait(),
66
            '+' . $lifetime . ' minutes'
67
        )->getUri();
68
 
69
        // Remove 2 extra slash from the presigned url result
70
        return substr($url, 2);
71
    }
72
}