1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Tests\Unit; |
5
|
|
|
|
6
|
|
|
use Longman\LaravelLodash\Middlewares\AllowCorsRequests; |
7
|
|
|
|
8
|
|
|
class MiddlewareTest extends TestCase |
|
|
|
|
9
|
|
|
{ |
10
|
|
|
protected function getEnvironmentSetUp($app) |
11
|
|
|
{ |
12
|
|
|
/** @var \Illuminate\Routing\Router $router */ |
13
|
|
|
$router = $app['router']; |
14
|
|
|
|
15
|
|
|
$router->get('url1', function () { |
16
|
|
|
return 'ok'; |
17
|
|
|
})->middleware(AllowCorsRequests::class); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** @test */ |
21
|
|
|
public function it_should_return_error_on_invalid_origin() |
22
|
|
|
{ |
23
|
|
|
config()->set('lodash.cors.allow_origins', ['domain.com']); |
24
|
|
|
|
25
|
|
|
// Invalid domain |
26
|
|
|
$response = $this->call('GET', 'url1', [], [], [], ['HTTP_Origin' => 'safsagsafsadsadsa']); |
|
|
|
|
27
|
|
|
$response->assertStatus(400); // Bad request |
|
|
|
|
28
|
|
|
|
29
|
|
|
// Without http:// |
30
|
|
|
$response = $this->call('GET', 'url1', [], [], [], ['HTTP_Origin' => 'google.com']); |
|
|
|
|
31
|
|
|
$response->assertStatus(400); // Bad request |
|
|
|
|
32
|
|
|
|
33
|
|
|
// Valid domain, but not whitelisted |
34
|
|
|
$response = $this->call('GET', 'url1', [], [], [], ['HTTP_Origin' => 'http://google.com']); |
|
|
|
|
35
|
|
|
$response->assertStatus(405); // Method not allowed |
|
|
|
|
36
|
|
|
|
37
|
|
|
// Valid similar domain, but not whitelisted |
38
|
|
|
$response = $this->call('GET', 'url1', [], [], [], ['HTTP_Origin' => 'http://mydomain.com']); |
|
|
|
|
39
|
|
|
$response->assertStatus(405); // Method not allowed |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** @test */ |
43
|
|
|
public function it_should_return_success_on_valid_origin() |
44
|
|
|
{ |
45
|
|
|
config()->set('lodash.cors.allow_origins', ['domain.com']); |
46
|
|
|
|
47
|
|
|
$origins = config('lodash.cors.allow_origins'); |
48
|
|
|
|
49
|
|
|
// Whitelisted origin |
50
|
|
|
$response = $this->call('GET', 'url1', [], [], [], ['HTTP_Origin' => 'http://' . $origins[0]]); |
|
|
|
|
51
|
|
|
$response->assertStatus(200); |
|
|
|
|
52
|
|
|
|
53
|
|
|
// Whitelisted subdomain origin |
54
|
|
|
$response = $this->call('GET', 'url1', [], [], [], ['HTTP_Origin' => 'http://sub.' . $origins[0]]); |
|
|
|
|
55
|
|
|
$response->assertStatus(200); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** @test */ |
59
|
|
|
public function it_should_return_success_on_project_url() |
60
|
|
|
{ |
61
|
|
|
config()->set('lodash.cors.allow_origins', ['domain.com']); |
62
|
|
|
|
63
|
|
|
// Whitelisted origin |
64
|
|
|
$response = $this->call('GET', 'url1', [], [], [], ['HTTP_Origin' => config('app.url', 'http://localhost')]); |
|
|
|
|
65
|
|
|
$response->assertStatus(200); |
|
|
|
|
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|