Failed Conditions
Pull Request — master (#10)
by Maximo
03:34
created

AuthenticationMiddleware::call()   B

Complexity

Conditions 7
Paths 1

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 15.4039

Importance

Changes 0
Metric Value
cc 7
eloc 18
nc 1
nop 1
dl 0
loc 34
ccs 8
cts 18
cp 0.4444
crap 15.4039
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 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 2
    public function call(Micro $api)
30
    {
31 2
        $auth = $api->getService('auth');
32 2
        $config = $api->getService('config');
33
34
        // to get the payload
35 2
        $data = $auth->data();
36
37 2
        $api->getDI()->setShared(
38 2
            'userData',
39
            function () use ($config, $data) {
40
                $session = new Sessions();
41
                $request = new Request();
42
43
                //all is empty and is dev, ok take use the first user
44
                if (empty($data) && empty($data['sessionId']) && strtolower($config->app->env) == Flags::DEVELOPMENT) {
45
                    return Users::findFirst(1);
46
                }
47
48
                if (!empty($data) && !empty($data['sessionId'])) {
49
                    //user
50
                    if (!$user = Users::getByEmail($data['email'])) {
51
                        throw new UnauthorizedHttpException('User not found');
52
                    }
53
54
                    $ip = $request->getClientAddress();
55
                    return $session->check($user, $data['sessionId'], (string) $ip, 1);
56
                } else {
57
                    throw new UnauthorizedHttpException('User not found');
58
                }
59 2
            }
60
        );
61
62 2
        return true;
63
    }
64
}
65