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

AuthenticatorService::isAuthenticated()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A AuthenticatorService::redirectToAccessDeniedPage() 8 8 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
     * @param string $redirectUrl
47
     * @return bool
48
     * @codeCoverageIgnore
49
     */
50
    public function loginUser(Entity $user, $shouldBeActive = true, $redirectUrl = '')
51
    {
52
        /** @var Entity $userData */
53
        $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...
54
            ->getDb()
55
            ->fetch(get_class($user))
56
            ->where('login', '=', $user->login)
57
            ->orWhere('email', '=', $user->login)
58
            ->one();
59
60
        if (empty($userData)) {
61
            $this->controller->setFlashMessage('error.login', 'invalid_username_or_password');
62
            return $this->redirectToAuthentication();
63
        }
64
65
        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...
66
            $this->controller->setFlashMessage('error.active', 'user_is_not_activated');
67
            return $this->redirectToAuthentication();
68
        }
69
70
        $passOk = Crypt::verifyPassword($user->password, $userData->password);
71
72
        if ($passOk && $userData instanceof Entity) {
73
74
            $this->saveUserInSession($userData);
75
76
            if ($redirectUrl) {
77
                return $this->controller->redirect($redirectUrl);
78
            }
79
80
            if ($userData->roles[0]->roleName === 'registered') {
81
                return $this->controller->redirect($this->controller->route('user'));
82
            } else {
83
                return $this->controller->redirect($this->controller->route('admin'));
84
            }
85
86
        }
87
88
        $this->controller->setFlashMessage('error.login', 'invalid_username_or_password');
89
90
        return $this->redirectToAuthentication();
91
    }
92
93
    /**
94
     * @return bool
95
     */
96 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...
97
    {
98
        /** @var Config $config */
99
        $config  = $this->controller->getServiceLocator()->get(Config::class);
100
        $authUrl = $config->get('auth:authUrl');
101
102
        return $this->controller->redirect($authUrl);
103
    }
104
105
    /**
106
     * @return bool
107
     */
108 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...
109
    {
110
        /** @var Config $config */
111
        $config  = $this->controller->getServiceLocator()->get(Config::class);
112
        $authUrl = $config->get('auth:authUrl');
113
114
        return $this->controller->redirect($authUrl);
115
    }
116
117
    /**
118
     * @param array $roles
119
     * @return bool
120
     */
121
    public function isPermitted(array $roles)
122
    {
123
        /** @var Entity $user */
124
        $user = $this->getUserFromSession();
125
126
        if (!$user instanceof Entity) {
127
            return null;
128
        }
129
130
        foreach ($user->roles as $userRole) {
131
132
            if (in_array($userRole->roleName, $roles, true)) {
133
                return true;
134
            }
135
136
        }
137
138
        return false;
139
    }
140
141
    /**
142
     * @param Entity $user
143
     * @codeCoverageIgnore
144
     */
145
    public function saveUserInSession(Entity $user)
146
    {
147
        $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...
148
    }
149
150
    /**
151
     * @param string $entity
152
     * @return Entity
153
     * @codeCoverageIgnore
154
     */
155
    public function getUserFromSession(string $entity = '')
156
    {
157
        $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...
158
159
        if (empty($id)) {
160
            return null;
161
        }
162
163
        /** @var Entity $user */
164
        if (!empty($entity)) {
165
            $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...
166
        } else {
167
            $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...
168
        }
169
170
        return $user;
171
    }
172
173
}