Test Failed
Pull Request — master (#80)
by Maximo
05:30
created

AuthenticationMiddleware::call()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7.2269

Importance

Changes 0
Metric Value
cc 7
eloc 18
nc 2
nop 1
dl 0
loc 38
ccs 15
cts 18
cp 0.8333
crap 7.2269
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Middleware;
6
7
use Phalcon\Mvc\Micro;
8
use Phalcon\Mvc\Micro\MiddlewareInterface;
9
use Baka\Auth\Models\Sessions;
10
use Gewaer\Models\Users;
11
use Gewaer\Exception\UnauthorizedHttpException;
12
use Gewaer\Constants\Flags;
13
14
/**
15
 * Class AuthenticationMiddleware.
16
 *
17
 * @package Niden\Middleware
18
 */
19
class AuthenticationMiddleware extends TokenBase
20
{
21
    /**
22
     * Call me.
23
     *
24
     * @param Micro $api
25
     * @todo need to check section for auth here
26
     * @return bool
27
     */
28 68
    public function call(Micro $api)
29
    {
30 68
        $config = $api->getService('config');
31 68
        $request = $api->getService('request');
32
33 68
        if ($this->isValidCheck($request)) {
34
            /**
35
             * This is where we will find if the user exists based on
36
             * the token passed using Bearer Authentication.
37
             */
38 65
            $data = $this->getToken($request->getBearerTokenFromHeader());
39
40 65
            $api->getDI()->setShared(
41 65
                'userData',
42
                function () use ($config, $data, $request) {
43 65
                    $session = new Sessions();
44
45
                    //all is empty and is dev, ok take use the first user
46 65
                    if (empty($data->getClaim('sessionId')) && strtolower($config->app->env) == Flags::DEVELOPMENT) {
47
                        return Users::findFirst(1);
48
                    }
49
50 65
                    if (!empty($data->getClaim('sessionId'))) {
51
                        //user
52 65
                        if (!$user = Users::getByEmail($data->getClaim('email'))) {
53
                            throw new UnauthorizedHttpException('User not found');
54
                        }
55
56 65
                        $ip = !defined('API_TESTS') ? $request->getClientAddress() : '127.0.0.1';
57 65
                        return $session->check($user, $data->getClaim('sessionId'), (string) $ip, 1);
58
                    } else {
59
                        throw new UnauthorizedHttpException('User not found');
60
                    }
61 65
                }
62
            );
63
        }
64
65 68
        return true;
66
    }
67
}
68