Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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
    private $credentialProvider;
18
 
19
    /**
20
     * The constructor takes an instance of Credentials or a CredentialProvider
21
     *
22
     * @param callable|Credentials $creds
23
     */
24
    public function __construct($creds)
25
    {
26
        if ($creds instanceof CredentialsInterface) {
27
            $promise = new Promise\FulfilledPromise($creds);
28
            $this->credentialProvider = Aws\constantly($promise);
29
        } else {
30
            $this->credentialProvider = $creds;
31
        }
32
    }
33
 
34
    /**
35
     * Create the token for database login
36
     *
37
     * @param string $endpoint The database hostname with port number specified
38
     *                         (e.g., host:port)
39
     * @param string $region The region where the database is located
40
     * @param string $username The username to login as
41
     * @param int $lifetime The lifetime of the token in minutes
42
     *
43
     * @return string Token generated
44
     */
45
    public function createToken($endpoint, $region, $username, $lifetime = 15)
46
    {
47
        if (!is_numeric($lifetime) || $lifetime > 15 || $lifetime <= 0) {
48
            throw new \InvalidArgumentException(
1441 ariadna 49
                "Lifetime must be a positive number less than or equal to 15, was {$lifetime}"
1 efrain 50
            );
51
        }
52
 
53
        $uri = new Uri($endpoint);
54
        $uri = $uri->withPath('/');
55
        $uri = $uri->withQuery('Action=connect&DBUser=' . $username);
56
 
57
        $request = new Request('GET', $uri);
58
        $signer = new SignatureV4('rds-db', $region);
59
        $provider = $this->credentialProvider;
60
 
61
        $url = (string) $signer->presign(
62
            $request,
63
            $provider()->wait(),
64
            '+' . $lifetime . ' minutes'
65
        )->getUri();
66
 
67
        // Remove 2 extra slash from the presigned url result
68
        return substr($url, 2);
69
    }
70
}