base64 not working in Middleware of Laravel 5.4 - json

My middleware Code:
public function handle($request, Closure $next) {
$api_headers = getallheaders();
$error_msg = '';
$error = 0;
if (isset($api_headers) && !empty($api_headers)) {
if (isset($api_headers ['device_id']) && !empty($api_headers['device_id'])) {
} else {
$error_msg = 'Please send device ID header.';
$error = 1;
}
if (isset($api_headers['device_type']) && !empty($api_headers['device_type'])) {
} else {
$error_msg = 'Please send device type header.';
$error = 1;
}
} else {
$error_msg = 'Please send headers.';
$error = 1;
}
if ($error == 1) {
return base64_encode(response()->json(['error' => true, 'message' => $error_msg, 'code' => 0]));
} else {
return $next($request);
}
}
I want to convert the JSON to a encoded string and send it as a response. So i used base64_encode to converted it into a string. But it is not working in middleware. I do not know its reason I made a lot of efforts but did not understand what to do. I am also attaching a screenshot of the error. Please help if possible.

I dont know what status code you want to respond with, but try:
$encoded = base64_encode(response()->json([
'error' => true,
'message' => $error_msg,
'code' => 0
]));
return response($encoded, ?response status code?)
->header('Content-Type', 'text/plain');

Related

croogo 2 Request blackholed due to "auth" violation

I have a problem with my old website. Now I try to move it to new server (php5.6) and when i try to save data I have error:
Request blackholed due to "auth" violation.
I serach the place whose do it this error:
if ($this->Node->saveWithMeta($this->request->data)) {
Croogo::dispatchEvent('Controller.Nodes.afterAdd', $this, array('data' => $this->request->data));
$this->Session->setFlash(__('%s has been saved', $type['Type']['title']), 'default', array('class' => 'success'));
if (isset($this->request->data['apply'])) {
$this->redirect(array('action' => 'edit', $this->Node->id));
} else {
$this->redirect(array('action' => 'index'));
}
}
I think error do function saveWithMeta(). This function view like:
public function saveWithMeta(Model $model, $data, $options = array()) {
$data = $this->_prepareMeta($data);
return $model->saveAll($data, $options);
}
Can I replace/edit this function so that it starts to work?
edit
if (!$db->create($this, $fields, $values)) {
$success = $created = false;
} else {
$created = true;
}
These lines cause an error.

Send mail on actionCreate

I have a system that works by the intranet and I would like to know how best to send an alert email in actionCreate?
I did as below, the email is sent correctly, but if the internet is offline an unfriendly error message appears.
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
} else {
// error in saving model
}
}
return $this->render('create', [
'model' => $model,
]);
}
Try this (don't save model if email not sended)
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
$transaction = $model->getDb()->beginTransaction();
try{
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
}
}
catch(Exception $e)
{
$transaction->rollBack();
throwe $e;
//unlik savedFile if exist
}
}
return $this->render('create', [
'model' => $model,
]);
}
or use mail queue to save mail in databases and send via cron

Returning a json Response from a laravel project "Cannot read Property of Null"

I have here in my php file (laravel ) after i send an email and get a response to the mobile application
$msg ="email sent " ; $erreur=false ;
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
But, When I get a response using this code in my javascript file
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.erreur == false)
{
alert("a Password has been send to you email ");
}
else
{
alert(response.Message);
}
};
I get this error
The error is pretty straight forward the response is null
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response !=null && response.erreur == false)
{
alert("A password has been sent to your email.");
}
else
{
console.log(response); //probably doesnt have Message either
}
};
#MikeMiller
here is my Js code that communicates with my API
loginBtn.addEventListener('click',function(e)
{
if ( email.value!='')
{
try {
loginReq.open("POST","http://192.168.0.105/appcelerator/public/");//my local ip im testing on my computer
var params = {
email:email.value,
};
loginReq.send(params);
}catch (e)
{
alert(e.message);
}
}
else
{
alert("All fields are required");
}
});
now here is my code in my API (php laravel )
public function getPassword(Request $request)
{
$email = $request["email"];
$user = \DB::table('users')
->where('email', $request['email'])
->first();
$email = $user->email;
session()->put('email',$email);
if (!$user)
{
$msg = 'invalid email adresses';
$erreur = true ;
}else
{
Mail::send('emails.test',['password' => $this->generatePass() ],function($message )
{
$message->to(session()->get('email'),'Bonjour')->subject('welcome:');
});
$msg = 'Password has benn send to your email ';
$erreur = false;
}
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
}
when it's executed i get the email in my email adresse but the response as you know is null. that's my problem

Codeigniter Cannot save hashed password to database

I cannot save hashed password to my 'users' table, but if it's not hashed, the password saved. Can everybody help me?
Controller
public function add()
{
$this->data['title'] = 'add new user';
$this->data['subview'] = 'admin/user/add';
$validate = $this->user->validate;
$this->form_validation->set_rules($validate);
if ($this->form_validation->run() == TRUE){
$this->user->insert(array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->user->hash($this->input->post('password'))
));
$this->session->set_flashdata('message', msg_success('Data Saved'));
redirect('admin/user', 'refresh');
}
$this->load->view('admin/_layout_main', $this->data);
}
my Hash function in user_model
public function hash($string)
{
return hash('md5', $string . config_item('encryption_key'));
}
What's wrong with my code, or is there any other way to do it without any library? or How you do it basically to do this using codeigniter? Thanks
EDIT
this is my insert function from MY_Model
public function insert($data, $skip_validation = FALSE)
{
if ($skip_validation === FALSE)
{
$data = $this->validate($data);
}
if ($data !== FALSE)
{
$data = $this->trigger('before_create', $data);
$this->_database->insert($this->_table, $data);
$insert_id = $this->_database->insert_id();
$this->trigger('after_create', $insert_id);
return $insert_id;
}
else
{
return FALSE;
}
}
Im using Jamie Rumbelow Base Model for my base model, and I have follow his tutorial for insert into database

JSON response always returns true

I have problem with resolving my response which always resolve as true. I am submitting a form for forgotten password, and i have only one field there, that is e-mail. I check in the database for the record on base on the e-mail, and if the record is returned, i set the json to true, else to false. Here is the code from my Codeigniter controller:
public function checkEmail()
{
// set the validation rules
$this->form_validation->set_rules('checkemail', 'E-Mail', 'valid_email');
$this->form_validation->set_error_delimiters('<br /><p class=jsdiserr>', '</p><br />');
// if validation is passed
if ($this->form_validation->run() != FALSE)
{
$ids=array();
$ids[0]=$this->db->where('email', $this->input->post('checkemail'));
$query = $this->backOfficeUsersModel->get();
if($query)
{
$data = array(
'userid' => $query[0]['userid'],
'username' => $query[0]['username'],
'password' => $query[0]['password'],
'firstname' => $query[0]['firstname'],
'lastname' => $query[0]['lastname'],
'email' => $query[0]['email']
);
$currentUser = array();
$currentUser = $this->session->set_userdata($data);
echo json_encode(array("success" => "true"));
} else {
echo json_encode(array("success" => "false"));
}
// form validation has failed
} else {
$errorMessage = "Wrong email!";
}
} // end of function checkEmail
Now, when i check the result in my javascript file, i get always true. Here is the code:
$("#formSendPassword").submit(function(e){
e.preventDefault();
var email = $(this).find("#checkemail").val();
var obj = {email: email};
var url = $(this).attr("action");
$.post(url, obj, function(r){
if(r.success == "true") {
console.log(r.success);
$('#forgotPasswordForm').hide();
$('#successMailMessage').fadeIn()
} else {
$('#forgotPasswordForm').hide();
$('#errorMailMessage').fadeIn()
}
}, 'json')
})
Can anyone give me a hand with this?
Regards,Zoran
Firstly modify the PHP...
json_encode(array("success" => "true"));
to
json_encode(array("success" => true));
and also
json_encode(array("success" => "false"));
to
json_encode(array("success" => false));
Then modify the JS as follows by changing...
if(r.success == "true") {
to...
if(r.success === true) {
See how you go from there!
EDIT: In liaison with the OP we concluded that the actual issue was the way JS was posting the data.
var obj = {email: email};
Should have been...
var obj = {checkemail: email};
There were also a few specific problems with the PHP that were unrelated to the issue but have now been fixed.
if ($this->form_validation->run() != FALSE)
should be
if ($this->form_validation->run() !== FALSE)
or simply
if (!$this->form_validation->run())
Is the best way to chekc for false... != may not always do as you expect!
You need to parse the JSON in the JS: myObj = $.parseJSON(r);
then use myObj.success