Completed
Pull Request — master (#19)
by Flo
02:42
created

AuthenticatorService   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 145
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 6
dl 0
loc 145
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A saveUserInSession() 0 4 1
C loginUser() 0 42 8
A redirectToAuthentication() 0 8 1
A isPermitted() 0 19 4
A getUserFromSession() 0 17 3
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
    public function redirectToAuthentication()
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
     * @param array $roles
107
     * @return bool
108
     */
109
    public function isPermitted(array $roles)
110
    {
111
        /** @var Entity $user */
112
        $user = $this->getUserFromSession();
113
114
        if (!$user instanceof Entity) {
115
            return null;
116
        }
117
118
        foreach ($user->roles as $userRole) {
119
120
            if (in_array($userRole->roleName, $roles, true)) {
121
                return true;
122
            }
123
124
        }
125
126
        return false;
127
    }
128
129
    /**
130
     * @param Entity $user
131
     * @codeCoverageIgnore
132
     */
133
    public function saveUserInSession(Entity $user)
134
    {
135
        $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...
136
    }
137
138
    /**
139
     * @param string $entity
140
     * @return Entity
141
     * @codeCoverageIgnore
142
     */
143
    public function getUserFromSession(string $entity = '')
144
    {
145
        $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...
146
147
        if (empty($id)) {
148
            return null;
149
        }
150
151
        /** @var Entity $user */
152
        if (!empty($entity)) {
153
            $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...
154
        } else {
155
            $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...
156
        }
157
158
        return $user;
159
    }
160
161
}