Test Failed
Pull Request — master (#19)
by Flo
03:56
created

AuthenticatorService::getUserFromSession()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
/**
3
 * Class AuthenticatorService | AuthenticatorService.php
4
 * @package Faulancer\Service
5
 * @author  Florian Knapp <[email protected]>
6
 */
7
namespace Faulancer\Service;
8
9
use Faulancer\Controller\AbstractController;
10
use Faulancer\ORM\User\Entity;
11
use Faulancer\Security\Crypt;
12
use Faulancer\ServiceLocator\ServiceInterface;
13
14
/**
15
 * Class AuthenticatorService
16
 */
17
class AuthenticatorService implements ServiceInterface
18
{
19
20
    /** @var AbstractController */
21
    protected $controller;
22
23
    /** @var DbService */
24
    protected $orm;
25
26
    /** @var Config */
27
    protected $config;
28
29
    /** @var string */
30
    protected $redirectAfterAuth;
31
32
    /**
33
     * Authenticator constructor.
34
     * @param AbstractController $controller
35
     * @param Config             $config
36
     */
37
    public function __construct(AbstractController $controller, Config $config)
38
    {
39
        $this->controller = $controller;
40
        $this->config     = $config;
41
    }
42
43
    /**
44
     * @param Entity $user
45
     * @param bool   $shouldBeActive
46
     * @return bool
47
     * @codeCoverageIgnore
48
     */
49
    public function loginUser(Entity $user, $shouldBeActive)
50
    {
51
        /** @var Entity $userData */
52
        $userData = $this->controller
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Faulancer\ServiceLocator\ServiceInterface as the method fetch() does only exist in the following implementations of said interface: Faulancer\Service\DbService.

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...
53
            ->getDb()
54
            ->fetch(get_class($user))
55
            ->where('login', '=', $user->login)
56
            ->orWhere('email', '=', $user->login)
57
            ->one();
58
59
        if (empty($userData)) {
60
            $this->controller->setFlashMessage('error.login', 'invalid_username_or_password');
61
            return $this->redirectToAuthentication();
62
        }
63
64
        if ($shouldBeActive && $userData->active !== 1) {
0 ignored issues
show
Documentation introduced by
The property active does not exist on object<Faulancer\ORM\User\Entity>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
65
            $this->controller->setFlashMessage('error.active', 'user_is_not_activated');
66
            return $this->redirectToAuthentication();
67
        }
68
69
        $passOk = Crypt::verifyPassword($user->password, $userData->password);
70
71
        if ($passOk && $userData instanceof Entity) {
72
73
            $this->saveUserInSession($userData);
74
75
            if ($userData->roles[0]->roleName === 'registered') {
76
                return $this->controller->redirect($this->controller->route('user'));
77
            } else {
78
                return $this->controller->redirect($this->controller->route('admin'));
79
            }
80
81
        }
82
83
        $this->controller->setFlashMessage('error.login', 'invalid_username_or_password');
84
85
        return $this->redirectToAuthentication();
86
    }
87
88
    /**
89
     * @return bool
90
     */
91 View Code Duplication
    public function redirectToAccessDeniedPage()
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...
92
    {
93
        /** @var Config $config */
94
        $config  = $this->controller->getServiceLocator()->get(Config::class);
95
        $authUrl = $config->get('auth:authUrl');
96
97
        return $this->controller->redirect($authUrl);
98
    }
99
100
    /**
101
     * @return bool
102
     */
103 View Code Duplication
    public function redirectToAuthentication()
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...
104
    {
105
        /** @var Config $config */
106
        $config  = $this->controller->getServiceLocator()->get(Config::class);
107
        $authUrl = $config->get('auth:authUrl');
108
109
        return $this->controller->redirect($authUrl);
110
    }
111
112
    /**
113
     * @param array $roles
114
     * @return bool
115
     */
116
    public function isPermitted(array $roles)
117
    {
118
        /** @var Entity $user */
119
        $user = $this->getUserFromSession();
120
121
        if (!$user instanceof Entity) {
122
            return null;
123
        }
124
125
        foreach ($user->roles as $userRole) {
126
127
            if (in_array($userRole->roleName, $roles, true)) {
128
                return true;
129
            }
130
131
        }
132
133
        return false;
134
    }
135
136
    /**
137
     * @param Entity $user
138
     * @codeCoverageIgnore
139
     */
140
    public function saveUserInSession(Entity $user)
141
    {
142
        $this->controller->getSessionManager()->set('user', $user->id);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Faulancer\ServiceLocator\ServiceInterface as the method set() does only exist in the following implementations of said interface: Faulancer\Service\SessionManagerService.

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...
143
    }
144
145
    /**
146
     * @param string $entity
147
     * @return Entity
148
     * @codeCoverageIgnore
149
     */
150
    public function getUserFromSession(string $entity = '')
151
    {
152
        $id = $this->controller->getSessionManager()->get('user');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Faulancer\ServiceLocator\ServiceInterface as the method get() does only exist in the following implementations of said interface: Faulancer\Service\SessionManagerService.

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...
153
154
        if (empty($id)) {
155
            return null;
156
        }
157
158
        /** @var Entity $user */
159
        if (!empty($entity)) {
160
            $user = $this->controller->getDb()->fetch($entity, $id);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Faulancer\ServiceLocator\ServiceInterface as the method fetch() does only exist in the following implementations of said interface: Faulancer\Service\DbService.

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...
161
        } else {
162
            $user = $this->controller->getDb()->fetch(Entity::class, $id);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Faulancer\ServiceLocator\ServiceInterface as the method fetch() does only exist in the following implementations of said interface: Faulancer\Service\DbService.

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...
163
        }
164
165
        return $user;
166
    }
167
168
}