Completed
Pull Request — master (#16)
by Flo
07:29
created

redirectAfterAuthentication()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Class AuthenticatorService | AuthenticatorService.php
4
 * @package Faulancer\Auth
5
 * @author  Florian Knapp <[email protected]>
6
 */
7
namespace Faulancer\Service;
8
9
use Faulancer\Controller\Controller;
10
use Faulancer\ORM\User\Entity as UserEntity;
11
use Faulancer\ServiceLocator\ServiceInterface;
12
use Faulancer\Session\SessionManager;
13
14
/**
15
 * Class AuthenticatorService
16
 */
17
class AuthenticatorService implements ServiceInterface
18
{
19
20
    /** @var Controller */
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 Controller $controller
35
     * @param Config     $config
36
     */
37
    public function __construct(Controller $controller, Config $config)
38
    {
39
        $this->controller = $controller;
40
        $this->config     = $config;
41
    }
42
43
    /**
44
     * @param UserEntity $user
45
     * @return bool
46
     * @codeCoverageIgnore
47
     */
48
    public function loginUser(UserEntity $user)
49
    {
50
        /** @var UserEntity $userData */
51
        $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...
52
            ->getDb()
53
            ->fetch(get_class($user))
54
            ->where('login', '=', $user->login)
55
            ->andWhere('password', '=', $user->password)
56
            ->one();
57
58
        if ($userData instanceof UserEntity) {
59
            $this->saveUserInSession($userData);
60
            return $this->controller->redirect($this->redirectAfterAuth);
61
        }
62
63
        /** @var SessionManagerService $sessionManager */
64
        $sessionManager = $this->controller->getServiceLocator()->get(SessionManagerService::class);
65
        $sessionManager->setFlashbag('loginError', 'No valid username/password combination found.');
66
        return $this->redirectToAuthentication();
67
    }
68
69
    /**
70
     * @return bool
71
     */
72
    public function redirectToAuthentication()
73
    {
74
        /** @var Config $config */
75
        $config  = $this->controller->getServiceLocator()->get(Config::class);
76
        $authUrl = $config->get('auth:authUrl');
77
78
        return $this->controller->redirect($authUrl);
79
    }
80
81
    /**
82
     * @param string $uri
83
     * @codeCoverageIgnore
84
     */
85
    public function redirectAfterAuthentication(string $uri)
86
    {
87
        $this->redirectAfterAuth = $uri;
88
    }
89
90
    /**
91
     * @param array $roles
92
     * @return bool
93
     */
94
    public function isAuthenticated(array $roles)
95
    {
96
        /** @var UserEntity $user */
97
        $user = $this->getUserFromSession();
98
99
        if (!$user instanceof UserEntity) {
100
            return false;
101
        }
102
103
        foreach ($user->roles as $userRole) {
104
105
            if (in_array($userRole->roleName, $roles, true)) {
106
                return true;
107
            }
108
109
        }
110
111
        return false;
112
    }
113
114
    /**
115
     * @param UserEntity $user
116
     */
117
    public function saveUserInSession(UserEntity $user)
118
    {
119
        $this->controller->getSessionManager()->set('user', $user->id);
120
    }
121
122
    /**
123
     * @return UserEntity
124
     */
125
    public function getUserFromSession()
126
    {
127
        $id = $this->controller->getSessionManager()->get('user');
128
129
        /** @var UserEntity $user */
130
        $user = $this->controller->getDb()->fetch(UserEntity::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...
131
        return $user;
132
    }
133
134
}