Completed
Push — master ( ad8d22...12c7dd )
by Temitope
02:40
created

Oauth::logoutUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 1 Features 1
Metric Value
c 8
b 1
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 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
                $this->runRegisterUser($user, $userParams, $response)
45
            }
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected '}'
Loading history...
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
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
116
     */
117
    public function logoutUser(Request $request, Response $response, $args)
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();
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