How can I throw a 403 exception in Symfony2? - php

I am doing a check if there is a specific token in my request URI and throw a Symfony\Component\Security\Core\Exception\AccessDeniedException if there is no token or the token is wrong.
if(!isset($token) && $token != 'whatever') {
throw new AccessDeniedException('No token given or token is wrong.');
}
But when I use this AccessDeniedException, Symfony2 simply redirects to the login page. Instead, I would like to have a dedicated 403 error page (I already created app/Resources/TwigBundle/views/Exceptions/error403.html.twig file).
What would I have to change in order to achieve this? Do I have to use a PHP native Exception? But how can I tell to pass a 403 error code?
Does Symfony2 maybe have a specific 403-Exception which doesn't simply redirect to login?

Throw Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException.
That will bypass the security system and give you a 403 response which in turn will get picked up by the twig exception listener.

As of Symfony 2.6 you can use the following controller shortcut that will trigger the good exception for you:
return $this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');

Related

Customize Laravel FormRequest autorize method validation

Laravel allows us to authorize, or not, a FormRequest to be processed via the authorize method. If the request isn't authorized, it will throw a \Illuminate\Auth\Access\AuthorizationException exception, with a message:
This action is unauthorized.
Is there somehow to customize this message?
See that I want to customize the message itself. Customizing the error messages of attributes I know it is possible!
To change the message you can add the following to your FormRequest class.
protected function failedAuthorization()
{
throw new AuthorizationException('Your new message goes here.');
}
if you are trying to customise the message authourization exceptional message then use throw new exception in authorization controller itself in else part

Symfony 3 exceptions without error 500

Is possible in symfony 3 to generate exception without internal server error?
I want do something action with this exception (add to databases) but do not stop execute application.
I assume what you want to do is not simply catch an exception, but handle (in your case: log) an uncatched exception.
This is a common scenario and is therefore explained in the cookbook. Basically, you create an event listener class which you register as a service for the “kernel.event_listener” event.
I was struggling with this as well because I was generating custom built exceptions, but no matter what I did Symfony would return an http status of 500. I was handling errors in a controlled fashion, and just needed to notify the user, which was more of a status 200 response since it was a message to the user.
Anyways I found that this didn't work:
$event->setResponse(new Response(json_encode($returnArray), 200));
But if I added a header it works, Symfony looks for this header later and respects it. Without the header Symfony just assigns a 500 if you use an /Exception instead of an /HttpException
$event->setResponse(new Response(json_encode($returnArray), 200, array('X-Status-Code' => 200)));
I'm still new to this exception thing, so let me know if something I'm doing is wrong, but that header fixed my problems.

When to use abort(404) in Laravel?

I am wanting to create a registration verification,
So far I have planned out, that my Users table should have a confirmation_code column, and an confirmed column. The confirmed column has a default value of 0 (boolean false).
I create the new User from registration and assign them a confirmation_code.
I then email them a link to the verify route, which expects this confirmation_code in the query string.
The method which handles the verify request will be checking to see if the query string parameter (confirmation_code) exists.
My question is :
If the confirmation_code is absent, should I use the abort(404) method? Or throw a custom exception?
public function verify($confirmation_code)
{
if ( ! $confirmation_code ) {
// abort(404)?
// or,
// throw new Exception?
}
Some feedback on when to use the abort method would be appreciated too.
It's actually your choice to choose what type of error handling and error logging you implement in your project.
As advice, I will say that using custom exceptions for missing field exceptions. is a better idea. You can read more about a 404 error in the given link:
404 error.
Also refer to laravel documentation for more details regarding error logging.

Laravel Handle Exceptions

I am using the Stripe API and Laravel together. If Stripe detects an error charging the card (such as using a test credit card number that throws an invalid security code error), the API bindings are supposed to throw an exception, which they do. The problem is, I am having issues catching the exception before Laravel throws up the error 500 page (I am trying to perform a redirect with an error message instead).
The code I've written is available on Pastebin: http://pastebin.com/ZaW2xbbt
The behavior I'm expecting is for the catch to fire and the redirect to be performed, but instead, I get the stack trace with the message and "Unhandled Exception". That's confusing me because I am handling the exception.
Variables such as $customer are valid and have been defined previously. Any ideas what's going on?
For any future viewers, here's an article on error handling in laravel 4.
Laravel 4 lets you catch Exceptions by exception type. For instance, you can handle Symfony's HttpException and of its sub-classes by adding this to your code:
// Catch HttpException, NotFoundHttpException, etc etc
App::error(function(HttpException $exception, $code, $fromConsole)
{
...
});
Symfony HttpExceptions (used in Laravel) can be found here.
You can also throw this in a ServiceProvider:
<?php namespace My\Namespace;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\HttpKernel\Exception\HttpException;
class MyServiceProvider extends ServiceProvider {
public function register()
{
$this->app->error(function(HttpException $exception, $code, $fromConsole)
{
...
});
}
}
Hope that helps!
Generally, all errors logged by Laravel are logged under storage/logs folder
Anyway, the 500 error could be a syntax/parse error, in such case the Laravel framework could be not yet loaded when the error occurs and if so, the exception is not lhandled by Laravel.
In this case you should access the apache/vargrant/whatif php error log in some way (dependently on your server capabilities and configuration), in my personal cases I have configured the server to put that logs in a /storage/logs/error_log.txt file such that I can access them as other Laravel server logs
Note that in Laravel 5, you have app/Exceptions/Handler.php as entry point for customize exception handling/reporting
https://laravel.com/docs/5.7/errors#the-exception-handler

Catching Kohana_Request_Exception in Kohana v3 during execution -- unexpected behaviour

As detailed here: Need assistance with Kohana 3 and catch all route turning into a 404 error as the accepted answer to the question, I'm attempting to catch errors thrown by Kohana to display pretty error pages and send correct HTTP codes.
Here's a simplified version to demonstrate the problem:
try {
// Instantiate your Request object
$request = Request::instance();
// The give it a try, to see if its a valid request
$request->execute();
}
catch (Kohana_Request_Exception $e) {
header('Content-Type: text/html; charset='.Kohana::$charset, TRUE, 404);
echo Request::factory('err/404')->send_headers()->execute()->response;
exit;
}
echo $request->send_headers()->response;
So I navigate to a non-existent URL such as http://example.local/moo/ and I get the following response
Kohana_Request_Exception [ 0 ]: Unable to find a route to match the URI: moo
Here is what's happening-- The request is being tried, failing with a Kohana_Request_Exception, it's being caught BUT when I try to build a new request object, Request::factory('err/404') THAT request throws the error from my first request....!? wtf??
I've fiddled with it for a good hour and am as puzzled as when I started. Shouldn't the new request from the factory have no knowledge of the old request?? Why is this code malfunctioning when I essentially copied it from the d00d's answer?
// Release version and codename
const VERSION = '3.0.7';
const CODENAME = 'hattrick';
Someone point me in the right direction.. thx guys.
It's because within Request::factory('err/404'), the err/404 part is a URL that is trying to be matched by your routes as well. Will it ever match, i.e. do you have a route with something like this...
Route::set('errors', 'err/<action>', array('action' => '404|500')) {}
You should also be sending a 404 via...
$request->status = 404;
Aha! Thanks guys but I got it figured.. I shoulda looked at the stack trace a little closer, the error page's template controller's before() method was throwing a new error as it was attempting to check authentication using Request::instance()I changed it to Request::current() and it's all shiny.
Thanks for the help!

Categories