Laravel: form with axios not saving - laravel

I'm writing an User Edit functionality with vue.js front-end.
The axios part:
sendUserData(){
axios.post('/api/saveUser', {
id: this.id,
name: this.name,
email: this.email,
password: this.password
},
{
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
}
).then(response => {
console.log(response.data);
if(response.data == 'success'){
this.$emit('userSaveSuccess')
} else {
this.$emit('userSaveError')
}
});
The output is success, but in the Database there isn't any changes. I tried with Postman too, and that time the data is changed, so the controller is working properly. What's the matter with this part?
Edit:
My controller method:
public function saveUser($name = '', $email = '', $password = ''){
$id = request('data.id', 0);
$name = request('data.name', $name);
$email = request('data.email', $email);
$password = request('data.pswrd', $password);
Log::info(request());
if($id == 0){
$saveUser = new User;
} else {
$saveUser = User::find($id);
if($name == ''){
$name = $saveUser -> name;
}
if($email == ''){
$email = $saveUser -> email;
}
}
$saveUser -> name = $name;
$saveUser -> email = $email;
if($password != ''){
$saveUser -> password = bcrypt($password);
}
if($saveUser->save()){
return 'success';
} else {
return 'error';
}
}

Your data needs to be sent within the data property.
axios.post('/api/saveUser', {
// don't forget the data property
data: {
id: this.id,
name: this.name,
email: this.email,
password: this.password
}
},
// ...
It would probably be a good idea to set up some validation in your controller too, as that would have made it apparent you weren't receiving the appropriate data.
EDIT: Thank you for posting the controller method.
You don't need to use data.* when retrieving the request data in the controller. This is simply where they go in axios to pass them as request variables. Also, the pswrd parameter in your controller does not match password which you are sending with axios.
public function saveUser($name = '', $email = '', $password = ''){
// get your parameters from the request helper
// you don't need to use data.* here
$id = request('id', 0);
$name = request('name', $name);
$email = request('email', $email);
$password = request('password', $password); // this is not 'pswrd'
// ...
// you should consider switching to the Hash facade to allow
// hashing to be configured within `/config/hashing.php`
if ($password != ''){
$saveUser->password = Hash::make($password);
}
// ...
}
As a final note, it's important to know that Laravel only updates an entry if the data has changed. If you send the same values, there will be no change. Since your method involves retrieving the existing name and email when those request values are empty, this might explain why it appears that nothing is saving in the database.
To force an update of the timestamps without any changes, you would need to call the ->touch() method on the model.

Related

How can I store the web push notification settings after the login in database

I want to send web push notification on the browser. I used this tutorial to
send the notification. This is working fine and show the details.
{
"endpoint":"https://fcm.googleapis.com/fcm/send/ftB1OYn5bJY:APA91bGNcquGDcUXr29JiVV5Zos4Vi7FzmZ_wJQMITEXt8FlVBRBtgrPdLnPR6GALtnCOe9RNPP1cmC_bkv9D1BE1o6_-0cMXQsodpPoRCeOP5EDt6EwqK0ys36MbCi3HNTWf7ZcItVi",
"expirationTime":null,
"keys":{"p256dh":"BLJQqNovnlJ28d5xteX8whwdby6l0BYLvC_iyNtY2nO7YXQSI-EOvdOs1LXy8F_EuH2MZi0FU_HoCO-5GRQYYVQ",
"auth":"tDcEgiy5M5tJ3_vXuuQ9uw"}
}
but I want to integrate with my Laravel API.
After the user login, I want to save the endpoint, public key, and auth
to the database.
Login Controller
public function authenticate(Request $request)
{
$credentials = $request->only('username', 'password');
// return $credentials;
$response = array(
'status' => 'Failed',
'msg' => '',
'is_success' => false,
'data' => ''
);
try {
if (!$token = JWTAuth::attempt($credentials)) {
$response["msg"] = "Wrong Username or Password";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
if (Auth::user()->is_active == 0) {
$response["msg"] = "Your account has not been activated";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
$data = array();
$user = User::find(Auth::user()->id);
$data['id'] = $user->id;
$data['fname'] = $user->fname;
$data['lname'] = $user->lname;
$data['email'] = $user->email;
$data['username'] = $user->username;
$response["msg"] = "Login Successfully";
$response["status"] = "Success";
$response["data"] = compact('token');
$response["user"] = Auth::user();
}
}
} catch (\Exception $th) {
$response["msg"] = $th->getMessage();;
$response["status"] = "Failed";
$response["is_success"] = false;
}
return $response;
}
I think the best way to solve this, is to make another model for that data, a one to one relationship between user model and push notification data model. Make a controller for CRUD operations on this new model, and just have another http call from the front end to store the data.

How can I encrypt a Joomla Configuration Parameter that is stored in the database?

I found this question, which is identical to what I need to do:
How do you Encrypt and Decrypt a PHP String?
I've got everything working to the point of encrypting the data before it is saved. In the event function onExtensionBeforeSave, I have access to the table. I can get the values that need to be encrypted from jinput and encrypt them. What I can't figure out is how to put the encrypted data into the table object in a way that it will replace the un-encrypted data before it is stored/saved.
I was able to figure this out. In the extension event onExtensionBeforeSave, I get the post data, load the config.xml file to check the form fields for my custom fields (type='encryptedtext'), encryt those and use the table object to bind and check it, so it will be stored correctly.
function onExtensionBeforeSave($context, $table, $isNew)
{
$jinput = JFactory::getApplication()->input;
$component = $jinput->get('component');
if($component !== 'com_store') // Only encrypting fields in the store component for now
{
return true;
}
$form_path = JPATH_ADMINISTRATOR . '\\components\\' . $component . '\\config.xml';
$xml = simplexml_load_file($form_path);
$has_encrypted = false;
foreach($xml->fieldset as $fieldset)
{
foreach($fieldset as $field)
{
if($field['type'] == 'encryptedtext') // is our custom form field type to be encrypted
{
$has_encrypted = true;
if(!$fields) // get fields if it hasn't already been done
{
$fields = $jinput->get('jform', '', 'array');
}
$field = (string)$field['name'];
$value = (string)$fields[$field];
$cipher = "aes-256-ctr";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen, $isStrongCrypto);
if (!$isStrongCrypto)
{
throw new \Exception("Not a strong key");
}
$keyhash = openssl_digest($component, 'sha256', true);
$opts = OPENSSL_RAW_DATA;
$encrypted = openssl_encrypt($value, $cipher, $keyhash, $opts, $iv);
if ($encrypted === false)
{
throw new \Exception('Encryption failed: ' . openssl_error_string());
}
$result = $iv . $encrypted;
$result = base64_encode($result);
$fields[$field] = $result;
}
}
}
if(!has_encrypted)
{
return false;
}
$data = array(
'params'=>$fields,
'option'=>$component
);
if (!$table->bind($data))
{
throw new RuntimeException($table->getError());
}
if (!$table->check())
{
throw new RuntimeException($table->getError());
}
return true;
}
All that is left is to decrypt it in the getInput function of the custom field. I answer this in case someone needs it, and I would love some critique if people see improvements, or if it's complete junk ...

Multiuser login codeigniter(how to use password_verify method?)

Please help guys, I have encrypted successfully my password with password_hash but is there any solution how to check login and password using PHP password_verify for multiuser login?
here's my controller:
public function index()
{
$this->form_validation->set_rules('email','Email address','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('view_login');
} else {
$this->load->model('Model_members');
$valid_user = $this->Model_members->check_credential();
if($valid_user == FALSE)
{
$this->session->set_flashdata('error','');
redirect("login");
} else {
$this->session->set_userdata('email', $valid_user->email);
if($this->session->userdata('groups') == '1')
{
redirect('home');
}
elseif($this->session->userdata('groups') == '2')
{
redirect('homepage');
}
elseif($this->session->userdata('groups') == '0')
{
redirect('test1');
}
}
}
}
This is my model:
public function check_credential()
{
$email = set_value('email');
$password = set_value('password');
$hasil3 = $this->db->where('email', $email)
->where('password', $password)
->limit(1)
->get('users');
if($hasil3->num_rows() > 0)
{
return $hasil3->row();
} else {
return array();
}
}
Very appreciate for the help !!
Please find below mentioned solution, It will help you.
In Controller
$userData['email'] = $this->input->post('email');
$userData['password'] = $this->input->post('password');
$valid_user = $this->Model_members->check_credential($userData);
In Model your function will look like below.
public function check_credential($param) {
$hasil3 = $this->db->where('email', $param['email'])
->where('password', password_hash($param['password'], PASSWORD_DEFAULT, ['cost' => 10]))
->limit(1)
->get('users');
if ($hasil3->num_rows() > 0) {
return $hasil3->row();
} else {
return array();
}
}
Let me know if it not work.
Controller
//create array to pass data to model
$data = [
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
];
//check model to see if user exists and if correct password
$user = $this->name_of_model->check_credential($data);
if(isset($user['error])){
//return error message in some form
}
Model:
You want to break you process in two, in order to make error reporting better. First check if user exists, then check if password is correct
public function check_credential($data) {
//see if user exists first
$user = $this->db->where('email', $data['email'])
->get('users')->row_array();
if($user){
$success = (password_verify($data['password'],$user['password']));
return ($success) ? $user : ['error'=>'Incorrect Password']
}
else{
return ['error'=>'User doesn't exist'];
}
}

resetting password in codeigniter

i'm new to codeigniter, and i am attempting to create a password reset system
this is my controller:
public function changePassword(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
$data['title'] = 'Change my Password | Watch Stop';
$this->load->view('template/header', $data);
$this->load->view('watch_stop/vpassword', $data);
$this->load->view('template/footer');
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function reset_password(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
//validating form
$this->form_validation->set_rules('old_password','Old Password','trim|required|min_length[5]|md5');
$this->form_validation->set_rules('new_password','New Password','trim|required|min_length[5]|matches[cnew_password]|md5');
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
if ($this->form_validation->run() == FALSE)
{
$this->changePassword();
//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Failed to update password</div>');
}else {
$query=$this->customer_model->change_password();
$data = array( "main_content" => 'includes/memberadmin/memberadmin_cpass_process',
"query" => $query
);
$this->load->view('includes/memberadmin/template',$data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this is my model:
function change_password(){
$this->db->select('id');
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('password',$this->input->post('old_password'));
$query=$this->db->get('user');
if ($query->num_rows() > 0)
{
$row = $query->row();
if($row->email===$this->session->userdata('email'))
{
$data = array(
'new_password' => $this->input->post('new_password')
);
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('new_password',$this->input->post('old_password'));
if($this->db->update('user', $data))
{
return "Password Changed Successfully";
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Wrong Old Password";
}
}
When i click on the update button in my reset password page, i am getting the following error for my new password confirmation field: Unable to access an error message corresponding to your field name Confirm Password.()
please help!
1) there are two pipe signs near required||md5
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
change it to
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required|md5');
2) changing input to md5 at this stage is not good.
You have to use password_hash function.
Read More >> http://php.net/manual/en/function.password-hash.php
3) You forgot to load model. $this->load->model('customer_model');

Joomla 2.5 method save()

Is there a way to show the changed values after saving within the Joomla save method?
For example, when I edit a "maxuser" field and save it, I´d like to show the old and the new value.
I tried this by comparing "getVar" and "$post", but both values are the same.
function save()
{
...
$maxuser1 = JRequest::getVar('maxuser');
$maxuser2 = $post['maxuser'];
...
if($maxuser1 != $maxuser2) {
$msg = "Not the same ...";
}
...
}
It's better to override JTable, not the Model. Heres sample code:
public function store($updateNulls = false) {
$oldTable = JTable::getInstance(TABLE_NAME, INSTANCE_NAME);
$messages = array();
if ($oldTable->load($this->id)) {
// Now you can compare any values where $oldTable->param is old, and $this->param is new
// For example
if ($oldTable->title != $this->title) {
$messages[] = "Title has changed";
}
}
$result = parent::store($updateNulls);
if ((count($messages) > 0) && ($result === true)){
$message = implode("\n", $messages);
return $message;
} else {
return $result;
}
}
This will return message string if there are any, true if there are no messages and save succeeded and false if saving failed. So all you have to do is check returned value in model and set right redirect message.
In the controller you can use the postSaveHook which gives you access to the validated values.

Resources