5 use BookStack\Auth\Permissions\RolePermission;
8 class ApiAuthTest extends TestCase
12 protected $endpoint = '/api/books';
14 public function test_requests_succeed_with_default_auth()
16 $viewer = $this->getViewer();
17 $resp = $this->get($this->endpoint);
18 $resp->assertStatus(401);
20 $this->actingAs($viewer, 'web');
22 $resp = $this->get($this->endpoint);
23 $resp->assertStatus(200);
26 public function test_no_token_throws_error()
28 $resp = $this->get($this->endpoint);
29 $resp->assertStatus(401);
30 $resp->assertJson($this->errorResponse("No authorization token found on the request", 401));
33 public function test_bad_token_format_throws_error()
35 $resp = $this->get($this->endpoint, ['Authorization' => "Token abc123"]);
36 $resp->assertStatus(401);
37 $resp->assertJson($this->errorResponse("An authorization token was found on the request but the format appeared incorrect", 401));
40 public function test_token_with_non_existing_id_throws_error()
42 $resp = $this->get($this->endpoint, ['Authorization' => "Token abc:123"]);
43 $resp->assertStatus(401);
44 $resp->assertJson($this->errorResponse("No matching API token was found for the provided authorization token", 401));
47 public function test_token_with_bad_secret_value_throws_error()
49 $resp = $this->get($this->endpoint, ['Authorization' => "Token {$this->apiTokenId}:123"]);
50 $resp->assertStatus(401);
51 $resp->assertJson($this->errorResponse("The secret provided for the given used API token is incorrect", 401));
54 public function test_api_access_permission_required_to_access_api()
56 $resp = $this->get($this->endpoint, $this->apiAuthHeader());
57 $resp->assertStatus(200);
60 $accessApiPermission = RolePermission::getByName('access-api');
61 $editorRole = $this->getEditor()->roles()->first();
62 $editorRole->detachPermission($accessApiPermission);
64 $resp = $this->get($this->endpoint, $this->apiAuthHeader());
65 $resp->assertJson($this->errorResponse("The owner of the used API token does not have permission to make API calls", 403));
68 public function test_token_expiry_checked()
70 $editor = $this->getEditor();
71 $token = $editor->apiTokens()->first();
73 $resp = $this->get($this->endpoint, $this->apiAuthHeader());
74 $resp->assertStatus(200);
77 $token->expires_at = Carbon::now()->subDay()->format('Y-m-d');
80 $resp = $this->get($this->endpoint, $this->apiAuthHeader());
81 $resp->assertJson($this->errorResponse("The authorization token used has expired", 403));
84 public function test_email_confirmation_checked_using_api_auth()
86 $editor = $this->getEditor();
87 $editor->email_confirmed = false;
90 // Set settings and get user instance
91 $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']);
93 $resp = $this->get($this->endpoint, $this->apiAuthHeader());
94 $resp->assertStatus(401);
95 $resp->assertJson($this->errorResponse("The email address for the account in use needs to be confirmed", 401));