Symfony2 - Show bad credentials error - php

I have been writing a custom auth provider in Symfony2. Everything works so far, but when I enter a wrong password a get an Internal Server error displaying: "LDAP authentication failed".
Now, this is the message that I want to display, but I'd like to display it above my login form and NOT throw an internal server error. In my listener, I have the following:
try {
$authToken= $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
throw new BadCredentialsException($failed->getMessage(), 0);
}
So is there anyone who can tell me what I need to do to show the user a message, instead of throwing an internal server error?
Thanks in advance.

You can manually add error to your login form in the controller. For example:
$form->get('username')
->addError(new FormError($message));

You should have a controler action that catch the same path of your form to catch the exception.
authentication process will be tryed before the form will be displayed.
You can see this example :
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Controller/SecurityController.php

Related

Laravel How do I return back with SQL errors displayed in HTML?

The problem
I created a constraint in my SQL database to prevent duplicate entries. The initial laravel form submission works fine. I get back the correct message. When I try to throw a duplicate entry, the app, as expected, throws an error.
This is my Controller. A successful form submission does throw the correct error:
$contact->save();
return redirect('contactus.php')->with('status', 'We received your message. We will get back to you soon.');
return back()->withErrors(['Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.']);
Question
How do I display that error on the HTML screen? Instead of having the page display the following?
Basically the contact form submits information into the database using laravel. When successful, it displays a success message by redirecting it. When not successful, (because of a SQL Unique constraint blocking duplicate entries) so far I've managed to make it throw a SQL error.
How do I display a custom message, like "post not successful, duplicate entry" in that case?
You can do it by using try catch and query exception:
try {
$contact->save();
return redirect('contactus.php')->with('status', 'We received your message. We will get back to you soon.');
} catch(\Illuminate\Database\QueryException $e){
$errorCode = $e->errorInfo[1];
if($errorCode == '1062'){
return back()->with('error', 'Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.');
}
else{
return back()->with('error', $e->getMessage());
}
}
or another way you can find/check the data first, if already exist just send the error. example:
$contact = Contact::where('email',$request->email)->first();
if($contact)
{
return back()->with('error', 'Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.');
}
dont forget to get the error on the form view using like below:
<script>
#if(session()->has('error'))
alert('{{session()->get('error')}}')
#endif
</script>

Laravel Restclient 500 error in api

I wanted to test an laravel api by connecting it with android studio by asyn task but i'm getting HTTP status code 500
Here is my code in AbcController :
public function register_otpsent(Request $req)
{
// $myclass = new MyClasses();
//{cardno}, {mobileno}
$cardno = $req->input('cardno');
$mobileno = $req->input('mobileno');
//
// if(strlen($cardno)==0){
// return response()->json("Please enter valid card number !" , 400);
// }
$cnt = DB::table('acc_status')->where('cardno','=',$cardno)->count();
if($cnt==0){
return response()->json("This card number seems to be wrong !", 400);
}
$accid = DB::table('acc_status')->where('cardno','=',$cardno)->first()->accid;
$pdetails = DB::table('acc_personaldetails')->where('accid','=',$accid)->first();
if($pdetails->mobileno != $mobileno){
return response()->json("This mobile number seems to be not registered !", 400);
}
$otp = mt_rand(100000, 999999);
return response()->json($otp, 200);
}
HTTP Status Code 500 is a server side error (all 5xx are server side)
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
There could be a number of things that could be wrong, it should be basic debugging:
Does input cardno exists in the request? If it doesn't, boom, error
Does input mobileno exists in the request? If it doesn't, boom, error
Do you have use DB; on the top of the page? If it doesn't, boom, error
Do you have use Illuminate\Http\Request on the top of the page? If it doesn't, boom, error
From this piece of code only, I'm guessing it's one of these (assuming the queries are correct and the tables exist). You should try to validate the data you're receiving, otherwise you'll get unexpected results/errors.
To detect this error, you can either:
Access your log files, located in projectdir/storage/logs/laravel.log (or depending on your custom configuration)
Request it with your browser and make sure you have in your .env file, APP_DEBUG = true, so you can see the error.
Wrap the content in a try-catch and on the catch, response()->json($$exception, 200); and check the error on your android studio end
Check with Postman if you want to use POST, PUT, or any other. (that I usually use https://www.getpostman.com/)

Display custom error message in MVC view with PHP

I need to display user friendly error message in the view I am in, and wondering what will be the best solution. I can display and error page using error controller but this is not what i want to achieve. I need to handle all custom error messages in any model and display an error in the view you are in. For example:
I am in "user" controller. When creating new user, the PHP model code checks if same user name exist, if exist I want to display a message in the view or maybe have something like this in header: echo $error; which display any error message I have set to be displayed from any model if occurred.
Example error message in model:
if ($p0 > 0) {
$IsValid = false;
log::LOG_USER_ERROR("This user already exist!", $username);
exit("This user already exist! </br> ");
}
This code write the error in a log file successfully, however how do I display the error message in the same view I am in? exit() displays the message in a blank page. I need to display it as block in red in the same view and design.
exit() terminates the current script, so the code for your View is not executed.
Instead, part of your View should be an area to display messages. Then you can put the error message in a variable (probably an array of messages) that the View displays to the user in that area.

CakePHP Catch Invalid Email

I am trying to send email invitations with CakePHP (2.3.6) where a User enters a comma separated list of email addresses into an input field.
Currently, I can send emails without an issue as long as there is no invalid email address. However, I tried adding a Try/Catch to catch errors if there was a bad email, but my code is never hitting the catch.
Here is what I have
try {
if($Email->send()) {
$this->Session->setFlash(__('Email successfully sent'), 'flash/success');
} else {
$this->Session->setFlash(__('Could not invite guests. Please, try again.'), 'flash/error');
$this->redirect($this->referer());
}
} catch(Exception $e) {
$this->Session->setFlash(__('Could not invite guests. Probably a bad email. Please, try again.'), 'flash/error');
$this->redirect($this->referer());
}
$this->redirect($this->referer());
When I enter an invalid email with debugging on, I get the following error:
Invalid email: "foo"
Error: An Internal Error Has Occurred.
And when debugging is off:
An Internal Error Has Occurred.
I assumed there is something wrong with my Try / Catch, but it looks right to me. Is there some other method I should be going through to catch CakePHP errors?
Thanks in advance!!
Invalid email addresses cause the exception to be thrown right away when they are set. This occurs before the send method is called, so it is not reaching the try block you posted.
This is from a component I have written that handles sending several different emails for our system here. I have wrapped each address setting in a try block so the offending address can be more easily tracked down, but if you did not want that much detail you could wrap all of them in a single block. You can examine the message from the exception with the getMessage method to see the offending address string. This works for me with Cake 2.3:
$email = new CakeEmail();
//...
// set to for email
try
{
$email->to($recipient);
}
catch(SocketException $e)
{
$result['problem'] = 'Recipient Address';
$result['message'] = $e->getMessage();
return $result;
}
// set cc for email - not required
try
{
if($cclist != '') $email->cc(preg_split('/, */', $cclist));
}
catch(SocketException $e)
{
$result['problem'] = 'CC List';
$result['message'] = $e->getMessage();
return $result;
}
Check where exactly the exception causing this error is thrown, it is most likely not in the try block you've posted, but in one of the CakeEmail methods (from, sender, replyTo, etc...) that validates the address.
That being said, you should probably either wrap the single CakeEmail method calls into try catch blocks (in case you want to respond with proper error messages depending on which value exactly is wrong), or maybe use a single one that wraps all operations and output a generic error message.
Also note that CakeEmail::send() returns an array (containing header and message data), not a boolean, determining whether an E-Mail was send successfully must be done using try...catch, ie when no exception is being thrown, then the E-Mail was probably sent successfully.
Unfortunately the Cookbook is missing some proper examples. Here's some untested example code that should illustrate how it might work:
$Email = new CakeEmail();
try
{
$Email->from($from);
$Email->to($to);
// etc...
try
{
$Email->send();
$this->Session->setFlash(__('Email successfully sent'), 'flash/success');
}
catch(SocketException $e)
{
$this->Session->setFlash(__('Could not invite guests. Please, try again.'), 'flash/error');
}
}
catch(SocketException $e)
{
$this->Session->setFlash(__('Bad input'), 'flash/error');
}
$this->redirect($this->referer());

CodeIgniter custom 404 message

I am trying to display an error message on CodeIgniter error page. I am trying this:
Controller/entries.php
public function show_entry()
{
$id = $this->uri->segment(3);
if ($id !== FALSE)
{
..
}
else
{
log_message('error', 'The post ID is missing.');
}
Shouldnt this display my error message 'The post ID is missing' on the CodeIgniter's default 404 error message ie. "The page you requested was not found."
No. The logging class is for writing messages to a log file (ideally somewhere that the user can't read it as it can have information on the inner-workings of your cite). It is something which is really beneficial to you above all.
To display a custom error message, you'll need to either use show_error or, probably more likely in this case, show_404 (both methods documented here).

Categories