Skip to content

Commit

Permalink
Merge branch 'release/5.3.7'
Browse files Browse the repository at this point in the history
  • Loading branch information
krisanalfa committed Dec 2, 2016
2 parents bee4fb3 + 4bbadb2 commit 7130952
Show file tree
Hide file tree
Showing 14 changed files with 1,379 additions and 382 deletions.
31 changes: 26 additions & 5 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace App\Exceptions;

use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
Expand All @@ -29,8 +31,7 @@ class Handler extends ExceptionHandler
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
* @param \Exception $e
*/
public function report(Exception $e)
{
Expand All @@ -40,18 +41,38 @@ public function report(Exception $e)
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @param \Illuminate\Http\Request $request
* @param \Exception $e
*
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof HttpException) {
return new JsonResponse([
'message' => $e->getMessage(),
'message' => $e->getMessage() ?: $this->getMessageFromClassName($e),
], $e->getStatusCode());
}

return parent::render($request, $e);
}

/**
* Get Message From Class Name.
*
* @param HttpException $e
*
* @return string
*/
protected function getMessageFromClassName(HttpException $e)
{
$class = get_class($e);
$file = Arr::last(explode('\\', $class));

return Str::snake(str_ireplace(
['HttpException', 'Exception'],
['', ''],
$file
));
}
}
106 changes: 76 additions & 30 deletions app/Http/Controllers/Auth/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

namespace App\Http\Controllers\Auth;

use JWTAuth;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Exception\HttpResponseException;
Expand All @@ -22,43 +22,88 @@ class AuthController extends Controller
public function postLogin(Request $request)
{
try {
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);
$this->validatePostLoginRequest($request);
} catch (HttpResponseException $e) {
return new JsonResponse([
'error' => [
'message' => 'invalid_auth',
'status_code' => Response::HTTP_BAD_REQUEST,
],
], Response::HTTP_BAD_REQUEST);
return $this->onBadRequest();
}

$credentials = $this->getCredentials($request);

try {
// Attempt to verify the credentials and create a token for the user
if (!$token = JWTAuth::attempt($credentials)) {
return new JsonResponse([
'error' => [
'message' => 'invalid_credentials',
],
], Response::HTTP_UNAUTHORIZED);
if (!$token = JWTAuth::attempt(
$this->getCredentials($request)
)) {
return $this->onUnauthorized();
}
} catch (JWTException $e) {
// Something went wrong whilst attempting to encode the token
return new JsonResponse([
'error' => [
'message' => 'could_not_create_token',
],
], Response::HTTP_INTERNAL_SERVER_ERROR);
return $this->onJwtGenerationError();
}

// All good so return the token
return $this->onAuthorized($token);
}

/**
* Validate authentication request.
*
* @param Request $request
* @return void
* @throws HttpResponseException
*/
protected function validatePostLoginRequest(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);
}

/**
* What response should be returned on bad request.
*
* @return JsonResponse
*/
protected function onBadRequest()
{
return new JsonResponse([
'success' => [
'message' => 'token_generated',
'message' => 'invalid_credentials'
], Response::HTTP_BAD_REQUEST);
}

/**
* What response should be returned on invalid credentials.
*
* @return JsonResponse
*/
protected function onUnauthorized()
{
return new JsonResponse([
'message' => 'invalid_credentials'
], Response::HTTP_UNAUTHORIZED);
}

/**
* What response should be returned on error while generate JWT.
*
* @return JsonResponse
*/
protected function onJwtGenerationError()
{
return new JsonResponse([
'message' => 'could_not_create_token'
], Response::HTTP_INTERNAL_SERVER_ERROR);
}

/**
* What response should be returned on authorized.
*
* @return JsonResponse
*/
protected function onAuthorized($token)
{
return new JsonResponse([
'message' => 'token_generated',
'data' => [
'token' => $token,
]
]);
Expand Down Expand Up @@ -103,7 +148,9 @@ public function patchRefresh()

return new JsonResponse([
'message' => 'token_refreshed',
'token' => $newToken
'data' => [
'token' => $newToken
]
]);
}

Expand All @@ -115,9 +162,8 @@ public function patchRefresh()
public function getUser()
{
return new JsonResponse([
'success' => [
'user' => JWTAuth::parseToken()->authenticate()
]
'message' => 'authenticated_user',
'data' => JWTAuth::parseToken()->authenticate()
]);
}
}
86 changes: 86 additions & 0 deletions app/Http/Middleware/CORSMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class CORSMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);

if ($this->isPreflightRequest($request)
&& $this->canBeConvertedToPreflightResponse($response)) {
$response = $this->createEmptyResponse();
}

return $this->addCorsHeaders($request, $response);
}

/**
* Determine if request is a preflight request.
*
* @param \Illiminate\Http\Request $request
*
* @return bool
*/
protected function isPreflightRequest($request)
{
return $request->isMethod('OPTIONS');
}

/**
* Determine if response is not an error.
*
* @param \Illiminate\Http\Response $response
*
* @return bool
*/
protected function canBeConvertedToPreflightResponse($response)
{
return ($response->isSuccessful() || $response->isClientError())
&& !$response->isNotFound();
}

/**
* Create empty response for preflight request.
*
* @return \Illiminate\Http\Response
*/
protected function createEmptyResponse()
{
return new Response(null, 204);
}

/**
* Add CORS headers.
*
* @param \Illiminate\Http\Request $request
* @param \Illiminate\Http\Response $response
*/
protected function addCorsHeaders($request, $response)
{
foreach ([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Max-Age' => (60 * 60 * 24),
'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers'),
'Access-Control-Allow-Methods' => $request->header('Access-Control-Request-Methods')
?: 'GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS',
'Access-Control-Allow-Credentials' => 'true',
] as $header => $value) {
$response->header($header, $value);
}

return $response;
}
}
7 changes: 1 addition & 6 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace App\Providers;

use Illuminate\Cache\CacheManager;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
Expand All @@ -14,10 +13,6 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
$this->app->singleton([CacheManager::class => 'cache'], function ($app) {
$app->configure('cache');

return new CacheManager($app);
});
//
}
}
12 changes: 6 additions & 6 deletions app/Providers/AuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class AuthServiceProvider extends ServiceProvider
*/
public function register()
{
$this->app->alias('auth', 'Illuminate\Auth\AuthManager');
//
}

/**
Expand All @@ -30,10 +30,10 @@ public function boot()
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.

// $this->app['auth']->viaRequest('api', function ($request) {
// if ($request->input('api_token')) {
// return User::where('api_token', $request->input('api_token'))->first();
// }
// });
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
}
}
12 changes: 6 additions & 6 deletions app/Providers/GuardServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ class GuardServiceProvider extends ServiceProvider
*/
public function register()
{
// $this->app->make('auth')->extend('api', function ($app, $name, array $config) {
// return new ApiGuard(
// $app->make('auth')->createUserProvider($config['provider']),
// $app->make('request')
// );
// });
$this->app->make('auth')->extend('api', function ($app, $name, array $config) {
return new ApiGuard(
$app->make('auth')->createUserProvider($config['provider']),
$app->make('request')
);
});
}
}
Loading

0 comments on commit 7130952

Please sign in to comment.