Skip to content

Commit

Permalink
feat: handle errors in production (#801)
Browse files Browse the repository at this point in the history
  • Loading branch information
asbiin authored May 21, 2021
1 parent ffd18e4 commit c060b00
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 95 deletions.
25 changes: 12 additions & 13 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@
namespace App\Exceptions;

use Throwable;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Inertia\Inertia;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
Expand All @@ -19,10 +14,6 @@ class Handler extends ExceptionHandler
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];

/**
Expand All @@ -48,11 +39,19 @@ class Handler extends ExceptionHandler
*/
public function render($request, Throwable $e)
{
if ($e instanceof TokenMismatchException) {
return Redirect::route('login');
$response = parent::render($request, $e);

if (! app()->environment('local') && in_array($response->getStatusCode(), [500, 503, 401, 404, 403])) {
return Inertia::render('Error', ['status' => $response->getStatusCode()])
->toResponse($request)
->setStatusCode($response->getStatusCode());
} elseif ($response->getStatusCode() === 419) {
return back()->with([
'message' => trans('errors.message_419'),
]);
}

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

/**
Expand Down
20 changes: 9 additions & 11 deletions app/Http/Controllers/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

use Inertia\Inertia;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
Expand Down Expand Up @@ -37,16 +38,15 @@ public function showLoginForm(): \Inertia\Response
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function authenticated(Request $request, $user)
{
$path = $request->session()->pull('url.intended', route('home'));

return new JsonResponse([
'success' => true,
'redirect' => $path,
]);
return $request->wantsJson()
? Response::json(['success' => true,'redirect' => $path])
: Redirect::intended($path);
}

/**
Expand All @@ -58,10 +58,8 @@ protected function authenticated(Request $request, $user)
*/
protected function sendFailedLoginResponse(Request $request)
{
return new JsonResponse([
'data' => [
trans('auth.login_invalid_credentials'),
],
], 401);
return $request->wantsJson()
? Response::json(['data' => [trans('auth.login_invalid_credentials')]], 401)
: Redirect::back()->with('message', trans('auth.login_invalid_credentials'));
}
}
2 changes: 1 addition & 1 deletion app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class Kernel extends HttpKernel
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Inertia\Middleware::class,
\App\Http\Middleware\HandleInertiaRequests::class,
],

'api' => [
Expand Down
73 changes: 73 additions & 0 deletions app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace App\Http\Middleware;

use Inertia\Middleware;
use Illuminate\Http\Request;
use App\Helpers\InstanceHelper;

class HandleInertiaRequests extends Middleware
{
/**
* The root template that's loaded on the first page visit.
*
* @see https://inertiajs.com/server-side-setup#root-template
* @var string
*/
protected $rootView = 'app';

/**
* Determines the current asset version.
*
* @see https://inertiajs.com/asset-versioning
* @param \Illuminate\Http\Request $request
* @return string|null
*/
public function version(Request $request)
{
return parent::version($request);
}

/**
* Defines the props that are shared by default.
*
* @see https://inertiajs.com/shared-data
* @param \Illuminate\Http\Request $request
* @return array
*/
public function share(Request $request)
{
return array_merge(parent::share($request), [
'auth' => fn () => [
'user' => $request->user() ? [
'id' => $request->user()->id,
'first_name' => $request->user()->first_name,
'last_name' => $request->user()->last_name,
'email' => $request->user()->email,
'name' => $request->user()->name,
'show_help' => $request->user()->show_help,
] : null,
'company' => $request->user() && ! is_null(InstanceHelper::getLoggedCompany()) ? InstanceHelper::getLoggedCompany() : null,
'employee' => $request->user() && ! is_null(InstanceHelper::getLoggedEmployee()) ? [
'id' => InstanceHelper::getLoggedEmployee()->id,
'first_name' => InstanceHelper::getLoggedEmployee()->first_name,
'last_name' => InstanceHelper::getLoggedEmployee()->last_name,
'name' => InstanceHelper::getLoggedEmployee()->name,
'permission_level' => InstanceHelper::getLoggedEmployee()->permission_level,
'display_welcome_message' => InstanceHelper::getLoggedEmployee()->display_welcome_message,
'user' => (! InstanceHelper::getLoggedEmployee()->user) ? null : [
'id' => InstanceHelper::getLoggedEmployee()->user_id,
],
] : null,
],
'help_links' => fn () => config('officelife.help_links'),
'flash' => [
'message' => fn () => $request->session()->get('message'),
'success' => fn () => $request->session()->get('success'),
],
'errors' => fn () => $request->session()->get('errors')
? $request->session()->get('errors')->getBag('default')->getMessages()
: [],
]);
}
}
52 changes: 0 additions & 52 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@

namespace App\Providers;

use Inertia\Inertia;
use App\Helpers\InstanceHelper;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use App\Notifications\EmailMessaging;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\ServiceProvider;
use Illuminate\Auth\Notifications\VerifyEmail;

Expand All @@ -21,7 +17,6 @@ class AppServiceProvider extends ServiceProvider
public function boot(): void
{
Schema::defaultStringLength(191);
$this->registerInertia();

VerifyEmail::toMailUsing(function ($user, $verificationUrl) {
return EmailMessaging::verifyEmailMail($user, $verificationUrl);
Expand Down Expand Up @@ -49,51 +44,4 @@ public function boot(): void
public function register()
{
}

public function registerInertia(): void
{
Inertia::version(function () {
return md5_file(public_path('mix-manifest.json'));
});

Inertia::share([
'auth' => function () {
return [
'user' => Auth::user() ? [
'id' => Auth::user()->id,
'first_name' => Auth::user()->first_name,
'last_name' => Auth::user()->last_name,
'email' => Auth::user()->email,
'name' => Auth::user()->name,
'show_help' => Auth::user()->show_help,
] : null,
'company' => Auth::user() && ! is_null(InstanceHelper::getLoggedCompany()) ? InstanceHelper::getLoggedCompany() : null,
'employee' => Auth::user() && ! is_null(InstanceHelper::getLoggedEmployee()) ? [
'id' => InstanceHelper::getLoggedEmployee()->id,
'first_name' => InstanceHelper::getLoggedEmployee()->first_name,
'last_name' => InstanceHelper::getLoggedEmployee()->last_name,
'name' => InstanceHelper::getLoggedEmployee()->name,
'permission_level' => InstanceHelper::getLoggedEmployee()->permission_level,
'display_welcome_message' => InstanceHelper::getLoggedEmployee()->display_welcome_message,
'user' => (! InstanceHelper::getLoggedEmployee()->user) ? null : [
'id' => InstanceHelper::getLoggedEmployee()->user_id,
],
] : null,
];
},
'help_links' => function () {
return config('officelife.help_links');
},
'flash' => function () {
return [
'success' => Session::get('success'),
];
},
'errors' => function () {
return Session::get('errors')
? Session::get('errors')->getBag('default')->getMessages()
: [];
},
]);
}
}
37 changes: 20 additions & 17 deletions resources/js/Pages/Auth/Login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,20 @@
</div>
<div class="">
<!-- Form Errors -->
<errors :errors="errors" :class="'mb3'" />
<errors :errors="form.errors" :class="'mb3'" />

<form @submit.prevent="submit">
<text-input v-model="form.email"
:name="'email'"
:errors="$page.props.errors.email"
:errors="form.errors.email"
:label="$t('auth.login_email')"
:required="true"
:type="'email'"
:autofocus="true"
/>
<text-input v-model="form.password"
:name="'password'"
:errors="$page.props.errors.password"
:errors="form.errors.password"
type="password"
:label="$t('auth.login_password')"
:required="true"
Expand All @@ -56,6 +56,7 @@
import TextInput from '@/Shared/TextInput';
import Errors from '@/Shared/Errors';
import LoadingButton from '@/Shared/LoadingButton';
import { useForm } from '@inertiajs/inertia-vue3';
export default {
components: {
Expand All @@ -73,32 +74,34 @@ export default {
data() {
return {
form: {
form: useForm({
email: null,
password: null,
},
errors: [],
loadingState: '',
remember: false
}),
errorTemplate: Error,
};
},
computed: {
loadingState() {
return this.form.processing ? 'loading' : '';
}
},
mounted() {
document.title = 'Login';
},
methods: {
submit() {
this.loadingState = 'loading';
axios.post(this.route('login.attempt'), _.assign({}, this.form, { remember: true}))
.then(response => {
this.loadingState = null;
this.$inertia.visit(response.data.redirect);
})
.catch(error => {
this.loadingState = null;
this.errors = error.response.data;
this.form
.transform(data => ({
... data,
remember: this.form.remember ? 'on' : ''
}))
.post(this.route('login'), {
onFinish: () => this.form.reset('password'),
});
},
}
Expand Down
Loading

0 comments on commit c060b00

Please sign in to comment.