Symfony2 logging 404 errors - http-status-code-404

I need to be able to log/receive an email when a 404 error occurs. I can see in the docs how to set up a new template for these errors, but how do I catch them in the first place in my controller so that I can implement the logging/emailing logic?

Maybe adding an event listener listening for the kernel.exception event would do it?
Check out http://symfony.com/doc/current/book/internals.html#kernel-exception-event along with http://symfony.com/doc/current/reference/dic_tags.html#dic-tags-kernel-event-listener
A little example:
1) Create a custom Listener
//bundles/Acme/AcmeBundle/Listener/CustomListener.php
namespace Acme\AcmeBundle\Listener;
use Symfony\Component\EventDispatcher\Event;
public class CustomListener {
public function onKernelException(Event $event) {
//Get hold of the exception
$exception = $event->getException();
//Do the logging
// ...
}
}
2) Add the listener to your config
//config.yml
services:
kernel.listener.your_listener_name:
class: Acme\AcmeBundle\Listener\CustomListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
To get hold of the logging or mailing (Swiftmailer) services, you might consider injecting them into the listener (http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services)

Related

how to add custom validation message in suitecrm api

I configure json api in my suitecrm and now i want to add validation mandatory fields for some parameter please suggest me how to add validation and custom message.
I tried to add validation but can't get success is any idea how to configure validation message display
Use before_save logic hooks in that module in which you want to add validation then create you own method to check validation e.g. for checking pan number you can use pan regix then apiException
Hello try this one to your custom api controller
here`s my sample custom/application/Api/V8/Controller/CustomController.php
namespace Api\V8\Controller;
use Slim\Http\Request;
use Slim\Http\Response;
class CustomController extends BaseController
{
public function saveLeads(Request
$request, Response $response, array $args)
{
try {
$jsonResponse = $request->getParams();
$leadBean = \BeanFactory::newBean('Leads');
if(empty(jsonResponse['name'])
{
$resultMessage['Error'] = 'Please filled up the Name';
}else{
$leadBean->name = jsonResponse['name'];
$leadBean->save();
$resultMessage['Succes'] = Leads Has been created';
}
return $this->generateResponse($response, $resultMessage, 201);
} catch (\Exception $exception){
return $this->generateErrorResponse($response, $exception, 400);
}
}

Auth.afterIdentify is not firing

I need to change something in the user session after it was started. This is temporary, so using an event such as Auth.afterIdentify is what I'm looking for.
What I tried
I have largely referred to this answer on how to even approach this.
I have tried using an anonymous function callback as well as a controller callback method
Following the Auth.afterIdentify documentation I have added implementedEvents
Made sure implementedEvents has a + parent::implementedEvents(), otherwise the controller kept showing me the home page
What I have
Here's my current src/Controller/AppController.php:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller implements \Cake\Event\EventListenerInterface
{
public function initialize()
{
parent::initialize();
// …
$this->loadComponent('Authentication.Authentication');
// Trying with an anonymous function
\Cake\Event\EventManager::instance()->on('Auth.afterIdentify', function ($event) {
Log::write( // noticed when posting this question, should have thrown an error
'info',
'Testing: ' . $event->getSubject()->id
);
debug($event);exit;
});
// Trying a controller callback
\Cake\Event\EventManager::instance()->on('Auth.afterIdentify', [$this, 'afterIdentify']);
}
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
$this->set('myAuth', $this->Authentication->getResult());
$this->set('myUser', $this->Authentication->getIdentity());
}
public function afterIdentify(CakeEvent $cakeEvent, $data, $auth) {
debug([
'$cakeEvent' => $cakeEvent,
'$data' => $data,
'$auth' => $auth,
]);exit;
}
public function implementedEvents()
{
return [
'Auth.afterIdentify' => 'afterIdentify',
] + parent::implementedEvents();
}
}
What doesn't work
It seems neither of the above event listeners is being called. No CakePHP logs are being updated (not even with errors), although they normally work.
What I expected to happen
Calling Log::write without declaring where it comes from should have thrown (and logged) an error
The debug() information was not displayed
Removing the public function afterIdentify method should have caused an error; it didn't – meaning the controller isn't even looking for it
You are mixing up the old auth component and the new authentication plugin, the Auth.afterIdentify event belongs to the former.
The authentication plugin's authentication component has a Authentication.afterIdentify event, but this only applies to authenticators that are stateful and do not implement automatic persisting. So out of the box this only applies to the Form authenticator, and the event is being triggered once on the request where the user was authenticated via the form, on subsequent requests where they are authenticated via for example the Session authenticator, the event is not being triggered.
public function initialize()
{
parent::initialize();
// ...
$this->loadComponent('Authentication.Authentication');
$this->Authentication->getEventManager()->on(
'Authentication.afterIdentify',
function (
\Cake\Event\EventInterface $event,
\Authentication\Authenticator\AuthenticatorInterface $provider,
\Authentication\IdentityInterface $identity,
\Authentication\AuthenticationServiceInterface $service
) {
// ...
$identity['foo'] = 'bar';
$this->Authentication->setIdentity($identity);
}
);
}

CefSharp: Injecting custom CSS File using a custom scheme

I'm using CefSharp (47) to render a webpage from a host that I have no control over, and I want to make some additional CSS tweaks to those provided by the host.
Reading up on various topics across GitHub (https://github.com/cefsharp/CefSharp/blob/cefsharp/47/CefSharp.Example/CefSharpSchemeHandlerFactory.cs), and here (CefSharp custom SchemeHandler), I wrote a custom scheme handler accordingly:
public class CustomSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "custom";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
Console.WriteLine(request.Url);
if (schemeName.ToLower() == SchemeName.ToLower())
{
// Do some stuff
}
return null;
}
}
I attempt to bind it in my application in the following manner:
CefSettings settings = new CefSettings();
settings.CachePath = browserCachePath;
settings.RegisterScheme(new CefCustomScheme()
{
SchemeName = CustomSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomSchemeHandlerFactory()
});
Cef.Initialize(settings);
The application then browses to the appropriate website, and uses the 'LoadingStateChanged' event to then fire off some JavaScript to inject the CSS file I want to load:
string linkText = "<link rel=\u0022stylesheet\u0022 type=\u0022text/css\u0022 href=\u0022custom://custom.css\u0022>";
var jsFunctionText = string.Format("(function() {{ $('head').append('{0}'); return true;}}) ();", linkText);
var injectionTask = await _myBrowser.GetMainFrame().EvaluateScriptAsync(jsFunctionText, null);
...which succeeds.
But my custom resource handler 'Create' event is never fired.
I can only presume that the handler isn't being registered properly, so I'd appreciate any advice/help in getting this working properly!
Thanks!

Laravel: resetting password without getting redirect response

I am building an angular application and want to implement password reset. However, default laravel config doesn't appear to allow one to do this using purely XMLHttpRequest ($http.post) requests and responds with a 302 redirect.
I managed to get postLogin and postRegister to work without issuing redirects by implementing said methods in authController class and returning a json response, doing this overrides the default laravel implementation of said methods. No such luck with postEmail and it appears the method is not hit at all, I just get a 302 response back immediately.
Ideally, other than to check their E-mail, I don't want the user to leave the single page angular application at all.
So 1. User posts E-mail to postEmail -> Email with reset link or better 'reset code' is sent to E-mail address -> User then inputs the reset token code into the already open web app or if it can't be done, browse to reset password page opened in new tab.
I tried implementing postEmail method as such:
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return response()->json(['msg' => 'A reset link has been sent to your E-mail'], 200);
case Password::INVALID_USER:
return response()->json(['msg' => 'This E-mail cannot be found in our system'], 200);
}
}
Also, where is template for the E-mail with the reset link that laravel sends out ?
You can create a PasswordController within the App\Http\Controllers\Auth namespace to extend the password reset methods.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
public function postEmail(Request $request)
{
}
}
To overwrite the email templates you can create a reminder.blade.php in the app/views/emails/auth directory, or change the location of the template file in the app/config/auth.php config.
while the accepted answer is completely valid, another solution without overriding the original notification class is as follows, ResetPassword provides a static method called createUrlUsing which accepts a Closure, So we can override the URL as something like the below:
use Illuminate\Support\Facades\Password;
use Illuminate\Auth\Notifications\ResetPassword;
...
$status = Password::sendResetLink(
['email' => $args['email']],
function ($user, $token) {
ResetPassword::createUrlUsing(function ($notifiable, $token) {
// This is where you override the URL, you can also take a look at
// the `url`, `action` and `route` functions in Laravel and skip
// `sprintf` if you prefer to stick to Laravel functions only.
return sprintf(
"%s/%s/?token=%s&email=%s",
config('your.optional.frontend_url'),
config('your.optional.password_reset'),
$token,
$notifiable->getEmailForPasswordReset(),
); // frontend_url/password_url/?token=TOKEN&email=EMAIL
});
return $user->notify(new ResetPassword($token));
}
);
// This is an optional way to handle the final response, you can convert it to
// JSON or ignore it.
return $status === Password::RESET_LINK_SENT
? ['status' => __($status)]
: throw new Error(__($status));
This piece of code should be placed at a new route to handle password reset requests instead of using the default Laravel one.

SignalR doesn't push message to client

I am implementing functionality to notify the user of long running job completions using SignalR in an AngularJS application.I have created groups of user based on their name,so for each user a group of his name and different connectionids which he has opened up will be created and he would be notified by his group. I want to notify the user on two pages i.e. landing Page and Job Run Page as even if the user is on landing page and job run completes he should be notified of it.
For the same reason i am creating group by his name on both the pages,so that if he is on any page he would be nofied through the group.
On landing page controller js file i have written code to add the user in group as follow...
$rootScope.signalRHub = $.connection.signalRHub;
$rootScope.hubStart = null;
$rootScope.startHub = function () {
if ($rootScope.hubStart == null)
{
$rootScope.hubStart = $.connection.hub.start();
}
return $rootScope.hubStart;
}
$scope.$on('$locationChangeStart', function (event) {
if ($rootScope.userName != "") {
$rootScope.signalRHub.server.leaveGroup($rootScope.userName);
}
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName);
});
on Job Run controller js file i have written following code....
$rootScope.signalRHub.client.showNotification = function (message) {
notify('Your notification message');//notify is the angular js directive injected in this controller which runs fine
};
$scope.$on('$locationChangeStart', function (event) {
$rootScope.signalRHub.server.leaveGroup($rootScope.studyid);
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName
});
My Hub File.....
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class SignalRHub : Hub
{
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
public void ShowNotification(string jobRunDetailId, string userName)
{
if (!string.IsNullOrEmpty(userName))
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHub>();
context.Clients.Group(userName).showNotification(jobRunDetailId);
}
}
}
The issue is when i run the application the group add functionality for both pages works fine.but when i call "showNotification" from Hub it doesn't show any message.
But strange thing is if i comment the "$rootScope.startHub().done...." function on landing page then the jobrun page notify functionality works fine.I am not sure if writing "$rootScope.startHub().done()..." on two places is creating this problem.please help.
You need to wire up all callbacks before calling start. If you turn client side logging on, it'll tell you what hubs you are subscribed to.
Aside:
[EnableCors] is a webapi specific attribute that does not work in SignalR.

Resources