Cant write to database with cakePHP - php

I am new to cakePHP and am just starting to use it for my new job.
I have created an edit_company action in my Orders Controller. I updated the acos table to allow this action. Now the problem is, I can't access any sort of 'edit' action. It says "You are not authorized to access that location" whenever I try to acccess any action that writes or updates database. edit,edit_products,edit_shipping, etc...
The view action works just fine.
This was not happening before.
Heres a bit of the code:
class OrdersController extends AppController{
public $uses = array('Order');
public $hideActions = array('campaign','customer','shipping','review_order','place_order','products','payment','confirmation','cancel','edit_status','edit_order_type','edit_products','edit_tax','add_product','cancel_shipping_label','track_label','view_label','reprint_label','edit_shipping','create_shipping_label');
public $components = array('Payflow','Printer');
public $actionMap = array(
'create' => array('add','create','campaign','customer','shipping','review_order','place_order','payment','products'),
'read'=> array('index', 'view', 'display','confirmation','track_label','search'),
'update' => array('edit','cancel','edit_status','edit_order_type','edit_products','edit_company','edit_tax','add_product','cancel_shipping_label','reprint_label','edit_shipping','create_shipping_label'),
'delete' => array('delete','back_orders_by_state')
);
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos');
}
public function permissions(){
$this->Acl->allow('Admin','Controllers/Orders');
$this->Acl->allow("Sales","Controllers/Orders",'read');
$this->Acl->allow("Sales","Controllers/Orders",'create');
$this->Acl->allow("Sales","Controllers/Orders",'update');
$this->Acl->deny("Shipping","Controllers/Orders",'update');
$this->Session->setFlash("Permissions Updated.");
$this->redirect("/orders/");
}
public function edit_shipping($id){
$sm_conditions = array();
if(!$this->Acl->check(array('User' => array('UserID' => $this->Auth->user("UserID"))), 'Controllers/Orders','delete')){
$sm_conditions['Restricted'] = 1;
}
$shipping_method_ids = $this->Order->ShippingMethod->find("list",array("conditions"=>$sm_conditions,"fields"=>array("ShippingMethodID","ShippingMethodName")));
$order = $this->Order->read(null,$id);
$this->set("order",$order);
$this->set("shipping_method_ids",$shipping_method_ids);
if($this->request->is('put')){
if($this->Order->save($this->data,null,array("ShippingAddress","ShippingMethodID"))){
$this->Session->setFlash("Order Shipping Updated.");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$this->Auth->user("UserID"),"NoteBody"=>"Order Shipping Information updated.","CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->redirect("/orders/view/$id");
}
}else{
$this->request->data = $order;
}
}
public function create_shipping_label($id){
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is('put')){
$this->Order->save(array(
"Order"=>array(
"OrderID"=>$id,
"LabelPrinted"=>false,
"OrderStatusID"=>2,
"Notes"=>(!empty($this->data['Order']['Notes']))?$this->data['Order']['Notes']:null
)
));
$this->Session->setFlash("A new shipping label will be created momentarily.");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$this->Auth->user("UserID"),"NoteBody"=>"New shipping label will be created. ".((!empty($this->data['Order']['Notes']))?$this->data['Order']['Notes']:null),"CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->redirect("view/".$id);
}else{
$this->request->data = $order;
}
}
public function cancel($id){
$order = $this->Order->read(null,$id);
if($this->request->is('post')){
//Check if note given
$this->Order->Note->data = $this->data;
if($this->Order->Note->validates()){
//Delete from Call table
$this->loadModel("Call");
$this->Call->deleteAll(array('Call.OrderID'=>$id));
//Add a note
$user_id = $this->Auth->user("UserID");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$user_id,"NoteBody"=>"Order Canceled. ","CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$user_id,"NoteBody"=>"Reason For Cancellation: ".$this->data['Note']['NoteBody'],"CreatedDate"=>date("Y-m-d H:i:s")))
);
//Create a refund request if payment type is in TxType (1,2,3,7,11,9)
$txTypes = array(1,2,3,7,11,9);
$paid = 0;
foreach($txTypes as $txType){
$payments = Set::extract("/Payment[TransactionTypeID=$txType]/PaymentAmount",$order);
$paid += array_sum($payments);
}
if($paid>0){
$this->Order->refund($id,$paid);
}
//Change Status to Cancel (4) & LabelPrinted = 0
$this->Order->save(array("Order"=>array("OrderID"=>$id,"LabelPrinted"=>0,"OrderStatusID"=>4)));
//Update the total price
$this->Order->updateOrderTotal($id);
$this->Session->setFlash("Order was successfully canceled.");
$this->redirect("/orders/view/".$id);
}
}
$this->set("order",$order);
}
public function edit_products($id){
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is("post")){
$error = false;
while($error==false && ($oe=array_shift($this->request->data['OrderEntry']))){
if(!$this->Order->OrderEntry->save(array("OrderEntry"=>$oe))){
$error = true;
}
}
if($error==false){
$this->Session->setFlash("Products Updated.");
$this->Order->updateOrderTotal($id);
$this->redirect("/orders/view/$id");
}
}
}
public function edit_company () {
}
public function edit ($id=null) {
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is("post")){
$error = false;
while($error==false && ($oe=array_shift($this->request->data['OrderEntry']))){
if(!$this->Order->OrderEntry->save(array("OrderEntry"=>$oe))){
$error = true;
}
}
if($error==false){
$this->Session->setFlash("Products Updated.");
$this->Order->updateOrderTotal($id);
$this->redirect("/orders/view/$id");
}
}
}
Could anyone help me with this problem?
Thanks!

You are only giving non authenticaded users permission to access two actions:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos');
}
Add the new actions or log the user in before accesing the actions:
Giving permission to not authenticated users to your new actions:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos','edit_products','edit','cancel','create_shipping_label','edit_shipping');
}
If you don't want to grant access to non authenticated users to these actions login before trying to access them.
You can check more about Auth here
Also check this example that is part of the Blog Tutorial

Related

Silverstripe: Pass URL Variable to Form Action

is there a way to pass a URL variable to a form action? I've got it working on a user details form, but when I'm trying to do it with a user file upload it won't work.
As you will see below, I have a form and a save action for saving user details. That works fine.
When I try to pass the URL variable to the User File Upload form, it doesn't work. It says that I'm trying to get a value of a non-object.
// Get Client ID from URL Parameters
public function getUser() {
if( isset($this->urlParams['ID']) && is_numeric($this->urlParams['ID']) ) {
return $user = Member::get()->byID($this->urlParams['ID']);
} else {
return $user = $this->request->postVars();
}
}
// Edit/Save a User's details
public function EditUserDetails() {
//Include JS for updating details
Requirements::javascript('module-memberprofiles/javascript/MemberProfileUpdate.js');
Requirements::set_force_js_to_bottom(true);
$fields = new FieldList(
$leftCol = CompositeField::create(
TextField::create('FirstName', 'First Name')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Surname', 'Surname')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
CompositeField::create(
TextField::create('Address', ''),
TextField::create('Suburb', ''),
CompositeField::create(
DropdownField::create('State', '', singleton('Member')->dbObject('State')->enumValues())->setFieldHolderTemplate('UserDetails_StatePostCode'),
TextField::create('PostCode', '')->setFieldHolderTemplate('UserDetails_StatePostCode')
)->addExtraClass('row')
)
->addExtraClass('userdetails-address wrap')
->setFieldHolderTemplate('UserDetails_AddressHolder'),
TextField::create('Phone', 'Phone')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Email', 'Email')
->setFieldHolderTemplate('UserDetails_FieldHolder')
)->setFieldHolderTemplate('UserDetails_CompositeField')
);
$actions = new FieldList(new FormAction('SaveUserDetails', 'Save Profile'));
$validation = new RequiredFields(array('FirstName','Surname','Email'));
$form = new Form ( $this, 'EditUserDetails', $fields, $actions, $validation);
$form->loadDataFrom($this->getUser());
$form->setTemplate('MemberProfilePage_UserDetailsForm');
return $form;
}
public function SaveUserDetails($data, $form) {
$table = Member::get()->byID($this->getUser());
$members = Member::get();
$emailExists = $members->filter(array(
'Email' => $data['Email'],
'ID:not' => $table->ID
));
if( $emailExists->count() > 0 ) {
$form->sessionMessage('Sorry, that email address already exists. Please try again','bad');
return $this->redirectBack();
} else {
$form->sessionMessage('You have successfully updated this user\'s details.','good');
}
$form->saveInto($table);
$table->write();
$this->redirectBack();
return $this;
}
//User file upload function
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files')
);
$actions = FieldList::create(FormAction::create('SaveUserFile', 'Upload files'));
$form = Form::create($this, __FUNCTION__, $fields, $actions, null);
$form->loadDataFrom($this->getUser());
return $form;
}
//Refresh files function
public function SaveUserFile($data, $form) {
$up = new Upload();
$file = Object::create('File');
$file->setFileName('newname');
$up->loadIntoFile($data['UserFiles'], $file, 'User-Files');
if($up->isError()) {
//handle error here
//var_dump($up->getErrors());
}else {
//file uploaded
//$file->OwnerID = 3;
//$file->write();
//$this->redirectBack();
return $this;
}
}
OK, I managed to figure this one out...
I had to set a form action to direct the upload function to the correct URL. It appears that the ID was being removed from the URL when I clicked submit, so the "getUser" function couldn't see the value.
Here's the working code for the Upload Form function:
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files'),
HiddenField::create('ID','',$this->getUser()->ID)
);
$actions = FieldList::create(
FormAction::create('SaveUserFile', 'Upload files')
->addExtraClass('button rounded solid')
);
$form = Form::create($this, 'UploadUserFile', $fields, $actions);
$form->setFormAction($this->Link().'UploadUserFile/'.$this->getUser()->ID);
return $form;
}

Role base access control system for admin and super_admin

I am trying to get this result -> Use access control logic for two user types: administrators and super administrators.
Administrators will have read access to all records within the system however they will have edit/delete access to only those records that are created by them.
Super administrators will have read/edit/delete access to all records. In this case what should i use? if any one know how to give Roll back accessing control in simple manner in above case then please tell me how to do this?
after login from admin_login.php my page comes here...
this is my controller page..
listing.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Listing extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('student');
$this->load->helper('url');
$this->load->helper('form');
$s = $this->session->userdata('admin_id');
log_message('error', 'Some variable did not contain a value.');
}
public function index()
{
$s = $this->session->userdata('admin_id');
$this->load->model('student',$s);
//$data['result'] = $this->student->listing();
$students = $this->student->listing();/////new line delete [resulet]time 5:42 29/03/16
//$this->load->view('list_view',$data); //// change here time 5:52 29/03/16
$this->load->view('list_view',array('students'=>$students)); /////listing->list_view name change
}
public function delete($id)
{
$result = $this->student->delete_operation($id);
$s = $this->session->userdata('admin_id');// session data call.
//$data['result'] = $this->student->listing();
$students = $this->student->listing();///new line 30/03 1230pm// change for list_view
$this->load->view('list_view',array('students'=>$students));///same as above//change for list_view
//$this->load->view('list_view',$data); ////////////////////////listing->list_view name change
}
public function edit($id)
{
if($id)
{
$s = $this->session->userdata('admin_id');
$result = $this->student->edit_record($id);
$data['action'] = 'edit';
$data['student_id'] = $result[0]->student_id;
$data['student_name'] = $result[0]->student_name;
$data['student_email'] = $result[0]->student_email;
$data['student_address'] = $result[0]->student_address;
$data['subject'] = $result[0]->subject;
$data['marks'] = $result[0]->marks;
}
$this->load->view('edit_student',$data);
}
public function add_student()
{
//$s['user'] = $this->session->userdata('admin_id');//get session data // new line30/03/16
$data['student_id'] = '';
$data['student_name'] = '';
$data['student_email'] = '';
$data['student_address'] ='';
$data['subject'] = '';
$data['marks'] = '';
//$data['admin_id']=''; //new line 12:39 30/03/16
$this->load->view('edit_student',$data);
}
public function add()
{
$data = array(
'student_name' => $this->input->post('txt_name'),
'student_email' => $this->input->post('txt_email'),
'student_address' => $this->input->post('txt_address'),
'subject' => $this->input->post('subject'),
'marks' => $this->input->post('marks'),
'admin_id' => $this->input->post('admin_id')//new line 12:39 31/03
);
$result = $this->student->add_record($id,$data);
header('location:'.base_url().'index.php/listing');
}
}
Probably the best way would be to use some roles in your system, for instance you can use the Ion auth library:
http://benedmunds.com/ion_auth/
With this you can define user groups (e.g.: user,administrator,superadministrator)
you can check the in_group() part of the manual to see how it works.
An example function to let you get some idea how can you check the record deleting:
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->ion_auth->in_group('administrator', $logged_in_user_id)) {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->ion_auth->in_group('superadministrator', $logged_in_user_id)) {
return true;
}
// other users cannot delete the record
return false;
}
You still can use this example as base of functions.
usage in your code:
public function delete($id)
{
$logged_user_id = $this->session->userdata('admin_id');
if(!hasDeleteRight($id, $logged_user_id))
{
return false;
}
//....your delete record code
update:
permission check without ion auth, only with session data and separated login (not preferred way):
in the super admin login code you can put the permission into session:
function super_admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'superadministrator');
}
}
similar for normal administrator login:
function admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'administrator');
}
}
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->session->userdata('permission') == 'administrator') {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->session->userdata('permission') == 'superadministrator') {
return true;
}
// other users cannot delete the record
return false;
}

Auth not logging in (CakePHP 2.7.5)

I have a CakePHP app that I am trying to upgrade from 1.3 to 2.7.5 and I can hit the log in page but when I go to log in, it doesn't do anything, no errors, just basically refreshes the page. I am really confused why this is happening and would greatly appreciate any help I could get. I did post another question about this but deleted it because it did not provide enough of the code to solve the problem. I have included the AppController as well as the Users controller below.
AppController.php
?php
class AppController extends Controller {
var $components = array('Auth', 'Session', 'RequestHandler');
var $uses = array('Tour');
function beforeFilter() {
$this->setLayout();
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'find_home');
$this->Auth->autoRedirect = false;
if ($this->Session->check('Auth.User.userid')) {
$tour = $this->Tour->findByUserid($this->Session->read('Auth.User.userid'));
$user = $this->Auth->user();
$tour = $this->Tour->findByUserid($user['User']['userid']);
$user['Tour'] = $tour['Tour'];
$this->set('user', $user);
}else if (isset($_GET['token'])) {
$tour = $this->Tour->read(null, $_GET['token']);
if ($tour) {
$tour['Tour']['sessionmodified'] = date('Y-m-d H:i:s');
$this->Tour->save($tour);
$this->set('user', $tour);
}
}
}
private function setLayout() {
if (array_key_exists('prefix', $this->params)) {
if ($this->params['prefix'] == 'admin') {
$this->layout = 'admin';
}else if ($this->params['prefix'] == 'teacher') {
$this->layout = 'teacher';
}
}
}
}
?>
UserController.php
function login() {
if (!empty($this->data) && $this->Auth->user()) {
// Delete all old tokens
$this->Tour->recursive = -1;
$this->Tour->deleteAll(array('Tour.userid' => $this->Auth->user('userid')));
// Create a new token
$this->Tour->create();
$this->Tour->save(array('token' => md5(rand()), 'userid' => $this->Auth->user('userid')));
// Update login count
$user = $this->User->read(null, $this->Auth->user('userid'));
$user['User']['logincount']++;
$this->User->saveField('logincount', $user['User']['logincount']);
// Update last login time
$this->User->saveField('lastlogin', date('Y-m-d h:m:s'));
$this->redirect($this->find_home());
}
}
function logout() {
if (!empty($this->data) && $this->Auth->user()) {
// Delete any tours
$this->Tour->recursive = -1;
$this->Tour->deleteAll(array('Tour.userid' => $this->Auth->user('userid')));
}
$this->redirect($this->Auth->logout());
}
function index() {
$this->layout = false;
$this->autoRender = false;
Configure::write('debug', 0);
ini_set('soap.wsdl_cache_enabled', '0');
$server = new SoapServer('http://' . $_SERVER['HTTP_HOST'] . $this->webroot . 'users/wsdl');
$server->setClass('User');
$server->handle();
}

how to validate duplicate email in magento admin on edit and add in custom module

I need to validate duplicate email in magento on edit and add action. Basically on edit if i changed email id if that is available in database then i need to got message duplicate email.... if I add then i also want to validate duplicate email in magento.
my save function in admin
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try {
$postData = $this->getRequest()->getPost();
$currentTimestamp = time();
$postData['updated_at']= $currentTimestamp;
$postData['seller_other_sale_sites'] = implode(',',$postData['seller_other_sale_sites']);
$sellerModel = Mage::getModel('seller/seller');
if( $this->getRequest()->getParam('id') <= 0 )
$sellerModel->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate()
);
$sellerModel
->addData($postData)
->setUpdateTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'))
->save();
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->settestData(false);
$this->_redirect('*/*/');
return;
} catch (Exception $e){
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->settestData($this->getRequest()
->getPost()
);
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
I need to validate that on save function
Create a function in helper class that takes $email as parameter
public function customerExists($email, $websiteId = null)
{
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($email);
if ($customer->getId()) {
return $customer;
}
return false;
}
Before you perform save operation, use the helper function this way.
Mage::helper('modulename')->customerExists($email, $websiteId);
If a customer is already there it will return the customer object and if it doesn't, it will return false. So you can write remaining code/throw exception/ set error message accordingly.
from Mage_Customer_Model_Resource_Customer this code checks for unique email _beforeSave before save (unless updating an existing customer in which case it checks for duplicates on just that customer).
This is within the Mage system, but doesn't use any models.
$adapter = $this->_getWriteAdapter();
$bind = array('email' => $customer->getEmail());
$select = $adapter->select()
->from($this->getEntityTable(), array($this->getEntityIdField()))
->where('email = :email');
if ($customer->getSharingConfig()->isWebsiteScope()) {
$bind['website_id'] = (int)$customer->getWebsiteId();
$select->where('website_id = :website_id');
}
if ($customer->getId()) {
$bind['entity_id'] = (int)$customer->getId();
$select->where('entity_id != :entity_id');
}
$result = $adapter->fetchOne($select, $bind);
if ($result) {
throw Mage::exception(
'Mage_Customer', Mage::helper('customer')->__('This customer email already exists'),
Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS
);
}

Cannot edit particular user data with user id by form using yii framework

I am new in YII framework. I am doing update operation using YII framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php.
I got the error:
Fatal error: Call to a member function isAttributeRequired() on a non-object in E:\wamp\www\yii\framework\web\helpers\CHtml.php on line 1414
My table is job_seeker_profile
Fields
1.id
2.user_id
3.contact_no
4.gender
5.dob
6.mstatus
7.address
8.location_id
I want to edit the data in contact_no and address according to user_id
Model-Jobseekerprofile.php - rules
public function rules()
{
return array(
array('contact_no,address','required'),
);
}
controller-Sitecontroller.php
class SiteController extends Controller {
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model=Jobseekerprofile::model()->find(array(
'select'=>'contact_no,address',"condition"=>"user_id=$user_id",
'limit'=>1,));
$model = Jobseekerprofile::model()->findByPk($user_id);
if(isset($_POST['Jobseekerprofile']))
{
$model->attributes=$_POST['Jobseekerprofile'];
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
}
$this->render('personal',array('model' =>$model));
}
}
Anybody help me?
Seems that $model = Jobseekerprofile::model()->findByPk($user_id) is not finding anything, so $model is null, and that is why $model->isAttributeRequired() throws an error. Check your incoming params because of this and check if there a profile with such id (or maybe you should search by attributes instead of by id?).
Besides you can use
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
//
}
Instead of
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
//
}
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile']; //post key edited
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
}
First Check what you are getting in $_POST
and if all is ok then try to save like
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['jobseekerprofile'];
$model->contact_no= $_POST['Jobseekerprofile']['contact_no']; //post key edited
$model->address = $_POST['Jobseekerprofile']['address'];
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
if not work then check what model returns
$error=$model->getErrors();
print_r($error);
above code surely gives you idea why it is not saving

Categories