Completed
Push — master ( 0f1d25...bd39e2 )
by Temitope
02:35
created

Oauth   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 175
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Importance

Changes 22
Bugs 10 Features 5
Metric Value
wmc 16
c 22
b 10
f 5
lcom 0
cbo 8
dl 0
loc 175
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
A verifyUserRegistration() 0 15 4
B buildAcessToken() 0 34 1
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
                $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
     * @param array $loginParams
0 ignored issues
show
Bug introduced by
There is no parameter named $loginParams. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
84
     *
85
     * @return json jwt
86
     */
87
    public function loginUser(Request $request, Response $response)
88
    {
89
        $loginParams = $request->getParsedBody();
90
91
        if (is_array($loginParams)) {
92
            $user = User::where('username', '=', $loginParams['username'])->get()->first();
93
94
            if (count($user) > 0) {
95
                $userInfo = ['id' => $user->id, 'username' => $user->username, 'email' => $user->email];
96
97
                if (password_verify($loginParams['password'], $user->password)) {
98
                    $token = $this->buildAcessToken($userInfo);
99
100
                    return $response->withAddedHeader('HTTP_AUTHORIZATION', $token)
101
                    ->withStatus(200)
102
                    ->write($token);
103
                }
104
            }
105
106
            return $response->withJson(['message' => 'Login credentials incorrect'], 400);
107
        }
108
    }
109
110
    /**
111
     * This method logout the user.
112
     *
113
     * @param $args logout
114
     *
115
     * @return $reponse
0 ignored issues
show
Documentation introduced by
The doc-type $reponse could not be parsed: Unknown type name "$reponse" 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...
116
     */
117
    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...
118
    {
119
        return $response->withJson(['message' => 'Logout successful'], 200);
120
    }
121
122
    /**
123
     * This method verifies a registered user.
124
     *
125
     * @param $email
126
     * @param $username
127
     *
128
     * @return bool true
129
     */
130
    public function verifyUserRegistration($username, $email)
131
    {
132
        if (isset($username) && isset($email)) {
133
            $userFound = Capsule::table('users')
134
            ->Where('username', '=', strtolower($username))
135
            ->orWhere('email', '=', strtolower($email))
136
            ->get();
137
138
            if (count($userFound) > 0) {
139
                return true;
140
            }
141
        }
142
143
        return false;
144
    }
145
146
    /**
147
     * This method builds an access token for a login user;.
148
     *
149
     * @param $userData
150
     *
151
     * @return string $token
152
     */
153
    public function buildAcessToken(array $userData)
154
    {
155
        $tokenId = base64_encode(mcrypt_create_iv(32));
156
        $issuedAt = time();
157
        $notBefore = $issuedAt;
158
        $expire = (float) strtotime('+30 days'); // Adding 30 days expiry date
159
        $serverName = 'http://localhost:8000/emojis'; // the server name
160
161
        /*
162
         *
163
         * Create the token params as an array
164
         */
165
        $data = [
166
            'iat'  => $issuedAt,         // Issued at: time when the token was generated
167
            'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
168
            'iss'  => $serverName,       // Issuer
169
            'nbf'  => $notBefore,        // Not before
170
            'exp'  => $expire,           // Expire
171
            'dat'  => $userData,          // User Information retrieved from the database
172
        ];
173
174
        $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...
175
176
        $secretKey = base64_decode(getenv('secret'));
177
178
        $jwt = JWT::encode(
179
        $data,      //Data to be encoded in the JWT
180
        $secretKey, // The signing key
181
        'HS512'     // Algorithm used to sign the token
182
        );
183
        $unencodedArray = ['jwt' => $jwt];
184
185
        return json_encode($unencodedArray);
186
    }
187
}
188