CakePHP 3 - record can not be saved in my login function - cakephp

Record can not be saved in my login function. I don't know why.
Does anyone know what the problem is?
Other functions in the controller (add, edit, delete) work without problems.
...
class UsersController extends AppController
{
...
/**
* Login method
*/
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$user = $this->Users->newEntity($user,['validate' => false]);
$user->isNew(false);
//Last login date
$user->test = 'abcdef';
$user->modified = new Time();
$this->Users->save($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Error'));
}
}
...
}

Why you use newEntity ?
Try to remove it and do something liek this :
$this->Auth->setUser($user);
$user->isNew(false);
$user->validate=false;
//Last login date
$user->test = 'abcdef';
$user->modified = new Time();
$this->Users->save($user);
If it doesn't work try to show entity errors to know why :
Before : $this->Users->save($user);
Do that :
debug($user->errors());
die();

It works on this way:
public function login()
{
if ($this->request->is('post')) {
$authUser = $this->Auth->identify();
if ($authUser) {
$this->Auth->setUser($authUser);
$User = $this->Users->get($authUser['id']);
//Last login date
$User->modified = new Time();
$this->Users->save($User);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Error'));
}
}

Related

Codeigniter 3.1.9 - CI_Session is filling up my database on every refresh

I have been getting back into Codeigniter as support was picked up by BCIT. I have a problem with ci_sessions and the database driver which is regenerating the encrypted session ID and storing new data in my database on every page refresh. I'm so frustrated right now! I have both secure file storage and database for both common drivers. I want to use both or either but the effect on my application is the same whether I am using a database or files. The ci_session keeps refreshing and it is not ideal for logins, registration or any account type. Please help me see what I am doing wrong? Much appreciation granted in advance.
Config:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'users';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Controllers:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* User Management class created by CodexWorld
*/
class Limousers extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user');
}
/*
* User account information
*/
public function account(){
print_r($_SESSION);
$data = array();
print_r($this->session->userdata());
if($this->session->userdata('isUserLoggedIn')){
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
//load the view
$this->load->view('limousers/account', $data);
}else{
redirect('limousers/login');
exit;
}
}
/*
* User login
*/
public function login(){
print_r($_SESSION);
if($this->session->userdata('isUserLoggedIn'))
{
print_r($this->session->userdata);
redirect('limousers/account');
exit;
}
$data = array();
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
if($this->input->post('loginSubmit')){
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == true) {
$con['returnType'] = 'single';
$con['conditions'] = array(
'email'=>$this->input->post('email'),
'password' => md5($this->input->post('password')),
'status' => '1'
);
$checkLogin = $this->user->getRows($con);
if($checkLogin){
$this->session->set_userdata('name',$con['conditions']['email']);
$this->session->set_userdata('isUserLoggedIn',TRUE);
$this->session->set_userdata('userId',$checkLogin['id']);
redirect('limousers/account');
exit;
}else{
$data['error_msg'] = 'Wrong email or password, please try again.';
}
}
}
//load the view
$this->load->view('limousers/login', $data);
}
/*
* User registration
*/
public function registration(){
print_r($_SESSION);
$data = array();
$userData = array();
if($this->input->post('regisSubmit')){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('conf_password', 'confirm password', 'required|matches[password]');
$userData = array(
'name' => strip_tags($this->input->post('name')),
'email' => strip_tags($this->input->post('email')),
'password' => md5($this->input->post('password')),
'gender' => $this->input->post('gender'),
'phone' => strip_tags($this->input->post('phone'))
);
if($this->form_validation->run() == true){
$insert = $this->user->insert($userData);
if($insert){
$this->session->set_userdata('success_msg', 'Your registration was successfully. Please login to your account.');
redirect('limousers/login');
exit;
}else{
$data['error_msg'] = 'Some problems occured, please try again.';
}
}
}
$data['user'] = $userData;
//load the view
$this->load->view('limousers/registration', $data);
}
/*
* User logout
*/
public function logout(){
$this->session->unset_userdata('isUserLoggedIn');
$this->session->unset_userdata('userId');
$this->session->sess_destroy();
redirect('limousers/login');
exit;
}
/*
* Existing email check during validation
*/
public function email_check($str){
$con['returnType'] = 'count';
$con['conditions'] = array('email'=>$str);
$checkEmail = $this->user->getRows($con);
if($checkEmail > 0){
$this->form_validation->set_message('email_check', 'The given email already exists.');
return FALSE;
} else {
return TRUE;
}
}
}
Models:
<?php if ( ! defined('BASEPATH')) exit('No direct script access
allowed');
class User extends CI_Model{
function __construct() {
$this->userTbl = 'users';
}
/*
* get rows from the users table
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->userTbl);
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
$this->db->where($key,$value);
}
}
if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
if(array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
$query = $this->db->get();
if(array_key_exists("returnType",$params) &&
$params['returnType'] == 'count'){
$result = $query->num_rows();
}elseif(array_key_exists("returnType",$params) &&
$params['returnType'] == 'single'){
$result = ($query->num_rows() > 0)?$query- >row_array():FALSE;
}else{
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
//return fetched data
return $result;
}
/*
* Insert user information
*/
public function insert($data = array()) {
//add created and modified data if not included
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
//insert user data to users table
$insert = $this->db->insert($this->userTbl, $data);
//return the status
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
}

CakeDC users plugin: redirect error after changePassword

My app is developed in CakePHP 3.x.
I use CakedDC Users plugin, and it works fine, except when the user wants to change his password, and click on Submit.
Let's say we have a Profile ID = 52606b3f-c72d-4485-9c76-3b0f8
The Edit page has a url like this:
localhost/my_app/profile/52606b3f-c72d-4485-9c76-3b0f8
The changePassword page has a url like this:
localhost/my_app/users/users/change-password/52606b3f-c72d-4485-9c76-3b0f8
When I click on Submit, it redirects to the profile page, but the ID is lost:
localhost/my_app/profile
and I get this error message:
Record not found in table "users" with primary key [NULL]
I think the reason is that the ID is not passed. And I don't find where and how to fix it.
Any help please ?.
When id is not passed, the id is taken from the logged in user. You can take a look at src/Controller/Traits/ProfileTrait.php. Could you debug $this->Auth->user('id')?
Also, you could customize the redirect url after changing the password. Configure::write('Users.Profile.route', [{url}]), see src/Controller/Traits/PasswordManagementTrait.php Ln44.
I don't remember my initial code, but, after months, I found the solution.
in src/Controller/Traits/ProfileTrait.php, set $redirect = Configure::read('Users.Profile.route');
public function changePassword()
{
$user = $this->getUsersTable()->newEntity();
$id = $this->Auth->user('id');
if (!empty($id)) {
$user->id = $this->Auth->user('id');
$validatePassword = true;
//#todo add to the documentation: list of routes used
$redirect = Configure::read('Users.Profile.route');
} else {
$user->id = $this->request->session()->read(Configure::read('Users.Key.Session.resetPasswordUserId'));
$validatePassword = false;
if (!$user->id) {
$this->Flash->error(__d('CakeDC/Users', 'User was not found'));
$this->redirect($this->Auth->config('loginAction'));
return;
}
//#todo add to the documentation: list of routes used
$redirect = $this->Auth->config('loginAction');
}
$this->set('validatePassword', $validatePassword);
if ($this->request->is('post')) {
try {
$validator = $this->getUsersTable()->validationPasswordConfirm(new Validator());
if (!empty($id)) {
$validator = $this->getUsersTable()->validationCurrentPassword($validator);
}
$user = $this->getUsersTable()->patchEntity($user, $this->request->data(), ['validate' => $validator]);
if ($user->errors()) {
$this->Flash->error(__d('CakeDC/Users', 'Password could not be changed'));
} else {
$user = $this->getUsersTable()->changePassword($user);
if ($user) {
$this->Flash->success(__d('CakeDC/Users', 'Password has been changed successfully'));
return $this->redirect($redirect);
} else {
$this->Flash->error(__d('CakeDC/Users', 'Password could not be changed'));
}
}
} catch (UserNotFoundException $exception) {
$this->Flash->error(__d('CakeDC/Users', 'User was not found'));
} catch (WrongPasswordException $wpe) {
$this->Flash->error(__d('CakeDC/Users', '{0}', $wpe->getMessage()));
} catch (Exception $exception) {
$this->Flash->error(__d('CakeDC/Users', 'Password could not be changed'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}

Image doesn't uploading cakephp 2.0

I have used a component for uploading image,there is no problem in controller after add component.Here the code
class OesUsersController extends AppController {
var $helpers = array('Html', 'Form');
var $components = array('upload');
public function index() {
}
public function upload()
{
if (empty($this->data))
{
$this->render();
}
else
{
$this->cleanUpFields();
// set the upload destination folder
$destination = realpath('../../app/webroot/img/uploads/') . '/';
// grab the file
$file = $this->data['Image']['filedata'];
// upload the image using the upload component
$result = $this->Upload->upload($file, $destination, null, array('type' => 'resizecrop', 'size' => array('400', '300'), 'output' => 'jpg'));
if (!$result){
$this->data['Image']['filedata'] = $this->Upload->result;
} else {
// display error
$errors = $this->Upload->errors;
// piece together errors
if(is_array($errors)){ $errors = implode("<br />",$errors); }
$this->Session->setFlash($errors);
$this->redirect('/images/upload');
exit();
}
if ($this->Image->save($this->data)) {
$this->Session->setFlash('Image has been added.');
$this->redirect('/images/index');
} else {
$this->Session->setFlash('Please correct errors below.');
unlink($destination.$this->Upload->result);
}
}
}
The problem is image doesn't come from add.ctp
here the add.ctp code
<label for="Image">Image:</label>
<input type="file" name="data[Image][filedata]" id="ImageFiledata" />
add function code
public function add() {
$clint_ip=$this->request->clientIp();
if ($this->request->is('post')) {
$this->OesUser->create();
pr($this->request->data);
$this->request->data['OesUser']['user_otpkey']=String::uuid();
$this->request->data['OesUser']['user_regdate']=date("Y-m-d H:i:s");
$this->request->data['OesUser']['user_ip']=$clint_ip;
$this->barcode($this->request->data['OesUser']['user_otpkey']);
if ($this->OesUser->save($this->request->data)) {
$this->Session->setFlash(__('The oes user has been saved'), 'flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The oes user could not be saved. Please, try again.'), 'flash_fail');
}
}
$this->set('ip',$clint_ip);
}
here, database field name: image
controller name :OesUsers
Model name :OesUser
for full work I have taken help from this link
http://labs.iamkoa.net/2007/10/23/image-upload-component-cakephp/
How is your entire form looks like in add.ctp?
It sounds to me that you did not add
enctype="multipart/form-data"
to the form. That will cause the form not to post the file.
And also, it is recommended to use Form helper to create form.
When using Form helper, specify the form type to file
$this->Form->create('model',array('type'=>'file'));

update Auth session

How to update user information stored in auth session? without logout and login again.
I think this function will do it.. but is it the best-practice?
function update($field, $value){
$this->Session->write($this->Auth->sessionKey . '.' . $field, $value);
}
Yes.
You could grab the current info array, modify it, and then call $this->Auth->login($newUserData);, but this will also renew the session (no user interaction needed, though). Note: Applies to CakePHP 2.0+ only.
I've completed update function to get an array of new values. with keys (field name):
public function update($fields, $values = null) {
if (empty(parent::$_user) && !CakeSession::check(parent::$sessionKey)) {
return false;
}
if (!empty(parent::$_user)) {
$user = parent::$_user;
} else {
$user = CakeSession::read(parent::$sessionKey);
}
if (is_array($fields)) {
if (is_array($values)) {
$data = array_combine($fields, $values);
} else {
$data = $fields;
}
} else {
$data = array($fields => $values);
}
foreach ($data as $field => $value) {
if (isset($user[$field])) {
$user[$field] = $value;
}
}
return $this->login($user);
}
(thanks to tigrang for login function)

CakePHP REST Authorization issue on POST and PUT (I get 404)

I'm developing a REST api for a application, and everething went fine up until now...
I'm building a header with login data, GET and DELETE work fine but when I try to send a PUT or POST request I get 404...
When authorization is off (i.e., I do not check it in cake) everything works fine.
Here's the controller code:
class SitesController extends AppController {
var $uses = array("Site");
var $name = 'Sites';
var $scaffold;
var $components = array('RequestHandler','Security');
function beforeFilter() {
$this->Security->loginOptions = array(
'type'=>'basic'
);
$this->Security->loginUsers = array(
'lukasz'=>'blabla',
'test'=>'test'
);
$this->Security->requireLogin();
}
function index() {
$sites = $this->Site->find('all');
$this->set(compact('sites'));
}
function view($id) {
$site = $this->Site->findById($id);
$this->set(compact('site'));
}
function add() {
if($this->data != null) {
$this->Site->create();
if($this->Site->save($this->data)) {
$message = array('Deleted');
} else {
$message = $this->data;
}
$this->set(compact("message"));
}
}
function edit($id) {
$this->Site->id = $id;
if ($this->Site->save($this->data)) {
$message = array('Saved');
} else {
$message = array('Error');
}
$this->set(compact("message"));
}
function delete($id) {
if($this->Site->delete($id)) {
$message = array('Deleted');
} else {
$message = array('Error');
}
$this->set(compact("message"));
}
}
And here's how I send requests:
http://bin.cakephp.org/view/165115685
http://bin.cakephp.org/view/1477117088
I suspect you're running into the CSRF protection (form spoofing protection) the SecurityComponent applies to all POST and PUT requests. Try turning it off using the $validatePost option.

Resources