/** * beforeSave callback * * Prevent saving if the context is not global * * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that was saved. * @return void */ public function beforeSave(Event $event, Entity $entity, $options) { if (MTApp::getContext() == 'tenant') { //save new operation $field = $this->config('foreign_key_field'); if ($entity->isNew()) { // Model is no required to have a foreign_key_field to tenant, // But if one exists we will update it // no overwrite, if foreign_keyfield has an assigned value, do nothing if ($entity->{$field} === null) { $entity->{$field} = MTApp::tenant()->id; } } } return true; }
/** * beforeDelete callback * * Prevent delete if the record is global * Prevent delete if the record belongs to another tenant * * @param \Cake\Event\Event $event The beforeDelete event that was fired. * @param \Cake\ORM\Entity $entity The entity that was saved. * @return void */ public function beforeDelete(Event $event, Entity $entity, $options) { if (MTApp::getContext() == 'tenant') { $field = $this->config('foreign_key_field'); //tenant cannot delete global records if he is not the onwer of the global tenant if ($entity->{$field} == $this->config('global_value') && MTapp::tenant()->id != $this->config('global_value')) { return false; } //paranoid check of ownership if ($entity->{$field} != MTApp::tenant()->id) { //current tenant is NOT owner throw new DataScopeViolationException('Tenant->id:' . MTApp::tenant()->id . ' does not own ' . $this->_table->alias() . '->id:' . $entity->id); } } return true; }
/** * beforeDelete callback * * Prevent delete if the context is not global * * @param \Cake\Event\Event $event The beforeDelete event that was fired. * @param \Cake\ORM\Entity $entity The entity that was saved. * @return void */ public function beforeDelete(Event $event, Entity $entity, $options) { if (MTApp::getContext() == 'tenant') { $field = $this->config('foreign_key_field'); //paranoid check of ownership if ($entity->{$field} != MTApp::tenant()->id) { //current tenant is NOT owner throw new DataScopeViolationException('Tenant->id:' . MTApp::tenant()->id . ' does not own ' . $this->_table->alias() . '->id:' . $entity->id); } } else { throw new DataScopeViolationException('Tenant Scoped accessed globally'); } return true; }