Skip to content

Commit eff01d0

Browse files
author
Michael Miscampbell
committed
Adding logic to ensure a valid error message is shown to the user when the login attempt failed.
1 parent 9a708a7 commit eff01d0

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/TokenBasedRestApiModule.php

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
use Firebase\JWT\JWT;
2222
use Rhubarb\Crown\DependencyInjection\Container;
23+
use Rhubarb\Crown\LoginProviders\Exceptions\LoginFailedException;
2324
use Rhubarb\Crown\LoginProviders\LoginProvider;
2425
use Rhubarb\RestApi\Exceptions\MethodNotAllowedException;
2526
use Rhubarb\RestApi\RhubarbApiModule;
@@ -91,24 +92,30 @@ protected function authenticate(Request $request)
9192
$authorizationHeader = $request->getHeader('Authorization');
9293

9394
if (empty($authorizationHeader)) {
94-
return false;
95+
return [false, 'Invalid payload'];
9596
}
9697

9798
$authHeader = $request->getHeader('Authorization')[0];
9899
$loginCredentials = explode(':', base64_decode(str_replace('Basic ', '', $authHeader)), 2);
99100

100101
if (count($loginCredentials) < 2) {
101-
return false;
102+
return [false, 'Invalid payload'];
102103
}
103104

104105
list($user, $password) = $loginCredentials;
105106
try {
106107
/** @var LoginProvider $login */
107108
$login = LoginProvider::getProvider();
108109
$login->login($user, $password);
109-
return $login->loggedInUserIdentifier;
110+
return [true, $login->loggedInUserIdentifier];
110111
} catch (\Exception $exception) {
111-
return false;
112+
$message = '';
113+
114+
if ($exception instanceof LoginFailedException) {
115+
$message = $exception->getPublicMessage();
116+
}
117+
118+
return [false, $message];
112119
}
113120
}
114121

@@ -143,15 +150,18 @@ public function registerRoutes(App $app)
143150
if ($request->getMethod() !== 'POST') {
144151
throw new MethodNotAllowedException();
145152
}
146-
if ($user = $self->authenticate($request)) {
153+
154+
list($status, $authData) = $self->authenticate($request);
155+
156+
if ($status) {
147157
$expiry = new \DateTime();
148158
$expiry->add(new\DateInterval('P1D'));
149159

150160
$data = [
151161
'token' => JWT::encode(
152162
[
153163
'expires' => $expiry->getTimestamp(),
154-
'user' => $user,
164+
'user' => $authData,
155165
],
156166
$self->secret,
157167
$self->algorithm
@@ -163,6 +173,7 @@ public function registerRoutes(App $app)
163173
->withStatus(201, 'Created');
164174
} else {
165175
return $response
176+
->withJson(['message' => $authData])
166177
->withAddedHeader('WWW_Authenticate', 'Basic')
167178
->withStatus(401, 'Access Denied');
168179
}

0 commit comments

Comments
 (0)