Failed Conditions
Push — master ( 55bfad...b74acd )
by Maximo
02:48
created

AuthenticationMiddleware::call()   B

Complexity

Conditions 8
Paths 1

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8.0877

Importance

Changes 0
Metric Value
cc 8
eloc 18
nc 1
nop 1
dl 0
loc 34
ccs 16
cts 18
cp 0.8889
crap 8.0877
rs 8.4444
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 Phalcon\Http\Request;
12
use Gewaer\Exception\UnauthorizedHttpException;
13
use Gewaer\Constants\Flags;
14
15
/**
16
 * Class AuthenticationMiddleware
17
 *
18
 * @package Niden\Middleware
19
 */
20
class AuthenticationMiddleware implements MiddlewareInterface
21
{
22
    /**
23
     * Call me
24
     *
25
     * @param Micro $api
26
     * @todo need to check section for auth here
27
     * @return bool
28
     */
29 37
    public function call(Micro $api)
30
    {
31 37
        $auth = $api->getService('auth');
32 37
        $config = $api->getService('config');
33
34
        // to get the payload
35 37
        $data = $auth->data();
36
37 37
        $api->getDI()->setShared(
38 37
            'userData',
39
            function () use ($config, $data) {
40 27
                $session = new Sessions();
41 27
                $request = new Request();
42
43
                //all is empty and is dev, ok take use the first user
44 27
                if (empty($data) && empty($data['sessionId']) && strtolower($config->app->env) == Flags::DEVELOPMENT) {
45 2
                    return Users::findFirst(1);
46
                }
47
48 26
                if (!empty($data) && !empty($data['sessionId'])) {
49
                    //user
50 26
                    if (!$user = Users::getByEmail($data['email'])) {
51
                        throw new UnauthorizedHttpException('User not found');
52
                    }
53
54 26
                    $ip = !defined('API_TESTS') ? $request->getClientAddress() : '127.0.0.1';
55 26
                    return $session->check($user, $data['sessionId'], (string) $ip, 1);
56
                } else {
57
                    throw new UnauthorizedHttpException('User not found');
58
                }
59 37
            }
60
        );
61
62 37
        return true;
63
    }
64
}
65