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:
Yisroel Baum 2026-05-02 21:27:36 +03:00
parent bf006220e8
commit bac8323806
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -2,6 +2,7 @@
namespace App\Text;
use App\User\User;
use App\Exceptions\BadRequestException;
use App\Text\TextRepository;
use App\Text\UseCases\CreateText;
@ -52,10 +53,19 @@ class TextController
): Response {
$data = $request->getParsedBody();
$name = $data['name'] ?? null;
$user = $request->getAttribute('user');
if (!$user instanceof User) {
return $this->errorResponse(
$response,
401,
'unauthenticated'
);
}
try {
$text = $createTextUseCase->execute(new CreateTextRequest(
name: $name,
user: $user,
));
} catch (BadRequestException $e) {
$response->getBody()->write(json_encode(['error' => $e->getMessage()]));
@ -68,4 +78,17 @@ class TextController
]));
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');
}
}