Completed
Push — master ( fd6c7c...1f9fde )
by Matze
09:32
created

Authentication::loadUser()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 11
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 11
loc 11
ccs 4
cts 5
cp 0.8
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
crap 3.072
1
<?php
2
3
namespace BrainExe\Core\Middleware;
4
5
use BrainExe\Annotations\Annotations\Inject;
6
use BrainExe\Core\Annotations\Middleware;
7
use BrainExe\Core\Application\UserException;
8
use BrainExe\Core\Authentication\AnonymusUserVO;
9
use BrainExe\Core\Authentication\Exception\UserNotFoundException;
10
use BrainExe\Core\Authentication\LoadUser;
11
use BrainExe\Core\Authentication\UserVO;
12
use BrainExe\Core\Translation\TranslationTrait;
13
use Symfony\Component\HttpFoundation\RedirectResponse;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
17
use Symfony\Component\Routing\Route;
18
19
/**
20
 * @Middleware("Middleware.Authentication")
21
 */
22
class Authentication extends AbstractMiddleware
23
{
24
25
    use TranslationTrait;
26
27
    /**
28
     * @var LoadUser
29
     */
30
    private $loadUser;
31
32
    /**
33
     * @Inject({
34
     *  "@Core.Authentication.LoadUser",
35
     * })
36
     * @param LoadUser $loadUser
37
     */
38 6
    public function __construct(LoadUser $loadUser)
39
    {
40 6
        $this->loadUser = $loadUser;
41 6
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 4
    public function processRequest(Request $request, Route $route)
47
    {
48 4
        if ($request->attributes->has('user')) {
49
            $user = $request->attributes->get('user');
50
        } else {
51 4
            $session = $request->getSession();
52 4
            $userId  = (int)$session->get('user_id');
53
54 4
            $user = $this->loadUser($userId);
55
        }
56
57 4
        $request->attributes->set('user', $user);
58 4
        $request->attributes->set('user_id', $user->getId());
59
60 4
        $this->checkForRole($route, $user);
61
62 3
        if ($route->hasDefault('_guest')) {
63
            return null;
64
        }
65
66 3
        if (empty($user->getId())) {
67 1
            return $this->handleNotAuthenticatedRequest($request);
68
        }
69
70 2
        return null;
71
    }
72
73
    /**
74
     * @param Route $route
75
     * @param UserVO $user
76
     * @throws MethodNotAllowedException
77
     */
78 4 View Code Duplication
    protected function checkForRole(Route $route, UserVO $user)
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...
79
    {
80 4
        if ($route->hasDefault('_role')) {
81 1
            $role = $route->getDefault('_role');
82 1
            if (!in_array($role, $user->roles)) {
83 1
                throw new MethodNotAllowedException([], sprintf('Need role %s', $role));
84
            }
85
        }
86 3
    }
87
88
    /**
89
     * @param int $userId
90
     * @return AnonymusUserVO|UserVO
91
     */
92 4 View Code Duplication
    private function loadUser(int $userId) : UserVO
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...
93
    {
94 4
        if ($userId > 0) {
95
            try {
96 3
                return $this->loadUser->loadUserById($userId);
97
            } catch (UserNotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
98
            }
99
        }
100
101 1
        return new AnonymusUserVO();
102
    }
103
104
    /**
105
     * @param Request $request
106
     * @return RedirectResponse
107
     * @throws UserException
108
     */
109 1
    private function handleNotAuthenticatedRequest(Request $request)
110
    {
111 1
        if ($request->isXmlHttpRequest()) {
112
            throw new UserException($this->translate('Not logged in'));
113
        }
114
115 1
        return new RedirectResponse('#/login');
116
    }
117
}
118