php - CakePHP Controller beforeFilter custom validation to prevent save data into DB
I have a Controller and a few functions inside. Some function are basically save data into DB. One of the function require a filter that specific type of user can't do write access into DB.
My question is how do I block to save data into db for specific user role.
class TestController extends AppController {
public function beforeFilter(){
if(in_array($this->action, ['f1','f2'])) {
if($this->authenticatedUser['role'] == 'readonly') {
//return message
//block save data into db
}
}
}
public function f1() {
//save data into db
}
public function f2() {
//save data into db
}
public function f3() {
}
}
When I tried to write using f1 or f2, it goes to beforeFilter
and show the message as well but data save into db also. How should I block it while I tried to write data into db on beforeFilter
.
Answer
Solution:
Here is some logic:
check if the request is a post
check which method is requested
if both checks match, create a flash message and make a GET redirect to the desired method
if($this->request->is('post') && in_array($this->action, ['f1','f2'])) { if($this->authenticatedUser['role'] == 'readonly') { //set flash message //get redirect to action } }
Next
function f1() {
// if request is post, save data
// else return find data or empty object / array
}
Source