I have a controller as admin
and another as guest
. I want to have some http
requests to a static address like test.com/guest/index
, and have this results:
if the user(determined in request body as a username
) is an admin
(actually not-guest
) user then it should port the request(not redirect, because redirect cant be done in an api-client, and of course http request cant move along the methods on redirect) to a specific method of admin
controller.
like i send a POST
request to test.com/guest/index
and I am admin
so it should run the methodName()
- I should specify the name not the request - from admin
controller and if somebody else who is not admin
send the same request it should run methodName()
(same method name) from guest
controller.
how can this be done? I use Yii2. so I want to know is there any way to do this or if there is no way so is it possible in a single controller with different method names? is it possible in ACL extension? thanks
I suggest creating single controller named GuestController
and process request not based on sent information, but on current user status:
class GuestController extends yii\web\Controller {
public function actionIndex() {
$response = null;
$model = User::getByCredentials();
if (!$model) {
$response = $this->guestAction();
} else {
switch ($model->role) {
case 'admin':
$response = $this->adminAction();
break;
case 'user':
$response = $this->someUserAction();
break;
}
}
echo $response;
}
protected function adminAction() {
$data = \Yii::$app->request->post(); // still can access _POST/_GET...
return 'Hallo Warold!';
}
/* ... */
}
/**
*
*/
class User extends yii\web\ActiveRecord {
public funcion getByCredentials($username, $password) {
$model = self::findOne(['username' => $username]);
if (!empty($model) && \Yii::$app->security->validatePassword($password, $model->password)) {
return $model;
}
return null;
}
}