Failed Conditions
Pull Request — master (#340)
by Rafael
02:25
created

AuthenticationMiddleware::sessionUser()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
nc 2
nop 4
dl 0
loc 36
ccs 0
cts 16
cp 0
crap 56
rs 8.4106
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Middleware;
6
7
use Phalcon\Mvc\Micro;
8
use Baka\Auth\Models\Sessions;
9
use Canvas\Models\Users;
10
use Canvas\Constants\Flags;
11
use Canvas\Http\Exception\UnauthorizedException;
12
13
/**
14
 * Class AuthenticationMiddleware.
15
 *
16
 * @package Niden\Middleware
17
 */
18
class AuthenticationMiddleware extends TokenBase
19
{
20
    /**
21
     * Call me.
22
     *
23
     * @param Micro $api
24
     * @todo need to check section for auth here
25
     * @return bool
26
     */
27
    public function call(Micro $api)
0 ignored issues
show
Coding Style introduced by
function call() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
28
    {
29
        $config = $api->getService('config');
30
        $request = $api->getService('request');
31
32
        /**
33
         * This is where we will find if the user exists based on
34
         * the token passed using Bearer Authentication.
35
         */
36
        if (!empty($request->getBearerTokenFromHeader())) {
37
            $token = $this->getToken($request->getBearerTokenFromHeader());
38
        } else {
39
            throw new UnauthorizedException('Missing Token');
40
        }
41
42
        $this->sessionUser($api, $config, $token, $request);
43
44
        return true;
45
    }
46
47
    /**
48
     * Get the real from the JWT Token.
49
     *
50
     * @param Micro $api
51
     * @param Config $config
52
     * @param string $token
0 ignored issues
show
Documentation introduced by
Should the type for parameter $token not be object?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
53
     * @param RequestInterface $request
54
     * @throws UnauthorizedException
55
     * @return void
56
     */
57
    protected function sessionUser(Micro $api, Config $config, object $token, RequestInterface $request): void
58
    {
59
        $api->getDI()->setShared(
60
            'userData',
61
            function () use ($config, $token, $request) {
62
                $session = new Sessions();
63
64
                //all is empty and is dev, ok take use the first user
65
                if (empty($token->getClaim('sessionId')) && strtolower($config->app->env) == Flags::DEVELOPMENT) {
66
                    return Users::findFirst(1);
67
                }
68
69
                if (!empty($token->getClaim('sessionId'))) {
70
                    //user
71
                    if (!$user = Users::getByEmail($token->getClaim('email'))) {
72
                        throw new UnauthorizedException('User not found');
73
                    }
74
75
                    $ip = !defined('API_TESTS') ? $request->getClientAddress() : '127.0.0.1';
76
                    return $session->check($user, $token->getClaim('sessionId'), (string) $ip, 1);
77
                } else {
78
                    throw new UnauthorizedException('User not found');
79
                }
80
            }
81
        );
82
83
        /**
84
         * This is where we will validate the token that was sent to us
85
         * using Bearer Authentication.
86
         *
87
         * Find the user attached to this token
88
         */
89
        if (!$token->validate(Users::getValidationData($token->getHeader('jti')))) {
90
            throw new UnauthorizedException('Invalid Token');
91
        }
92
    }
93
94
    /**
95
     * Anonymous user from token.
96
     *
97
     * @param Micro $api
98
     * @param Config $config
99
     * @param string $token
100
     * @param RequestInterface $request
101
     * @return void
102
     */
103
    protected function anonymousUser(Micro $api, Config $config, $token, RequestInterface $request): void
104
    {
105
        $api->getDI()->setShared(
106
            'userData',
107
            function () use ($config, $token, $request) {
108
                /**
109
                 * @todo we need to track session for anonymous user
110
                 */
111
                if ($anonymous = Users::findFirst('-1')) {
112
                    return $anonymous;
113
                }
114
115
                throw new UnauthorizedException(
116
                    strtolower($config->app->env) == Flags::DEVELOPMENT ?
117
                    'No anonymous user configured in the app' :
118
                    'No user found guest'
119
                );
120
            }
121
        );
122
    }
123
}
124