File size: 2,221 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php

declare(strict_types=1);

namespace Presentation\AccessControls;

use Easy\Http\Message\StatusCode;
use Exception;
use LogicException;
use Presentation\Exceptions\HttpException;
use Presentation\Exceptions\NotFoundException;
use Shared\Infrastructure\CommandBus\Dispatcher;
use Shared\Infrastructure\CommandBus\Exception\NoHandlerFoundException;
use User\Domain\Entities\UserEntity;
use Workspace\Application\Commands\ReadWorkspaceCommand;
use Workspace\Domain\Entities\WorkspaceEntity;
use Workspace\Domain\Exceptions\WorkspaceNotFoundException;

class WorkspaceAccessControl
{
    public function __construct(
        private Dispatcher $dispatcher
    ) {
    }

    /**
     * @throws NoHandlerFoundException
     * @throws NotFoundException
     * @throws Exception
     * @throws LogicException
     * @throws HttpException
     */
    public function denyUnlessGranted(
        Permission $permission,
        UserEntity $user,
        string|WorkspaceEntity $workspace
    ): void {
        if (is_string($workspace)) {
            $workspace = $this->getWorkspace($workspace);
        }

        $isGranted = match ($permission) {
            Permission::WORKSPACE_MANAGE => $this->canManage($user, $workspace),
            default => false
        };

        if (!$isGranted) {
            throw new HttpException(statusCode: StatusCode::FORBIDDEN);
        }
    }

    private function canManage(UserEntity $user, WorkspaceEntity $workspace): bool
    {
        if (
            $workspace->getOwner()->getId()->getValue()->toString()
            !== $user->getId()->getValue()->toString()
        ) {
            return false;
        }

        return true;
    }

    /**
     * @throws NoHandlerFoundException
     * @throws NotFoundException
     */
    private function getWorkspace(string $id): WorkspaceEntity
    {
        try {
            $cmd = new ReadWorkspaceCommand($id);

            /** @var WorkspaceEntity */
            $workspace = $this->dispatcher->dispatch($cmd);
        } catch (WorkspaceNotFoundException $th) {
            throw new NotFoundException(
                param: 'id',
                previous: $th
            );
        }

        return $workspace;
    }
}