CakePHP 2.0 Accessing model field values for view/controller comparisons - Only letting users edit/delete their own posted items - cakephp

I am fairly new to CakePHP, I am trying to only allow those users who created an event to be able to edit or delete an event, so I am comparing the current user id, with the 'user_id' field of the event the current event (saved when a user creates an event). Any help would be appreciated thanks, my code(Andrew Perk) is as follows:
public function isAuthorized($user) {
$this->loadModel('User');
if ($user['role'] == 'admin') {
return true;
}
if (in_array($this->action, array('edit', 'delete'))) {
if ($user['id'] != $this->request->data['Event']['user_id']) { ///THIS IS THE LINE I FEEL IS WRONG - PLEASE ADVISE
//echo debug($event['user_id']);
//$this->Session->setFlash(__('You are not allowed to edit someones event'));
return false;
}
}
return true;
}

There are a few ways you can accomplish this. The one I have found that usually works best is to put a callback in the model that will set the user_id for the record you are trying to modify. Then it doesn't have to get all mixed up in controller everywhere you are trying to CRUD a record.
You can read more about limiting user data here: http://blogchuck.com/2010/06/limit-data-by-user-with-cakephp/
This will also apply to deleting data.
Hope it helps. Happy coding!

Related

Add a user in Cakephp

There is a problem when I write an add() function for UsersController.
public function add() {
if ($this->request->is('post')) {
$this->request->data['User']['book_id'] = $this->Book('id');
if ($this->User->saveAssociated($this->request->data)){
$this->request->data['User']['book_id'] = "ff";
$this->Session->setFlash(__('Save User'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User Error.'));
}
}
If I add a User I want to save the book ID in my User book_id.
Anyone know how to deal with this problem? Thanks!
When you're adding a new user, does he get to select a book from a drop down(in the form)? If so, $this->request->data['User']['book_id'] will already contain the Book id.
There's no need to explicitly write $this->request->data['User']['book_id'] = $this->Book('id'); like you have done.
The way I see it, the add.ctp view file should contain a select box containing a list of all books which the user can select. On selecting one of those and submitting the form, $this->request->data['User']['book_id'] will automatically store the book_id, without having to write anything in the controller.
Please specify the add.ctp form fields so that I can assist you better.
Thanks!

CakePHP: Scaffolding after having written edit/view/add

I have an application in which we give a very friendly interface for managing data. This is done through many controllers' add/edit/view functions. But now the requirement has come that we should have "super admins" able to edit anything, and scaffolding will give them a quick and dirty manner of changing data. Since scaffolding uses add/edit/view by default, I've unintentionally overwritten the ability to scaffold.
I can't just go and change all my calls to edit/add for our "user friendly" data managing. So I want to essentially ignore the add/edit/view when, for example, a user has a flag of "yes, please let me scaffold". I imagined it would be something like:
public function edit($id) {
if (admin_user) {
$scaffold;
} else {
[user-friendly version code]
}
}
But no dice. How can I achieve what I want?
suppose you already have admin users and you want to scaffold only super-user:
Also suppose you store the information about beeing a super-user or not in a column named super in the users table
in your core.php
Configure::write('Routing.prefixes', array('admin', 'super));
in your appController
public $scaffold = 'super';
beforFilter() {
if($this->Auth->user('super') && !isset($this->params['super'])
$this->redirect(array('super' => true));
}
Now I can't try this code but the idea should work.
edit: we need to check if we are already in a super_action to avoid infinite redirect

Validate associated models in CakePHP2

I'm a noob in CakePHP and I've been trying to do some complex validations here:
I have the following models:
- Fonts (name, file);
- Settings(value1,value2,value3,type_id,script_id);
- Types(name)
Whenever I create a Font I also create a default setting associated to it. Also, this setting has a type associated. After the Font is created I can associate more settings to it (Font hasMany Settings), but I need to make sure that two settings of the same type are not added to that font. I don't know how to handle this case. Any help is appreciated. Thanks.
I'd use a simple beforeSave validation
//in setting.php model
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['font_id']) && isset($this->data[$this->alias]['type_id']) {
$otherSettings = $this->find('all', array('conditions'=>
array('type_id'=>$this->data[$this->alias]['type_id'],
'font_id'=>$this->data[$this->alias]['font_id']);
//check if it's insert or update
$updated_id = null;
if ($this->id)
$updated_id = $this->id;
if (isset($this->data[$this->alias][$this->primaryKey]))
$updated_id = $this->data[$this->alias][$this->primaryKey];
if (count($otherSettings) > 0) {
if ($updated_id == null)
return false; //it's not an update and we found other records, so fail
foreach ($otherSettings as $similarSetting)
if ($updated_id != $similarSetting['Setting']['id'])
return false; //found a similar record with other id, fail
}
}
return true; //don't forget this, it won't save otherwise
}
That will prevent inserting new settings to the same font with the same type. Have in mind that this validation will return false if the validation is incorrect, but you have to handle how you want to alert the user of the error. You can throw exceptions from the beforeSave and catch them in the controller to display a flash message to the user. Or you could just not save those settings and let the user figure it out (bad practice).
You could also create a similar function in the model like checkPreviousSettings with a similar logic as the one I wrote above, to check if the settings about to be saved are valid, if not display a message to the user before attempting a save.
The option I prefer is the exception handling error, in that case you'd have to replace the return false with
throw new Exception('Setting of the same type already associated to the font');
and catch it in the controller.
Actually, the better approach is to not even display the settings with the same type and font to the user, so he doesn't even have the option of choosing. But this behind-the-scenes validation would also be needed.

Write Checkbox to CakePHP Session

i would like to have a form where i have an additional checkbox (will not store input to db) which will be readout in the controller.
For Example.
In a Job Edit view i can select a user. Under this user is a checkbox. This checkbox will send after i have assigned the Job to the User an email.
In my Controller i write
$post_array = $this->request->data;
if ($post_array['Job']['mailcheck'] == NULL) {
// DO SOMETHING
} else {
// DO SOMETHING
}
But it doesn´t read out the checkbox value...
Any ideas how to solve this problem?
Thx for help
While mark's answer is correct, allow me to elaborate.
Keep in mind that checkboxes sometimes behave curiously. An unchecked checkbox may not get posted at all, and that may be why your condition fails.
Regarding why you couldn't make it work:
It seems you are performing a redirect in either case, which is why you never see the edit form. Check to see if you missed something or just try this:
if ($this->request->is('post')) {
if (!empty($this->request->data['Job']['mailcheck'])) {
$this->redirect(array('action' => 'sendMails',$id));
} else {
$this->redirect(array('action' => 'sorted'));
}
}
This suffices:
if (!empty($this->request->data['Job']['mailcheck'])) {
// yes, checkbox was selected
} else {
// no, it was not selected
}

Receive model data inside a CakePHP model callback function

I try to use existing model data inside a models callback function in CakePHP 2.1 but can't get it working.
What I do is I try to get a users role in the beforeValidate() callback and check if it's empty. If yes, I'll set it. Normally I do it like this, and for the first creation of the record it works pretty well.
if (empty($this->data[$this->alias]['role']))
$this->data[$this->alias]['role'] = 'user';
The problem is, every time an existing record (user) gets updated, the role will be set again.
Question: So, how do I check if the field role is already set in the record data, not the post data (seems like $this->data[$this->alias] only contains POST data)?
There are three solutions to this problem as I can see it.
Set a default value in the database column (easiest, best?)
Add role to your inputs everytime.
Lookup the user and add a role if it's missing
The first two options seem obvious, so I'll just illustrate the last.
public function beforeValidate() {
if (!empty($this->id) {
$this->data[$this->alias][$this->primaryKey] = $this->id;
}
if (!empty($this->data[$this->alias][$this->primaryKey])) {
// user exists, check their data
$id = $this->data[$this->alias][$this->primaryKey];
$user = $this->find('first', array(
'conditions' => array($this->primaryKey => $id)
));
$this->data[$this->alias]['role'] = $user[$this->alias]['role'];
}
if (empty($this->data[$this->alias]['role'])) {
// new user but missing a role
$this->data[$this->alias]['role'] = 'user';
}
return true;
}
This callback will check if an ID was passed, and if so it will look up the user and populate the role field. Then, it checks for an empty role and fills it with the default if necessary. Obviously he more code you have, the more possibilities for bugs, so I suggest the first option for default column values.
try:
if (empty($this->data[$this->alias]['role']) && empty($this->role)) {
$this->data[$this->alias]['role'] = 'user';
}

Resources