Oauth   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 173
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Importance

Changes 26
Bugs 12 Features 5
Metric Value
wmc 15
c 26
b 12
f 5
lcom 0
cbo 8
dl 0
loc 173
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
B registerUser() 0 27 4
A runRegisterUser() 0 18 2
B loginUser() 0 22 4
A logoutUser() 0 4 1
B buildAcessToken() 0 34 1
A verifyUserRegistration() 0 15 3
1
<?php
2
/**
3
 * @author   Temitope Olotin <[email protected]>
4
 * @license  <https://opensource.org/license/MIT> MIT
5
 */
6
namespace Laztopaz\EmojiRestfulAPI;
7
8
use Firebase\JWT\JWT;
9
use Illuminate\Database\Capsule\Manager as Capsule;
10
use Psr\Http\Message\ResponseInterface as Response;
11
use Psr\Http\Message\ServerRequestInterface as Request;
12
13
class Oauth
14
{
15
    /**
16
     * This method register a new user.
17
     *
18
     * @param $request
19
     * @param $response
20
     *
21
     * @return json response
22
     */
23
    public function registerUser(Request $request, Response $response)
24
    {
25
        $userParams = $request->getParsedBody();
26
27
        if (is_array($userParams)) {
28
            $user = new UserController();
29
            $emoji = new EmojiController($this);
30
31
            $validateResponse = $emoji->validateUserInput([
32
                'firstname',
33
                'lastname',
34
                'username',
35
                'password',
36
                'email',
37
            ], $userParams);
38
39
            if (is_array($validateResponse)) {
40
                return $response->withJson($validateResponse, 400);
41
            }
42
43
            if (!$this->verifyUserRegistration($userParams['username'], $userParams['email'])) {
44
                return $this->runRegisterUser($user, $userParams, $response);
45
            }
46
47
            return $response->withJson(['message' => 'User already exists'], 400);
48
        }
49
    }
50
51
    /**
52
     * This method creates user.
53
     *
54
     * @param $user
55
     * @param $userParams
56
     * @param $response
57
     *
58
     * @return json $response
59
     */
60
    public function runRegisterUser($user, $userParams, $response)
61
    {
62
        $boolResponse = $user->createUser([
63
            'firstname'  => $userParams['firstname'],
64
            'lastname'   => $userParams['lastname'],
65
            'username'   => strtolower($userParams['username']),
66
            'password'   => $userParams['password'],
67
            'email'      => strtolower($userParams['email']),
68
            'created_at' => date('Y-m-d h:i:s'),
69
            'updated_at' => date('Y-m-d h:i:s'),
70
        ]);
71
72
        if ($boolResponse) {
73
            return $response->withJson(['message' => 'User successfully created'], 201);
74
        }
75
76
        return $response->withJson(['message' => 'User not created'], 400);
77
    }
78
79
    /**
80
     * This method authenticate the user and log them in if the supplied
81
     * credentials are valid.
82
     *
83
     * @return json jwt
84
     */
85
    public function loginUser(Request $request, Response $response)
86
    {
87
        $loginParams = $request->getParsedBody();
88
89
        if (is_array($loginParams)) {
90
            $user = User::where('username', '=', $loginParams['username'])->get()->first();
91
92
            if (count($user) > 0) {
93
                $userInfo = ['id' => $user->id,];
94
95
                if (password_verify($loginParams['password'], $user->password)) {
96
                    $token = $this->buildAcessToken($userInfo);
97
98
                    return $response->withAddedHeader('HTTP_AUTHORIZATION', $token)
99
                    ->withStatus(200)
100
                    ->write($token);
101
                }
102
            }
103
104
            return $response->withJson(['message' => 'Login credentials incorrect'], 400);
105
        }
106
    }
107
108
    /**
109
     * This method logout the user.
110
     *
111
     * @param $args logout
112
     *
113
     * @return $response
0 ignored issues
show
Documentation introduced by
The doc-type $response could not be parsed: Unknown type name "$response" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
114
     */
115
    public function logoutUser(Request $request, Response $response, $args)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
116
    {
117
        return $response->withJson(['message' => 'Logout successful'], 200);
118
    }
119
120
    /**
121
     * This method verifies a registered user.
122
     *
123
     * @param $email
124
     * @param $username
125
     *
126
     * @return bool true
127
     */
128
    public function verifyUserRegistration($username, $email)
129
    {
130
        if (isset($username, $email)) {
131
            $userFound = Capsule::table('users')
132
            ->Where('username', '=', strtolower($username))
133
            ->orWhere('email', '=', strtolower($email))
134
            ->get();
135
136
            if (count($userFound) > 0) {
137
                return true;
138
            }
139
        }
140
141
        return false;
142
    }
143
144
    /**
145
     * This method builds an access token for a login user;.
146
     *
147
     * @param $userData
148
     *
149
     * @return string $token
150
     */
151
    public function buildAcessToken(array $userData)
152
    {
153
        $tokenId = base64_encode(mcrypt_create_iv(32));
154
        $issuedAt = time();
155
        $notBefore = $issuedAt;
156
        $expire = (float) strtotime('+30 days'); // Adding 30 days expiry date
157
        $serverName = 'http://localhost:8000/emojis'; // the server name
158
159
        /*
160
         *
161
         * Create the token params as an array
162
         */
163
        $data = [
164
            'iat'  => $issuedAt,         // Issued at: time when the token was generated
165
            'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
166
            'iss'  => $serverName,       // Issuer
167
            'nbf'  => $notBefore,        // Not before
168
            'exp'  => $expire,           // Expire
169
            'dat'  => $userData,         // User Information retrieved from the database
170
        ];
171
172
        $loadEnv = DatabaseConnection::loadEnv();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $loadEnv is correct as \Laztopaz\EmojiRestfulAP...seConnection::loadEnv() (which targets Laztopaz\EmojiRestfulAPI...seConnection::loadEnv()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
$loadEnv is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
173
174
        $secretKey = base64_decode(getenv('secret'));
175
176
        $jwt = JWT::encode(
177
        $data,      //Data to be encoded in the JWT
178
        $secretKey, // The signing key
179
        'HS512'     // Algorithm used to sign the token
180
        );
181
        $unencodedArray = ['jwt' => $jwt];
182
183
        return json_encode($unencodedArray);
184
    }
185
}
186