浏览代码

Use configured auth value in response calls

shalvah 5 年之前
父节点
当前提交
e76fea3662

+ 4 - 4
config/scribe.php

@@ -52,14 +52,14 @@ return [
 
         /*
          * The value of the parameter. This will NOT be part of the generated documentation.
-         * Use it to easily auth response calls by this package.
+         * Use it to easily auth response calls by this package. Otherwise, we'll use a random value.
          */
-        'value' => env('SCRIBE_API_KEY'),
+        'use_value' => env('SCRIBE_API_KEY'),
 
         /*
-         * Short text describing to your users where to find (or generate) their auth key.
+         * Any extra info for your users. For instance, you can describe where to find (or generate) their auth credentials.
          */
-        'how_to_fetch' => 'You can retrieve your token by visiting your dashboard and clicking <b>Generate API token</b>.',
+        'extra_info' => 'You can retrieve your token by visiting your dashboard and clicking <b>Generate API token</b>.',
     ],
 
     /*

+ 8 - 8
src/Extracting/Generator.php

@@ -260,6 +260,7 @@ class Generator
 
     public function addAuthField(array $parsedRoute)
     {
+        $parsedRoute['auth'] = null;
         $isApiAuthed = $this->config->get('auth.enabled', false);
         if (!$isApiAuthed || !$parsedRoute['metadata']['authenticated']) {
             return $parsedRoute;
@@ -273,8 +274,11 @@ class Generator
             $faker->seed($this->config->get('faker_seed'));
         }
         $token = $faker->shuffle('abcdefghkvaZVDPE1864563');
+        $valueToUse = $this->config->get('auth.use_value');
         switch ($strategy) {
             case 'query':
+            case 'query_or_body':
+                $parsedRoute['auth'] = "cleanQueryParameters.$parameterName.".($valueToUse ?: $token);
                 $parsedRoute['queryParameters'][$parameterName] = [
                     'name' => $parameterName,
                     'value' => $token,
@@ -283,6 +287,7 @@ class Generator
                 ];
                 break;
             case 'body':
+                $parsedRoute['auth'] = "cleanBodyParameters.$parameterName.".($valueToUse ?: $token);
                 $parsedRoute['bodyParameters'][$parameterName] = [
                     'name' => $parameterName,
                     'type' => 'string',
@@ -291,21 +296,16 @@ class Generator
                     'required' => true,
                 ];
                 break;
-            case 'query_or_body':
-                $parsedRoute['queryParameters'][$parameterName] = [ // Keep things simple; put only in query
-                    'name' => $parameterName,
-                    'value' => $token,
-                    'description' => '',
-                    'required' => true,
-                ];
-                break;
             case 'bearer':
+                $parsedRoute['auth'] = "headers.Authorization.".($valueToUse ? "Bearer $valueToUse" : "Bearer $token");
                 $parsedRoute['headers']['Authorization'] = "Bearer $token";
                 break;
             case 'basic':
+                $parsedRoute['auth'] = "headers.Authorization.".($valueToUse ? "Basic $valueToUse" : "Basic $token");
                 $parsedRoute['headers']['Authorization'] = "Basic ".base64_encode($token);
                 break;
             case 'header':
+                $parsedRoute['auth'] = "headers.$parameterName.".($valueToUse ?: $token);
                 $parsedRoute['headers'][$parameterName] = $token;
                 break;
         }

+ 19 - 0
src/Extracting/Strategies/Responses/ResponseCalls.php

@@ -52,6 +52,7 @@ class ResponseCalls extends Strategy
         $this->configureEnvironment($rulesToApply);
 
         // Mix in parsed parameters with manually specified parameters.
+        $context = $this->setAuthFieldProperly($context, $context['auth'] ?? null);
         $bodyParameters = array_merge($context['cleanBodyParameters'] ?? [], $rulesToApply['bodyParams'] ?? []);
         $queryParameters = array_merge($context['cleanQueryParameters'] ?? [], $rulesToApply['queryParams'] ?? []);
         $urlParameters = $context['cleanUrlParameters'] ?? [];
@@ -288,6 +289,24 @@ class ResponseCalls extends Strategy
         return $request;
     }
 
+    /**
+     * @param array $context
+     * @param string $authInfo in the format "<location>.<paramName>.<value>" eg "headers.Authorization.Bearer ahjuda"
+     *
+     * @return array
+     */
+    private function setAuthFieldProperly(array $context, ?string $authInfo)
+    {
+        if (!$authInfo) {
+            return $context;
+        }
+
+        [$where, $name, $value] = explode('.', $authInfo, 3);
+        $context[$where][$name] = $value;
+
+        return $context;
+    }
+
     /**
      * @param Request $request
      *

+ 2 - 2
src/Writing/Writer.php

@@ -266,8 +266,8 @@ class Writer
                     $text .= "a **`$parameterName`** header with the value **`\"{your-token}\"`**.";
                     break;
             }
-            $howToFetch = $this->config->get('auth.how_to_fetch', '');
-            $text .= " $howToFetch";
+            $extraInfo = $this->config->get('auth.extra_info', '');
+            $text .= " $extraInfo";
         }
 
         $authMarkdown = view('scribe::authentication', ['isAuthed' => $isAuthed, 'text' => $text]);

+ 2 - 0
tests/Extracting/Strategies/Responses/ResponseCallsTest.php

@@ -67,6 +67,7 @@ class ResponseCallsTest extends TestCase
             ],
         ];
         $context = [
+            'auth' => 'headers.Authorization.Bearer bearerToken',
             'headers' => [
                 'Content-Type' => 'application/json',
                 'Accept' => 'application/json',
@@ -83,6 +84,7 @@ class ResponseCallsTest extends TestCase
         $this->assertEquals('queryValue', $responseContent['queryParam']);
         $this->assertEquals('bodyValue', $responseContent['bodyParam']);
         $this->assertEquals('value', $responseContent['header']);
+        $this->assertEquals('Bearer bearerToken', $responseContent['auth']);
     }
 
     /** @test */

+ 2 - 0
tests/Fixtures/TestController.php

@@ -238,6 +238,7 @@ class TestController extends Controller
     }
 
     /**
+     * @authenticated
      * @urlparam $id Example: 3
      */
     public function shouldFetchRouteResponseWithEchoedSettings($id)
@@ -245,6 +246,7 @@ class TestController extends Controller
         return [
             '{id}' => $id,
             'header' => request()->header('header'),
+            'auth' => request()->header('Authorization'),
             'queryParam' => request()->query('queryParam'),
             'bodyParam' => request()->get('bodyParam'),
         ];

+ 84 - 0
tests/Unit/GeneratorTestCase.php

@@ -206,6 +206,19 @@ abstract class GeneratorTestCase extends TestCase
         $this->assertNull($response['param4']);
     }
 
+    /**
+     * @test
+     * @dataProvider authRules
+     */
+    public function adds_appropriate_field_based_on_configured_auth_type($config, $expected)
+    {
+        $route = $this->createRoute('POST', '/withAuthenticatedTag', 'withAuthenticatedTag', true);
+        $generator = new Generator(new DocumentationConfig($config));
+        $parsed = $generator->processRoute($route, []);
+        $this->assertNotNull($parsed[$expected['where']][$expected['name']]);
+        $this->assertStringStartsWith("{$expected['where']}.{$expected['name']}.", $parsed['auth']);
+    }
+
     /** @test */
     public function generates_consistent_examples_when_faker_seed_is_set()
     {
@@ -273,4 +286,75 @@ abstract class GeneratorTestCase extends TestCase
     abstract public function createRouteUsesArray(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class);
 
     abstract public function createRouteUsesCallable(string $httpMethod, string $path, callable $handler, $register = false);
+
+    public function authRules()
+    {
+        return [
+            [
+                array_merge($this->config, [
+                    'auth' => [
+                        'enabled' => true,
+                        'in' => 'bearer',
+                        'name' => 'dfadb',
+                    ]
+                ]),
+                [
+                    'name' => 'Authorization',
+                    'where' => 'headers',
+                ]
+            ],
+            [
+                array_merge($this->config, [
+                    'auth' => [
+                        'enabled' => true,
+                        'in' => 'basic',
+                        'name' => 'efwr',
+                    ]
+                ]),
+                [
+                    'name' => 'Authorization',
+                    'where' => 'headers',
+                ]
+            ],
+            [
+                array_merge($this->config, [
+                    'auth' => [
+                        'enabled' => true,
+                        'in' => 'header',
+                        'name' => 'Api-Key',
+                    ]
+                ]),
+                [
+                    'name' => 'Api-Key',
+                    'where' => 'headers',
+                ]
+            ],
+            [
+                array_merge($this->config, [
+                    'auth' => [
+                        'enabled' => true,
+                        'in' => 'query',
+                        'name' => 'apiKey',
+                    ]
+                ]),
+                [
+                    'name' => 'apiKey',
+                    'where' => 'cleanQueryParameters',
+                ]
+            ],
+            [
+                array_merge($this->config, [
+                    'auth' => [
+                        'enabled' => true,
+                        'in' => 'body',
+                        'name' => 'access_token',
+                    ]
+                ]),
+                [
+                    'name' => 'access_token',
+                    'where' => 'cleanBodyParameters',
+                ]
+            ],
+        ];
+    }
 }