cakephp email object notify on failure - cakephp

I have this code in my cakephp 2 installation to send out emails
if($Email->template('invitation', 'default')
->emailFormat('html')
->from(array('no-reply#domain.com' => 'MyHospitals'))
->to($email)
->subject($subject)
->send()){
This works fine as long as smtp settings and everything is fine. However if someone changes the password, this fails miserably ....is there a check I can add that will tell me that $Email object was formatted correctly so that if it was not, I can kill it gracefully instead of having errors showing up on the page
thanks

try {
if ($Email->template('invitation', 'default')
->emailFormat('html')
->from(array('no-reply#domain.com' => 'MyHospitals'))
->to($email)
->subject($subject)
->send()) {
// Do success stuff
} else {
// Handle failure (no exception thrown)
}
} catch (Exception $e) {
// Handle exceptions
}

Related

Showing error message on MEAN website

I am quite new to MEAN and I am learning a lot. At the moment I am trying to show an error message on my page when an user is not allowed into the website. The page contains a button which redirects you to the steam login. After you login the steam API sends your steamid which I will then check in the mongodb database:
app.get('/auth/steam/return',
passport.authenticate('steam', { failureRedirect: '/' }),https://stackoverflow.com/users/5333805/luud-van-keulen
function(req, res) {
UserModel.findOne({ steamid : req.user.id }, function (err, user) {
if(!user) {
console.log('does not exist');
//Probably have to set the error message here
} else {
req.session.userid = req.user.id; //Setting the session
}
});
res.redirect('/');
});
The only thing that I can't get working is how to show a message when the user is not allowed (he is not in the database). I want to use AngularJS for the HTML (so no Jade).
I do know that I have to set a variable somewhere in the response header and then with AngularJS I need to check if this variable exists or not. When It exist it should show the div which contains the error message.
The problem is that I can't use res.render because I need to redirect.
So in the block where user is not found, you should have something like:
res.status(401).send("Login failed.");
And then on the client side you can check the response status and display the mesage.
Edit: if you need help on the client side as well, please provide your client code.
I ended up using express-flash.

Delete function doesnt work in cakephp

I am working in this project which is left by some other person to me.
The database of this project has been moved from one location to another. Moving the database is done by the owner. This caused one function to stop working which is the "delete" function for records.
For my development enviroment I moved the database locally, than it suddenly works. Which make me believe that there is something wrong with sending a delete request to the server.
The code looks like this:
if ($this->RemovedDuty->save($duty['Duty'])) {
if ($this->Duty->delete($duty_id)) {
$this->Session->setFlash('This duty is removed', 'default', array('class' => 'message success'));
return true;
} else {
$this->Session->setFlash('This duty could not be removed.', 'default', array('class' => 'message error'));
return false;
}
} else {
$this->Session->setFlash('There is something wrong with backing up the data', 'default', array('class' => 'message error'));
return false;
}
}
How can I go about troubleshooting my problem?
Have you checked, whether your database user has got the privilege to delete records for the new server.
Are you sure about your models? I see that you're saving in RemovedDuty model and deleting in Duty model. Make sure your models are correct.
Also check if the models are referencing correct tables.
Cheers!

PrestaShop - Login programmatically

I am writing a android and windows native app. The native app stores the login details as reated for mulitple other web apps, and logs them into this when browsing to them from the native app.
one of the buttons in my app open a prestashop site for a authenticated user. How can i set the username and password and log that user in to the site programmitcally, giving the illusion and user experience that he has been seemlessly authenticated and accessed to his shop.
I know this is an old question, but theres another way which i find better for the purpose.
You include the AuthController from the controllers folder, set your post-parameters and execute the postProcess() method. After this, you can check the "$authController->errors" array for errors. If it's empty - the login was successful.
Example:
public function hookDisplayHeader()
{
if ($this->context->cookie->isLogged())
{
return;
} else {
$acceptLogin = false;
if( isset( $_POST["email"] ) && isset( $_POST["passwd"] ) )
{
$acceptLogin = $this->attemptLogin($_POST["email"],$_POST["passwd"]);
}
if( $acceptLogin )
return;
die( $this->display(__FILE__, 'logintemplate.tpl') );
}
}
protected function attemptLogin($email, $password)
{
include _PS_FRONT_CONTROLLER_DIR_ . "AuthController.php";
$auth = new AuthController();
$auth->isAjax = true;
$_POST["email"] = $email;
$_POST["passwd"] = $password;
$_POST["SubmitLogin"] = true;
$auth->postProcess();
if( count($auth->errors) > 0 )
{
$this->context->smarty->assign( "errors", $auth->errors );
return false;
} else {
return true;
}
}
Edit: This no longer works with Prestashop 1.6. As of PS 1.6 $auth->postProcess() either redirects or sends the ajaxs response immediately. There is no way to circumvent this. If you want to do something after login, you have to make two ajax calls.
Basically do the same as the PrestaShop login form does, which is (for v1.5 at least):
Sending a POST request to http(s)://yourshop.com/index.php?controller=authentication with the following parameters:
email: your customer's email address
passwd: your customer's password
back: name of the controller you want to be redirected to after success (ex: my-account)
SubmitLogin: put anything there, it just needs to be true, so that the controller knows it's a login action
If it doesn't work, your version may work differently and you will have to check the network tab of your favourite developer tool, to see what kind of request is sent with which parameters.

how can I get more error messages out of solrj SolrException

When I send queries to Solr using solrj, I sometimes get SolrException's thrown. When I dig through the exception, it just says "Bad Request", and gives the HTTP return code (which is 400).
When I take the request URL and put it in my browser, I was able to see a richer error message. The browser displays an error message saying one of the fields names is not valid.
I would like to be able to capture this inside my log file. I was able to capture this by copying all the parameters to an Apache HTTP Client POST request (I'm using POST and not GET because GET made the URL too long) and re-executing the request, but this is inefficient. Is there a way to get error message out of SolrException directly?
Here's what I'm doing:
catch (SolrServerException e) {
if(e.getRootCause() instanceof SolrException) {
SolrException ee = (SolrException) e.getRootCause();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(SOLR_URL);
// copy params over
Iterator<String> iter = request.getParams().getParameterNamesIterator();
while(iter.hasNext()) {
String p = iter.next();
method.setParameter(p, request.getParams().get(p));
}
int statusCode;
try {
// re execute and display the error message
statusCode = client.executeMethod(method);
logger.error(method.getResponseBodyAsString());
} catch (Exception e1) {
// TODO Auto-generated catch block
}
}
These messages aren't available via SolrJ. You can see them in solr's log file, but there is no way to capture them in your client, since solr only returns the 400 error status with a generic message to the client :(

How can I save an automatically generated password in CakePHP?

I am trying to automatically register users. You enter an email address and it sends the user a password. Sounds simple enough, right? Here are a bunch of things that I've tried in my add action, but none of them work (as indicated).
if (!empty($this->data)) {
$this->User->create();
$random_pass = $this->Auth->password($this->generatePassword());
// Doesn't work:
$user_data['User'] = $this->data['User'];
$user_data['User']['password'] = $random_pass;
if ($this->User->save($user_data)) { /* ... */ }
// Doesn't work:
$this->User->set('password', $random_pass);
if ($this->User->save($this->data)) { /* ... */ }
// Doesn't work:
$this->data['User']['password'] = $random_pass;
if ($this->User->save($this->data)) { /* ... */ }
// Doesn't work:
$this->data['User'][0]['password'] = $random_pass;
if ($this->User->saveAll($this->data)) { /* ... */ }
}
According to Why is the CakePHP password field is empty when trying to access it using $this->data? it's because the Auth component is removing the password. Seems common enough, no? So how do I get around it?
More information
I'm using this function to generate the password. The add view only has three fields, first_name, last_name, and email (which is assigned to the username field in the Auth component).
first of all.. you can do
$random_pass = $this->Auth->password($this->generatePassword());
pr($random_pass);
to make sure there is actually data in that variable...
then you can save that data with...
$this->data['User']['password'] = $random_pass;
$this->User->save($this->data);
Also keep in mind that... during your testing you have if (!empty($this->data))
so make sure you are actually testing by entering some form of default data somewhere in your form.
Maybe you've got some validation rules defined in your User model that are not satisfied? You can try to check this by printing $this->validationErrors (or just check your User model to see if there are any rules).
JohnP answered this question in the comments. I had some junk in the beforeSave action. Removed and now it's working perfectly. Thanks again JohnP!
I am using Cake PHP 2.3.3 and following code works for me
public function recover()
{
if ($this->request->is('post') )
{
$this->loadModel('AclManagement.User');
$passwords = AuthComponent::password($this->data['User']['password']);
$this->User->query("UPDATE users SET password = '".$passwords."' WHERE password_change = '".$this->request->data['User']['id']."' ");
$this->Session->setFlash(__('Password Saved Sucessfully'), 'success');
$this->redirect(array('action' => 'login'));
} else {
$this->set('resettoken', $_REQUEST['id']);
}
}

Resources