extract user from session in text controller
prevent payload from spoofing ownership by reading the user from the request attribute set by auth middleware. respond 401 when unauthenticated.
This commit is contained in:
parent
bf006220e8
commit
bac8323806
1 changed files with 23 additions and 0 deletions
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
namespace App\Text;
|
namespace App\Text;
|
||||||
|
|
||||||
|
use App\User\User;
|
||||||
use App\Exceptions\BadRequestException;
|
use App\Exceptions\BadRequestException;
|
||||||
use App\Text\TextRepository;
|
use App\Text\TextRepository;
|
||||||
use App\Text\UseCases\CreateText;
|
use App\Text\UseCases\CreateText;
|
||||||
|
|
@ -52,10 +53,19 @@ class TextController
|
||||||
): Response {
|
): Response {
|
||||||
$data = $request->getParsedBody();
|
$data = $request->getParsedBody();
|
||||||
$name = $data['name'] ?? null;
|
$name = $data['name'] ?? null;
|
||||||
|
$user = $request->getAttribute('user');
|
||||||
|
if (!$user instanceof User) {
|
||||||
|
return $this->errorResponse(
|
||||||
|
$response,
|
||||||
|
401,
|
||||||
|
'unauthenticated'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$text = $createTextUseCase->execute(new CreateTextRequest(
|
$text = $createTextUseCase->execute(new CreateTextRequest(
|
||||||
name: $name,
|
name: $name,
|
||||||
|
user: $user,
|
||||||
));
|
));
|
||||||
} catch (BadRequestException $e) {
|
} catch (BadRequestException $e) {
|
||||||
$response->getBody()->write(json_encode(['error' => $e->getMessage()]));
|
$response->getBody()->write(json_encode(['error' => $e->getMessage()]));
|
||||||
|
|
@ -68,4 +78,17 @@ class TextController
|
||||||
]));
|
]));
|
||||||
return $response->withHeader('Content-Type', 'application/json');
|
return $response->withHeader('Content-Type', 'application/json');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function errorResponse(
|
||||||
|
Response $response,
|
||||||
|
int $status,
|
||||||
|
string $message,
|
||||||
|
): Response {
|
||||||
|
$response->getBody()->write(
|
||||||
|
json_encode(['error' => $message])
|
||||||
|
);
|
||||||
|
|
||||||
|
return $response->withStatus($status)
|
||||||
|
->withHeader('Content-Type', 'application/json');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue