Completed
Push — master ( 5c6c30...bc878e )
by Temitope
02:29
created

Oauth::verifyUserRegistration()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 19
rs 9.2
cc 4
eloc 13
nc 3
nop 2
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 Psr\Http\Message\ResponseInterface as Response;
10
use Psr\Http\Message\ServerRequestInterface as Request;
11
use Illuminate\Database\Capsule\Manager as Capsule;
12
use Laztopaz\EmojiRestfulAPI\UserController;
13
14
class Oauth
15
{
16
17
    /**
18
     * This method register a new user
19
     *
20
     * @param $request
21
     * @param $response
22
     *
23
     * @return json response
24
     */
25
    public function registerUser(Request $request, Response $response)
26
    {
27
        $userParams = $request->getParsedBody();
28
29
        if (is_array($userParams)) {
30
            $user = new UserController();
31
32
            if (!  $this->verifyUserRegistration($userParams['username'], $userParams['email'])) {
33
                $boolResponse = $user->createUser([
34
                    'firstname'  => $userParams['firstname'],
35
                    'lastname'   => $userParams['lastname'],
36
                    'username'   => $userParams['username'],
37
                    'password'   => $userParams['password'],
38
                    'email'      => $userParams['email'],
39
                    'created_at' => date('Y-m-d h:i:s'),
40
                    'updated_at' => date('Y-m-d h:i:s')
41
                ]);
42
43
                if ($boolResponse) {
44
                    return $response->withJson(['message' => 'User successfully created'], 200);
45
                }
46
47
                return $response->withJson(['message' => 'User not created'], 400);
48
            }
49
50
            return $response->withJson(['message' => 'User already exists'], 400);
51
        }
52
53
    }
54
55
    /**
56
     * This method authenticate the user and log them in if the supplied
57
     * credentials are valid.
58
     *
59
     * @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...
60
     *
61
     * @return json jwt
62
     */
63
    public function loginUser(Request $request, Response $response)
64
    {
65
        $loginParams = $request->getParsedBody();
66
67
        if (is_array($loginParams)) {
68
            $user = User::where('username', '=', $loginParams['username'])->get();
69
            $user = $user->first();
70
71
            $userInfo = ['id' => $user->id, 'username' => $user->username, 'email' => $user->email];
72
73
            if (password_verify($loginParams['password'], $user->password)) {
74
                $token = $this->buildAcessToken($userInfo);
75
76
                return $response->withAddedHeader('HTTP_AUTHORIZATION', $token)->withStatus(200)->write($token);
77
            }
78
79
            return $response->withJson(['status'], 400);
80
        }
81
    }
82
83
    /**
84
     * This method logout the user.
85
     *
86
     * @param $args logout
87
     *
88
     * @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...
89
     */
90
    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...
91
    {
92
        return $response->withJson(['message' => 'Logout successful'], 200);
93
    }
94
95
    /**
96
     * This method verifies a registered user
97
     *
98
     * @param $email
99
     * @param $username
100
     *
101
     * @return boolean true
102
     */
103
    public function verifyUserRegistration($username, $email)
104
    {
105
        if (isset($username) && isset($email)) {
106
            $userFound = Capsule::table('users')
107
            ->where('username', '=', strtoupper($username))
108
            ->orWhere('username', '=', strtolower($username))
109
            ->orWhere('username', '=', ucwords($username))
110
            ->where('email', '=', strtoupper($email))
111
            ->orWhere('email', '=', strtolower($email))
112
            ->orWhere('email', '=', ucwords($email))
113
            ->get();
114
115
            if (count($userFound) > 0) {
116
                return true;
117
            }
118
        }
119
120
        return false;
121
    }
122
123
    /**
124
     * This method builds an access token for a login user;.
125
     *
126
     * @param $userData
127
     *
128
     * @return string $token
129
     */
130
    public function buildAcessToken(array $userData)
131
    {
132
        $tokenId = base64_encode(mcrypt_create_iv(32));
133
        $issuedAt = time();
134
        $notBefore = $issuedAt;
135
        $expire = $notBefore + (float) strtotime('+30 days'); // Adding 30 days expiry date
136
        $serverName = 'http://sweatemoji.com/api'; // Retrieve the server name
137
138
        /*
139
         *
140
         * Create the token params as an array
141
         */
142
        $data = [
143
            'iat'  => $issuedAt,         // Issued at: time when the token was generated
144
            'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
145
            'iss'  => $serverName,       // Issuer
146
            'nbf'  => $notBefore,        // Not before
147
            'exp'  => $expire,           // Expire
148
149
            'dat'  => $userData         // User Information retrieved from the database
150
        ];
151
152
        $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...
153
154
        $secretKey = base64_decode(getenv('secret'));
155
156
        $jwt = JWT::encode(
157
        $data,      //Data to be encoded in the JWT
158
        $secretKey, // The signing key
159
        'HS512'     // Algorithm used to sign the token
160
        );
161
        $unencodedArray = ['jwt' => $jwt];
162
163
        return json_encode($unencodedArray);
164
    }
165
166
}
167