aboutsummaryrefslogtreecommitdiffhomepage
path: root/misc
diff options
context:
space:
mode:
Diffstat (limited to 'misc')
-rw-r--r--misc/get_remote_object_authenticated.php40
1 files changed, 40 insertions, 0 deletions
diff --git a/misc/get_remote_object_authenticated.php b/misc/get_remote_object_authenticated.php
new file mode 100644
index 0000000..ba67473
--- /dev/null
+++ b/misc/get_remote_object_authenticated.php
@@ -0,0 +1,40 @@
+<?php
+
+use Digitigrade\Model\Instance;
+
+/**
+ * Makes an HTTPS GET request to a remote instance, using the corresponding outbound auth token (if any)
+ * @param string $uri
+ * @param bool $dontLookUpInstance if true, will skip looking up the Instance, and consequently the auth token
+ * @return false|string the response data, or false if it failed
+ */
+function get_remote_object_authenticated(string $uri, bool $dontLookUpInstance = false) {
+ if (!str_starts_with($uri, 'https://'))
+ return false;
+
+ $instance = null;
+ if (!$dontLookUpInstance) {
+ $instance = Instance::findByDomain(explode('/', $uri)[2]);
+ }
+
+ if ($instance?->auth?->outboundToken == null) {
+ // hopefully we can make the request anyway?
+ $resp = file_get_contents($uri);
+ // $http_response_header just poofs into existence .
+ // i don't like this api. i should probably use curl instead. hmm
+ // TODO: use curl instead of file_get_contents
+ if (str_contains($http_response_header[0], '401') || str_contains($http_response_header[0], '403')) {
+ // we can't authenticate right now because it's asynchronous
+ // so i'm choosing to begin the auth process now and return false in the hopes that
+ // this request will be retried later
+ $instance?->beginOutboundAuth();
+ return false;
+ }
+ return $resp;
+ }
+
+ $context = stream_context_create(['http' => [
+ 'header' => 'Authorization: Bearer ' . $instance->auth->outboundToken
+ ]]);
+ return file_get_contents($uri, context: $context);
+} \ No newline at end of file