AbstractAuthorizedApiController   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 6
c 2
b 0
f 1
lcom 0
cbo 0
dl 0
loc 39
rs 10
ccs 0
cts 22
cp 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A authorizeApi() 0 14 4
A init() 0 8 2
1
<?php
2
3
namespace Craft;
4
5
/**
6
 * Class ApiAuthController
7
 *
8
 * Api authentication using user keys
9
 *
10
 * @author    Nerds & Company
11
 * @copyright Copyright (c) 2015, Nerds & Company
12
 * @license   MIT
13
 *
14
 * @link      http://www.nerds.company
15
 */
16
abstract class AbstractAuthorizedApiController extends BaseController
17
{
18
    /**
19
     * Allow anonymous access to this controller.
20
     *
21
     * @var bool
22
     */
23
    protected $allowAnonymous = true;
24
25
    /**
26
     * Initialize controller
27
     */
28
    public function init()
29
    {
30
        craft()->apiAuth->setCorsHeaders();
31
        if (craft()->apiAuth->isOptionsRequest()) {
32
            craft()->end();
33
        }
34
        $this->authorizeApi();
35
    }
36
37
    /**
38
     * @return bool
39
     */
40
    private function authorizeApi()
0 ignored issues
show
Coding Style introduced by
authorizeApi 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...
41
    {
42
        if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
43
            http_response_code(401);
44
            $this->returnErrorJson(Craft::t('Authorization header missing'));
45
        }
46
        $key = $_SERVER['HTTP_AUTHORIZATION'];
47
        list($bearer, $token) = explode(' ', $key);
48
        if ($bearer != 'Bearer' || !craft()->apiAuth->authenticateKey($token)) {
49
            http_response_code(401);
50
            $this->returnErrorJson(Craft::t('Invalid key used'));
51
        }
52
        return true;
53
    }
54
}
55