File size: 2,500 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
91
92
<?php

namespace Mautic\CoreBundle\Twig\Helper;

use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\UserBundle\Entity\User;
use Mautic\UserBundle\Event\AuthenticationContentEvent;
use Mautic\UserBundle\UserEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;

/**
 * final class SecurityHelper.
 */
final class SecurityHelper
{
    public function __construct(
        private CorePermissions $security,
        private RequestStack $requestStack,
        private EventDispatcherInterface $dispatcher,
        private CsrfTokenManagerInterface $tokenManager
    ) {
    }

    public function getName(): string
    {
        return 'security';
    }

    /**
     * Helper function to check if user is an Admin.
     */
    public function isAdmin(): bool
    {
        return $this->security->isAdmin();
    }

    /**
     * Helper function to check if the logged in user has access to an entity.
     *
     * @param string|bool $ownPermission
     * @param string|bool $otherPermission
     * @param User|int    $ownerId
     */
    public function hasEntityAccess($ownPermission, $otherPermission, $ownerId): bool
    {
        return $this->security->hasEntityAccess($ownPermission, $otherPermission, $ownerId);
    }

    /**
     * @param string[]|string $permission
     *
     * @return mixed
     */
    public function isGranted($permission)
    {
        return $this->security->isGranted($permission);
    }

    /**
     * Get content from listeners.
     */
    public function getAuthenticationContent(): string
    {
        $request = $this->requestStack->getCurrentRequest();
        $content = '';
        if ($this->dispatcher->hasListeners(UserEvents::USER_AUTHENTICATION_CONTENT)) {
            $event = new AuthenticationContentEvent($request);
            $this->dispatcher->dispatch($event, UserEvents::USER_AUTHENTICATION_CONTENT);
            $content = $event->getContent();

            // Remove post_logout session after content has been generated
            $request->getSession()->remove('post_logout');
        }

        return $content;
    }

    /**
     * Returns CSRF token string for an intention.
     *
     * @param string $intention
     *
     * @return string
     */
    public function getCsrfToken($intention)
    {
        return $this->tokenManager->getToken($intention)->getValue();
    }
}