Completed
Push — feature/EVO-7278-tracking-info... ( e99586...a5fe2c )
by
unknown
11:44
created

StoreManager::getSecurityUser()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 9
loc 9
ccs 0
cts 8
cp 0
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 2
nop 0
crap 12
1
<?php
2
/**
3
 * To manage the data to be saved into DB as last thing to do.
4
 */
5
namespace Graviton\AuditTrackingBundle\Manager;
6
7
use Doctrine\ODM\MongoDB\DocumentManager;
8
use Graviton\AuditTrackingBundle\Document\AuditTracking;
9
use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
10
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
11
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
12
use Symfony\Component\Security\Core\User\UserInterface;
13
use Graviton\SecurityBundle\Entities\SecurityUser;
14
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
15
16
/**
17
 * Class StoreManager
18
 * @package Graviton\AuditTrackingBundle\Manager
19
 *
20
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
21
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
22
 * @link     http://swisscom.ch
23
 */
24
class StoreManager
25
{
26
    const AUDIT_HEADER_KEY = 'x-header-audit-thread';
27
28
    /** @var ActivityManager */
29
    private $activityManager;
30
31
    /** @var DocumentManager */
32
    private $documentManager;
33
    
34
    /** @var SecurityUser */
35
    private $securityUser;
36
37
    /**
38
     * StoreManager constructor.
39
     * @param ActivityManager $activityManager Main activity manager
40
     * @param ManagerRegistry $doctrine        Doctrine document mapper
41
     * @param TokenStorage    $tokenStorage    Sf Auth token storage
42
     */
43
    public function __construct(
44
        ActivityManager $activityManager,
45
        ManagerRegistry $doctrine,
46
        TokenStorage $tokenStorage
47
    ) {
48
        $this->activityManager = $activityManager;
49
        $this->documentManager = $doctrine->getManager();
50
        $this->tokenStorage = $tokenStorage;
51
    }
52
53
    /**
54
     * Save data to DB
55
     * onKernelResponse
56
     *
57
     * @param FilterResponseEvent $event Sf fired kernel event
58
     *
59
     * @return void
60
     */
61
    public function persistEvents(FilterResponseEvent $event)
62
    {
63
        if (!($events = $this->activityManager->getEvents())
64
            || !($username = $this->getSecurityUsername())) {
65
            return;
66
        }
67
68
        $thread = $this->generateUUID();
69
        $response = $event->getResponse();
70
        
71
        // If request is valid we save it or we do not.
72
        if (!$this->activityManager->getConfigValue('log_on_failure', 'bool')) {
73
            if (!$response->isSuccessful()) {
74
                // TODO log that we do not save
75
                return;
76
            }
77
        }
78
79
        // Set Audit header information
80
        $response->headers->set(self::AUDIT_HEADER_KEY, $thread);
81
82
        foreach ($events as $event) {
83
            $this->trackEvent($event, $thread, $username);
84
        }
85
    }
86
87
    /**
88
     * Save the event to DB
89
     *
90
     * @param AuditTracking $event    Performed by user
91
     * @param string        $thread   The thread ID
92
     * @param string        $username User connected name
93
     * @return void
94
     */
95
    private function trackEvent($event, $thread, $username)
96
    {
97
        // Request information
98
        $event->setThread($thread);
99
        $event->setUsername($username);
100
101
        try {
102
            $this->documentManager->persist($event);
103
            $this->documentManager->flush($event);
104
        } catch (\Exception $e) {
105
            // TODO LOG the error and event
106
        }
107
    }
108
109
110
111
    /**
112
     * Generate a unique identifer
113
     *
114
     * @return string
115
     */
116
    private function generateUUID()
117
    {
118
        if (!function_exists('openssl_random_pseudo_bytes')) {
119
            return uniqid('unq', true);
120
        }
121
122
        $data = openssl_random_pseudo_bytes(16);
123
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
124
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
125
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
126
    }
127
    
128
    /**
129
     * Find current user
130
     *
131
     * @return string|bool
0 ignored issues
show
Documentation introduced by
Should the return type not be UserInterface|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
132
     */
133 View Code Duplication
    private function getSecurityUser()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
    {
135
        /** @var PreAuthenticatedToken $token */
136
        if (($token = $this->tokenStorage->getToken())
137
            && ($user = $token->getUser()) instanceof UserInterface ) {
138
            return $user;
139
        }
140
        return false;
141
    }
142
143
    /**
144
     * Last check before saving the Event into DB
145
     *
146
     * @return bool|string
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use false|string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
147
     */
148
    public function getSecurityUsername()
149
    {
150
        // No securityUser, no tracking
151
        if (!($this->securityUser = $this->getSecurityUser())) {
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getSecurityUser() of type object<Symfony\Component...ore\User\UserInterface> or false is incompatible with the declared type object<Graviton\Security...\Entities\SecurityUser> of property $securityUser.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
152
            return false;
153
        }
154
155
        // Check if we wanna log test and localhost calls
156
        if (!$this->activityManager->getConfigValue('log_test_calls', 'bool')) {
157
            if (!$this->securityUser->hasRole(SecurityUser::ROLE_CONSULTANT)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Security\Core\User\UserInterface as the method hasRole() does only exist in the following implementations of said interface: Graviton\SecurityBundle\Entities\SecurityUser.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
158
                return false;
159
            }
160
        }
161
162
        return $this->securityUser->getUsername();
163
    }
164
}
165