Auth::update()   D
last analyzed

Complexity

Conditions 13
Paths 8

Size

Total Lines 89
Code Lines 38

Duplication

Lines 15
Ratio 16.85 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 0
Metric Value
dl 15
loc 89
ccs 0
cts 51
cp 0
rs 4.9922
c 0
b 0
f 0
cc 13
eloc 38
nc 8
nop 1
crap 182

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 *
5
 * This file is part of the Apix Project.
6
 *
7
 * (c) Franck Cassedanne <franck at ouarz.net>
8
 *
9
 * @license     http://opensource.org/licenses/BSD-3-Clause  New BSD License
10
 *
11
 */
12
13
namespace Apix\Plugin;
14
15
use Apix\Service,
16
    Apix\Exception;
17
18
class Auth extends PluginAbstractEntity
19
{
20
    public static $hook = array('entity', 'early');
21
22
    protected $options = array(
23
        // 'enable'        => true,        // wether to enable or not
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
24
        'adapter'       => 'Apix\Plugin\Auth\Adapter',
25
        'public_group'  => 'public',    // public group to skip auth
26
    );
27
28
    protected $annotation = 'api_auth';
29
30
    public function update(\SplSubject $entity)
0 ignored issues
show
Coding Style introduced by
update uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
31
    {
32
        $this->entity = $entity;
0 ignored issues
show
Documentation Bug introduced by
$entity is of type object<SplSubject>, but the property $entity was declared to be of type object<Apix\Entity>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
33
34
        $groups = $this->getSubTagValues('groups');
35
        $users = $this->getSubTagValues('users');
36
37
        // skip auth if groups and users are both null
38
        // or if the group is public.
39
        if(
40
            null === $users
41
            && null === $groups
42
            || null !== $groups
43
            && in_array($this->options['public_group'], $groups)
44
        ) {
45
            return null;
46
        }
47
48
        $logger = Service::get('logger');
49
50
        // authenticate
51
        if ( !$this->adapter->authenticate() ) {
52
53
            // $logger->info(
54
            //     'Login failed for "{username}"',
55
            //     array('username' => $this->adapter->getUsername())
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
56
            // );
57
58
            $this->adapter->send();
59
60
            // TODO: eventually in Auth...
61
            // $response = Service::get('response');
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
62
            // $response->setHeaders($headers);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
63
            // $response->send();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
64
65
            throw new Exception('Authentication required', 401);
66
        }
67
68
        // TODO: get the Session object.
69
        if (Service::has('session')) {
70
            $session = Service::get('session');
71
72
            $context = array('user' => $session->getUsername());
73
74
            // check the username is in the authorised list.
75 View Code Duplication
            if (null !== $users && !in_array($context['user'], $users)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
76
77
                $logger->notice('Auth: User unauthorised [{user}]', $context);
78
79
                throw new Exception('Access unauthorised', 401);
80
            }
81
82
            // check user group
83
            $context['group'] = $session->getGroup();
84 View Code Duplication
            if (null !== $groups && !in_array($context['group'], $groups) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
85
86
                $logger->notice(
87
                    'Auth: Sessions\'s group unauthorised [{user}/{group}]".',
88
                    $context
89
                );
90
91
                throw new Exception('Access unauthorised.', 401);
92
            }
93
94
            // check for (required) trusted user IPs
95
            if ($session->hasTrustedIps()) {
96
                $context['ip'] = Service::get('response')->getRequest()->getIp();
97
                if (!$this->isTrustedIp($context['ip'], $session->getTrustedIps())) {
98
99
                    $logger->notice(
100
                        'Auth: Session\'s IP not trusted [{user}/{group}/{ip}].',
101
                        $context
102
                    );
103
104
                    throw new Exception('Session\'s IP not trusted', 401);
105
                }
106
            }
107
108
            // TODO: set X_REMOTE_USER or X_AUTH_USER
109
            $_SERVER['X_AUTH_USER'] = $context['user'];
110
111
            $logger->info(
112
                'Auth: User logged in [{user}/{group}/{ip}]',
113
                $context
114
            );
115
        }
116
117
        return true;
118
    }
119
120
    protected function isTrustedIp($ip, array $ips)
121
    {
122
        // TODO: improve this, check IP ranges, etc...
123
        return in_array($ip, $ips);
124
    }
125
126
}
127