diff --git a/src/GoogleStorageAdapter.php b/src/GoogleStorageAdapter.php index 26b9460..5d651b3 100644 --- a/src/GoogleStorageAdapter.php +++ b/src/GoogleStorageAdapter.php @@ -27,6 +27,11 @@ class GoogleStorageAdapter extends AbstractAdapter */ protected $bucket; + /** + * @var array + */ + protected $auth = []; + /** * @var string */ @@ -38,7 +43,7 @@ class GoogleStorageAdapter extends AbstractAdapter * @param string $pathPrefix * @param string $storageApiUri */ - public function __construct(StorageClient $storageClient, Bucket $bucket, $pathPrefix = null, $storageApiUri = null) + public function __construct(StorageClient $storageClient, Bucket $bucket, $pathPrefix = null, $storageApiUri = null, $key_file_path = '') { $this->storageClient = $storageClient; $this->bucket = $bucket; @@ -50,6 +55,12 @@ public function __construct(StorageClient $storageClient, Bucket $bucket, $pathP if ($storageApiUri) { $this->storageApiUri = $storageApiUri; } + + if (is_file($key_file_path)) { + if ($data = json_decode(file_get_contents($key_file_path), True)) { + $this->auth = $data; + } + } } /** @@ -380,6 +391,45 @@ public function getUrl($path) return $uri . '/' . $this->bucket->name() . '/' . $path; } + /** + * Return a signed url to a file with expiration timestamp. + * + * @param string $path + * @param integer $expires + * @param string $method + * @return string + */ + public function getSignedUrl($path, $expires = 0, $method = 'GET') + { + if (!empty($this->auth)) { + $signature = ''; + $canonical_resource = '/' . $this->bucket->name() . '/' . $path; // e.g.: /bucket/somefile.txt + + $to_sign = [ + $method, + '', + '', + $expires, + $canonical_resource + ]; + + $to_sign_string = implode("\n", $to_sign); + + // sign $to_sign_string as $signature with private_key from provided + openssl_sign($to_sign_string, $signature, $this->auth['private_key'], 'sha256'); + + $signature = urlencode(base64_encode($signature)); + + return $this->getStorageApiUri() + . $canonical_resource + . "?GoogleAccessId=" . urlencode($this->auth['client_email']) + . "&Expires=" . $expires + . "&Signature=" . $signature; + } + + return $this->getUrl($path); + } + /** * @param string $path * @return string