Issues (20)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Controllers/AuthController.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * @author: Raimi Ademola <[email protected]>
5
 * @copyright: 2016 Andela
6
 */
7
namespace Demo;
8
9
use Carbon\Carbon;
10
use Firebase\JWT\JWT;
11
use Psr\Http\Message\ResponseInterface as Response;
12
use Psr\Http\Message\ServerRequestInterface as Request;
13
14
class AuthController
15
{
16
    /**
17
     * Login a user.
18
     *
19
     * @param Slim\Http\Request $request
20
     * @param Slim\Http\Response $response
21
     *
22
     * @return json response
23
     */
24
    public function login($request, $response)
25
    {
26
        $userData         = $request->getParsedBody();
27
        $validateResponse = $this->validateUserData(['username', 'password'], $userData);
28
29
        if (is_array($validateResponse)) {
30
            return $response->withJson($validateResponse, 400);
31
        }
32
33
        $user = $this->authenticate($userData['username'], $userData['password']);
34
35
        if (!$user) {
36
            return $response->withJson(['message' => 'Username or Password field not valid.'], 400);
37
        }
38
39
        $issTime = $request->getAttribute('issTime') == null ? time() : $request->getAttribute('issTime');
40
        $token   = $this->generateToken($user->username, $issTime);
41
    
42
        return $response->withAddedHeader('HTTP_AUTHORIZATION', $token)->withStatus(200)->write($token);
43
    }
44
45
    /**
46
     * Generate a token for user with passed Id.
47
     *
48
     * @param int $userId
0 ignored issues
show
There is no parameter named $userId. 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...
49
     *
50
     * @return string
51
     */
52
    private function generateToken($username, $time = null)
53
    {
54
        $time         = $time == null ? time() : $time;
55
        $appSecret    = getenv('APP_SECRET');
56
        $jwtAlgorithm = getenv('JWT_ALGORITHM');
57
        $timeIssued   = $time;
58
        $tokenId      = $appSecret;
59
        $token = [
60
            'iat'     => $timeIssued,   // Issued at: time when the token was generated
61
            'jti'     => $tokenId,          // Json Token Id: an unique identifier for the token
62
            'nbf'     => $timeIssued, //Not before time
63
            'exp'     => $timeIssued + 60 * 60 * 24 * 30, // expires in 30 days
64
            'data'    => [                  // Data related to the signer user
65
                'username'  => $username, // userid from the users tableu;
66
            ],
67
        ];
68
69
        return JWT::encode($token, $appSecret, $jwtAlgorithm);
70
    }
71
72
    /**
73
     * Register a user.
74
     *
75
     * @param Slim\Http\Request  $request
76
     * @param Slim\Http\Response $response
77
     *
78
     * @return json response
79
     */
80
    public function register($request, $response)
81
    {
82
        $requestParams    = $request->getParsedBody();
83
        $validateUserData = $this->validateUserData(['fullname', 'username', 'password'], $requestParams);
84
85
        if (is_array($validateUserData)) {
86
            return $response->withJson($validateUserData, 400);
87
        }
88
89
        $validateEmptyInput = $this->checkEmptyInput($requestParams['fullname'], $requestParams['username'], $requestParams['password']);
90
91
        if (is_array($validateEmptyInput)) {
92
            return $response->withJson($validateEmptyInput, 401);
93
        }
94
95
        if (User::where('username', $requestParams['username'])->first()) {
96
            return $response->withJson(['message' => 'Username already exist.'], 409);
97
        }
98
99
        User::create([
100
            'fullname'   => $requestParams['fullname'],
101
            'username'   => strtolower($requestParams['username']),
102
            'password'   => password_hash($requestParams['password'], PASSWORD_DEFAULT),
103
            'created_at' => Carbon::now()->toDateTimeString(),
104
            'updated_at' => Carbon::now()->toDateTimeString(),
105
        ]);
106
107
        return $response->withJson(['message' => 'User successfully created.'], 201);
108
    }
109
110
    /**
111
     * This method logout the user.
112
     *
113
     * @param $args logout
114
     *
115
     * @return json response
116
     */
117
    public function logout(Request $request, Response $response)
118
    {
119
        $request->getAttribute('users');
120
        return $response->withJson(['message' => 'Logout successful'], 200);
121
    }
122
123
    /**
124
     * Authenticate username and password against database.
125
     *
126
     * @param string $username
127
     * @param string $password
128
     *
129
     * @return bool
130
     */
131
    private function authenticate($username, $password)
132
    {
133
        $user = User::where('username', $username)->first();
134
135
        if (password_verify($password, $user->password)) {
136
            return $user;
137
        }
138
    }
139
140
    /**
141
     * Validate user data are correct.
142
     *
143
     * @param $expectedFields
144
     * @param $userData
145
     *
146
     * @return bool
147
     */
148
    public function validateUserData($expectedFields, $userData)
149
    {
150
        $tableFields = [];
151
        $tableValues = [];
152
153
        foreach ($userData as $key => $val) {
154
            $tableFields[] = $key;
155
            $tableValues[] = $val;
156
        }
157
158
        $result = array_diff($expectedFields, $tableFields);
159
160
        if (count($result) > 0 && empty($userData)) {
161
            return ['message' => 'All fields must be provided.'];
162
        }
163
164
        $tableValues = implode('', $tableValues);
165
166
        if (empty($tableValues)) {
167
            return ['message' => 'All fields are required'];
168
        }
169
170
        foreach ($userData as $key => $val) {
171
            if (!in_array($key, $expectedFields)) {
172
                return ['message' => 'Unwanted fields must be removed'];
173
            }
174
        }
175
176
        return true;
177
    }
178
179
    /**
180
     * This method checks for empty input from user.
181
     *
182
     * @param $inputName
183
     * @param $inputChars
184
     * @param $inputCategory
185
     * @param $inputKeywords
186
     *
187
     * @return bool
188
     */
189
    public function checkEmptyInput($inputFullname, $inputUsername, $inputPassword)
190
    {
191
        if (empty($inputFullname) || empty($inputUsername) || empty($inputPassword)) {
192
            return ['message' => 'All fields must be provided.'];
193
        }
194
195
        return true;
196
    }
197
}
198