Skip to content

Commit

Permalink
various changes of methods and code improve
Browse files Browse the repository at this point in the history
  • Loading branch information
rigonlucas committed Aug 23, 2024
1 parent 0e6bc00 commit 6f5f700
Show file tree
Hide file tree
Showing 36 changed files with 230 additions and 194 deletions.
8 changes: 4 additions & 4 deletions app/Http/Controllers/V1/User/ChangeUserRoleController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

use App\Http\Controllers\Controller;
use App\Http\Requests\V1\User\ChangeUserRoleRequest;
use Core\Application\User\ChangeRole\Inputs\ChangeRoleInput;
use Core\Application\User\ChangeRole\Inputs\ChangeUserRoleInput;
use Core\Application\User\Commons\Gateways\UserCommandInterface;
use Core\Application\User\Commons\Gateways\UserRepositoryInterface;
use Core\Presentation\Http\Errors\ErrorPresenter;
use Core\Services\Framework\FrameworkContract;
use Core\Support\Exceptions\OutputErrorException;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Infra\Handlers\UseCases\User\ChangeRole\ChangeRoleUserHandler;

class ChangeUserRoleController extends Controller
Expand All @@ -25,7 +25,7 @@ public function __construct(
public function __invoke(ChangeUserRoleRequest $request, string $userUuid)
{
$userAutenticated = $this->frameworkService->auth()->user();
$changeRoleInput = new ChangeRoleInput(
$changeRoleInput = new ChangeUserRoleInput(
authenticatedUser: $userAutenticated,
userUuid: $userUuid,
role: $request->role
Expand All @@ -52,7 +52,7 @@ public function __invoke(ChangeUserRoleRequest $request, string $userUuid)
}

return response()->json(
status: ResponseStatusCodeEnum::NO_CONTENT->value
status: ResponseStatus::NO_CONTENT->value
);
}
}
4 changes: 2 additions & 2 deletions app/Http/Controllers/V1/User/CreateUserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Core\Presentation\Http\User\UserPresenter;
use Core\Services\Framework\FrameworkContract;
use Core\Support\Exceptions\OutputErrorException;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Infra\Handlers\UseCases\User\Create\CreateUserHandler;

class CreateUserController extends Controller
Expand Down Expand Up @@ -70,7 +70,7 @@ public function __invoke(CreateUserRequest $request)

return response()->json(
data: (new UserPresenter($output->userEntity))->withDataAttribute()->toArray(),
status: ResponseStatusCodeEnum::CREATED->value
status: ResponseStatus::CREATED->value
);
}
}
4 changes: 2 additions & 2 deletions app/Http/Controllers/V1/User/ShowUserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
use Core\Presentation\Http\User\UserDetaisPresenter;
use Core\Services\Framework\FrameworkContract;
use Core\Support\Exceptions\OutputErrorException;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Infra\Database\User\Repository\UserRepository;
use Ramsey\Uuid\Uuid;

Expand Down Expand Up @@ -45,7 +45,7 @@ public function __invoke(string $uuid)

return response()->json(
data: (new UserDetaisPresenter($userEntity))->withDataAttribute()->toArray(),
status: ResponseStatusCodeEnum::OK->value
status: ResponseStatus::OK->value
);
}
}
9 changes: 5 additions & 4 deletions app/Http/Controllers/V1/User/UpdateUserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Core\Services\Framework\FrameworkContract;
use Core\Support\Exceptions\InvalidEmailException;
use Core\Support\Exceptions\OutputErrorException;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Infra\Handlers\UseCases\User\Update\UpdateUserHandler;
use Ramsey\Uuid\Uuid;

Expand All @@ -35,9 +35,10 @@ public function __invoke(UpdateUserRequest $request, string $uuid)
$input = new UpdateUserInput(
uuid: Uuid::fromString($uuid),
name: $request->name,
email: new EmailValueObject($request->email, false),
email: new EmailValueObject($request->email),
password: $request->password,
birthday: Carbon::createFromFormat('Y-m-d', $request->birthday)
birthday: Carbon::createFromFormat('Y-m-d', $request->birthday),
authenticableUser: $this->frameworkService->auth()->user()
);

try {
Expand Down Expand Up @@ -69,7 +70,7 @@ public function __invoke(UpdateUserRequest $request, string $uuid)

return response()->json(
data: (new UserPresenter($output->userEntity))->withDataAttribute()->toArray(),
status: ResponseStatusCodeEnum::OK->value
status: ResponseStatus::OK->value
);
}
}
4 changes: 2 additions & 2 deletions core/Application/Account/Create/CreateAccountUseCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use Core\Domain\Entities\Account\AccountEntity;
use Core\Domain\Entities\User\UserEntity;
use Core\Services\Framework\FrameworkContract;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Core\Support\Validations\HasErrorBagTrait;

class CreateAccountUseCase
Expand Down Expand Up @@ -77,7 +77,7 @@ private function findAnAccountByAccessCode(AccountInput $accountInput): AccountE
if (is_null($accountEntity)) {
throw new AccountNotFoundException(
message: 'Account join code not found',
code: ResponseStatusCodeEnum::NOT_FOUND->value
code: ResponseStatus::NOT_FOUND->value
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

namespace Core\Application\User\ChangeRole;

use Core\Application\User\ChangeRole\Inputs\ChangeRoleInput;
use Core\Application\User\ChangeRole\Inputs\ChangeUserRoleInput;
use Core\Application\User\Commons\Exceptions\UserNotFountException;
use Core\Application\User\Commons\Gateways\UserCommandInterface;
use Core\Application\User\Commons\Gateways\UserRepositoryInterface;
use Core\Support\Exceptions\ForbidenException;
use Core\Support\Exceptions\InvalidRoleException;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Core\Support\Permissions\UserRoles;

readonly class ChangeRoleUseCase
readonly class ChangeUserRoleUseCase
{
public function __construct(
private UserCommandInterface $userCommand,
Expand All @@ -24,27 +24,22 @@ public function __construct(
* @throws InvalidRoleException
* @throws ForbidenException
*/
public function execute(ChangeRoleInput $input): void
public function execute(ChangeUserRoleInput $input): void
{
if ($input->authenticatedUser->hasNotPermission(UserRoles::ADMIN)) {
throw new ForbidenException(
message: 'You do not have permission to change the role',
code: ResponseStatusCodeEnum::FORBIDDEN->value
);
}
$this->validateAccessPolicies($input);

if (UserRoles::isValidRole($input->role)) {
throw new InvalidRoleException(
message: 'Invalid role',
code: ResponseStatusCodeEnum::BAD_REQUEST->value
code: ResponseStatus::BAD_REQUEST->value
);
}

$userForChange = $this->userRepository->findByUuid($input->userUuid);
if (!$userForChange) {
throw new UserNotFountException(
message: 'User not found',
code: ResponseStatusCodeEnum::NOT_FOUND->value
code: ResponseStatus::NOT_FOUND->value
);
}
$userForChange->checkUsersAreFromSameAccount($input->authenticatedUser);
Expand All @@ -56,4 +51,16 @@ public function execute(ChangeRoleInput $input): void
$userForChange->setPermissions($input->role);
$this->userCommand->changeRole($userForChange);
}

/**
* @throws ForbidenException
*/
private function validateAccessPolicies(ChangeUserRoleInput $input): void
{
if ($input->authenticatedUser->hasNotPermission(UserRoles::ADMIN)) {
throw new ForbidenException(
message: 'You do not have permission to change the role'
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use Core\Domain\Entities\User\UserEntity;

readonly class ChangeRoleInput
readonly class ChangeUserRoleInput
{
public function __construct(
public UserEntity $authenticatedUser,
Expand Down
28 changes: 15 additions & 13 deletions core/Application/User/Create/CreateUserUseCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ public function __construct(
*/
public function execute(CreateUserInput $createUserInput): UserEntity
{
$this->processEmail($createUserInput);
$emailAlreadyExists = $this->userRepository->existsEmail($createUserInput->email);
if ($emailAlreadyExists) {
$this->addError('email', 'Email já utilizado por outro usuário');
}

$userEntity = UserEntity::forCreate(
name: $this->framework->Str()->title($createUserInput->name),
Expand All @@ -36,26 +39,25 @@ public function execute(CreateUserInput $createUserInput): UserEntity
uuid: $this->framework->uuid()->uuid7Generate(),
birthday: $createUserInput->birthday
);
$this->processValidations($userEntity);
$this->checkValidationErrors();

return $this->createUserInterface->create($userEntity);
}

/**
* @param UserEntity $userEntity
* @return void
*/
private function processValidations(UserEntity $userEntity): void
{
if ($userEntity->getEmail()->isInvalid()) {
$this->addError('email', 'Invalid email');
}
$isUnderAge = $userEntity->underAge();
if ($isUnderAge) {
$this->addError('birthday', 'Idade inválida');
}

$this->checkValidationErrors();

return $this->createUserInterface->create($userEntity);
}

private function processEmail(CreateUserInput $createUserInput): void
{
$emailAlreadyExists = $this->userRepository->existsEmail($createUserInput->email);
if ($emailAlreadyExists) {
$this->addError('email', 'Email já utilizado por outro usuário');
}
}

}
30 changes: 19 additions & 11 deletions core/Application/User/Show/ShowUserUseCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use Core\Application\User\Commons\Exceptions\UserNotFountException;
use Core\Application\User\Commons\Gateways\UserRepositoryInterface;
use Core\Domain\Entities\User\UserEntity;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Core\Support\Permissions\UserRoles;
use Ramsey\Uuid\UuidInterface;

Expand All @@ -23,20 +23,12 @@ public function __construct(
*/
public function execute(UuidInterface $uuid, UserEntity $userAuthenticaded): UserEntity
{
if (
!$userAuthenticaded->getUuid()->equals($uuid) &&
$userAuthenticaded->hasNotPermission(UserRoles::ADMIN)
) {
throw new UserNotFountException(
message: 'Forbidden access',
code: ResponseStatusCodeEnum::FORBIDDEN->value,
);
}
$this->validateAccessPolicies($userAuthenticaded, $uuid);
$userEntity = $this->userRepository->findByUuid($uuid);
if (!$userEntity) {
throw new UserNotFountException(
message: 'User not found',
code: ResponseStatusCodeEnum::NOT_FOUND->value,
code: ResponseStatus::NOT_FOUND->value,
);
}

Expand All @@ -45,4 +37,20 @@ public function execute(UuidInterface $uuid, UserEntity $userAuthenticaded): Use

return $userEntity;
}

/**
* @throws UserNotFountException
*/
private function validateAccessPolicies(UserEntity $userAuthenticaded, UuidInterface $uuid): void
{
if (
!$userAuthenticaded->getUuid()->equals($uuid) &&
$userAuthenticaded->hasNotPermission(UserRoles::ADMIN)
) {
throw new UserNotFountException(
message: 'Forbidden access',
code: ResponseStatus::FORBIDDEN->value,
);
}
}
}
4 changes: 3 additions & 1 deletion core/Application/User/Update/Inputs/UpdateUserInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Core\Application\User\Update\Inputs;

use Core\Domain\Entities\User\UserEntity;
use Core\Domain\ValueObjects\EmailValueObject;
use DateTimeInterface;
use Ramsey\Uuid\UuidInterface;
Expand All @@ -15,7 +16,8 @@ public function __construct(
public EmailValueObject $email,
#[SensitiveParameter]
public string $password,
public DateTimeInterface $birthday
public DateTimeInterface $birthday,
public UserEntity $authenticableUser
) {
}
}
30 changes: 16 additions & 14 deletions core/Application/User/Update/UpdateUserUseCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use Core\Services\Framework\FrameworkContract;
use Core\Support\Exceptions\ForbidenException;
use Core\Support\Exceptions\OutputErrorException;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;
use Core\Support\Permissions\UserRoles;
use Core\Support\Validations\HasErrorBagTrait;

Expand All @@ -31,23 +31,13 @@ public function __construct(
*/
public function execute(UpdateUserInput $input): UserEntity
{
if (!filter_var($input->email, FILTER_VALIDATE_EMAIL)) {
$this->addError('email', 'Invalid email.');
}
$this->validateAccessPolicies($input);

$recordedUser = $this->userRepository->findByUuid(uuid: $input->uuid);
if (!$recordedUser) {
throw new UserNotFountException(
message: 'Contém erros de validação',
code: ResponseStatusCodeEnum::NOT_FOUND->value
);
}
if (
!$this->framework->auth()->user()->getUuid()->equals($input->uuid) &&
!$this->framework->auth()->user()->hasNotPermission(UserRoles::ADMIN)
) {
throw new ForbidenException(
message: 'Você não tem permissão para alterar este usuário',
code: ResponseStatusCodeEnum::FORBIDDEN->value
code: ResponseStatus::NOT_FOUND->value
);
}

Expand Down Expand Up @@ -76,4 +66,16 @@ public function execute(UpdateUserInput $input): UserEntity
$userEntity->setUuid($recordedUser->getUuid());
return $this->userCommand->update($userEntity);
}

private function validateAccessPolicies(UpdateUserInput $input): void
{
if (
!$input->authenticableUser->getUuid()->equals($input->uuid) &&
!$input->authenticableUser->hasNotPermission(UserRoles::ADMIN)
) {
throw new ForbidenException(
message: 'Você não tem permissão para alterar este usuário'
);
}
}
}
4 changes: 2 additions & 2 deletions core/Domain/Entities/Account/AccountEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use Core\Domain\Entities\Account\Traits\Account\AccountEntityAcessors;
use Core\Domain\Entities\Account\Traits\Account\AccountEntityBuilder;
use Core\Domain\Entities\User\UserEntity;
use Core\Support\Http\ResponseStatusCodeEnum;
use Core\Support\Http\ResponseStatus;

class AccountEntity
{
Expand All @@ -32,7 +32,7 @@ public function validateAccountName(): void
if (is_null($this->name) || strlen($this->name) <= 0) {
throw new AccountNameInvalidException(
'Account name is required',
ResponseStatusCodeEnum::BAD_REQUEST->value
ResponseStatus::BAD_REQUEST->value
);
}
}
Expand Down
Loading

0 comments on commit 6f5f700

Please sign in to comment.