excuse me I want to ask, about how to make permission rules from my user table in yii2 framework,
which I have a table named user.in it contains a column of positions with the contents "user" and "admin" I want to set that when logging in only my admin can upload files.
I want to know how to solve it??
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'rulesConfig' => ['class'=> AccessRule::className()
],
'only' => ['upload'],
'rules' => [
[
'allow' => true,
// 'actions' => ["upload"],
'roles' => ['#'],
],
],
],
];
}
There is the possibility to use the PHPManager, which saves the roles within files.
Or the DBManager, which brings its own database tables where it stores the things.
There is a wonderful article by Yii that might help you, it explains everything in detail.
Link to Guide
Related
I have a custom controller and I'm trying to define an action in the controller that could be accessed by the guest users.
My controller code is the following:
class MyCustomController extends Controller
{
...
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
'access' => [
'class' => AccessControl::class,
'only' => ['live'],
'rules' => [
[
'allow' => true,
'actions' => ['live'],
'roles' => ['?'],
],
]
]
];
}
/**
* Live action.
* #return mixed
*/
public function actionLive()
{
return $this->render('live');
}
...
}
And the view code is this:
<?php
echo 'We are live!!';
?>
I also have this setting in frontend/config/main.php
return [
...
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
...
]
When I try to access the page http://my-webapp/my-custom/live as an authenticated user I get the message Forbidden (#403) which is ok (although displaying it for the authenticated users would be perfectly ok too).
But when I access that page as a guest user I get redirected to the login page. I just want to disable the redirect for this particular action and just let the guest users see that view.
You are applying AccessControl filter twice.
First filter is set for Application so it is applied for each request with following rules:
If the action id is "login" or "error" allow any user.
Allow logged in users
Deny any other request.
The second filter is for MyCustomController and it's set to apply only for requests to action live of that controller with following rules:
Allow any user who is not logged in.
Deny any other request.
So when request comes from user who is logged in, the request is stopped by second filter and the 403 error is displayed.
When request comes from guest user it is stopped by first filter and user is redirected to login page.
To allow guests access your action you should add exception to first filter to make sure only second AccessControl filter is applied:
return [
//...
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'except' => ['my-custom/live'],
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
...
];
Actually, if you are OK with allowing any user to see the my-custom/live there is no need for the second AccessControl filter. Just setting the exception in the first (application wide) filter will be enough.
i am new in yii2 and using advance template .
i am using yii2/admin for roles , permission. but i can't get the menu manage using yii2/admin
the image for the menu manage
like this
how to get this interface for manage menu
i read this
when i run
(index.php?r=admin/menu)
i got an error
Invalid Configuration – yii\base\InvalidConfigException
The table does not exist: {{%menu}}
how to create menu table.
i got a migration file from
vendor/mdmsoft/yii2-admin/migrations/m140602_111327_create_menu_table.php
how to run this migration
please go through with this link MDM Yii2-admin Basic Configuration
add in backend/congif/main.php
'modules' => [
'admin' => [
'class' => 'mdm\admin\Module',
'layout' => 'left-menu', // it can be '#path/to/your/layout'.
'controllerMap' => [
'assignment' => [
'class' => 'mdm\admin\controllers\AssignmentController',
'userClassName' => 'common\models\User',
'idField' => 'id'
],
],
'menus' => [
'assignment' => [
'label' => 'Grand Access' // change label
],
'route' => null, // disable menu route
]
],
],
for run migration use this, through cmd/terminal
yii migrate --migrationPath=#mdm/admin/migrations
So I have seen post on how to set the default route in Yii 1 whereby the initial page is the login page, but no posts on how to do this in Yii 2.
What I need is for all users to first login and to then be able to use CRUD functions, with some users able to do more than others.
For your information, I am using the basic template.
try in basic\config\web.php
add 'loginUrl' => ['user/login'], to user in components
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'loginUrl' => ['user/login'],
],
// ...
]
Just thought to make the solution visible here. Found via at https://www.yiiframework.com/forum/index.php/topic/54255-newbies-question-to-yii2-how-can-i-force-user-to-login/ by vishwasrao, and a similar post here Yii2 global filter/behavior to force user to authenticate first by jagsler.
For Basic template, in config/web.php, add the following 'as access' section:
'components' => [ ... ],
'as access' => [
'class' => \yii\filters\AccessControl::className(),//AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'], // add all actions to take guest to login page
'allow' => true,
'roles' => ['#'],
],
],
],
'params' => $params,
Hope this helps anyone still looking for this.
I am trying to setup Yii2 advanced like a traditional user/admin system. Frontend would be /user and backend would be /admin, and would use their respective table in the database (user and admin). I have not renamed frontend and backend to user and admin yet..
Using migrate generated the 'user' table, with all it's fields. I registered to create a new user, all that works perfect. I then copied the 'user' table and named it 'admin', and changed the username to admin. I can change the password, or truncate it, register new admin user, then remove the registration from the backend later. The admin table in the db itself isn't the issue as I am not getting that far when I reach the error..
I have setup and used Yii2 advanced just fine on the frontend (user) side of it. Of course, you have Yii::$app->user and it works just fine on the frontend. I can login, it uses the 'users' table. Frontend works great...
Now on the backend (admin) I need it to use the 'admin' table. I know you specify the table to use in the model. I copied /common/models/User.php and have /common/models/Admin.php and updated the function to use the 'admin' table instead.
I also copied /vendor/yiisoft/yii2/web/User.php and put it in /common/models/web/Admin.php (and renamed the name of the class from User to Admin)
Then I edited the /backend/config/main.php to reflect the changes for Admin (class and identityClass).
/backend/config/main.php
'components' => [
'admin' => [
'identityClass' => 'common\models\Admin',
'class' => 'common\models\web\Admin',
'enableAutoLogin' => true,
],
],
/common/models/web/Admin.php
class Admin extends Component { ... }
/common/models/Admin.php
class Admin extends ActiveRecord implements IdentityInterface {
public static function tableName()
{
return '{{%admin}}';
}
}
Error: User::identityClass must be set. <-- As you can see, it's still references the User model some how...
Also, when I get this setup, would I use Yii::$app->admin instead of Yii::$app->user ? Like for checking if they are logged in using isGuest.
I want to be sure that a user can't login to frontend, then manually go to backend and be logged in!
I have solved this :)
You have to edit the main config of each (frontend and backend) and specify the 'identityClass' for the user component, and add 'session' and 'request' to the list.
Example of frontend config:
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
]
],
'session' => [
'name' => 'PHPFRONTSESSID',
'savePath' => sys_get_temp_dir(),
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '[RANDOM KEY HERE]',
'csrfParam' => '_frontendCSRF',
],
],
Example of backend config:
'components' => [
'user' => [
'identityClass' => 'common\models\Admin',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_backendUser', // unique for backend
]
],
'session' => [
'name' => 'PHPBACKSESSID',
'savePath' => sys_get_temp_dir(),
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '[DIFFERENT UNIQUE KEY]',
'csrfParam' => '_backendCSRF',
],
],
For a more detailed guide, you can read the wiki I created.
Wiki: [Guide] How to actually separate Frontend and Backend on Yii2 Advanced
In my Yii2 application I'm trying to force all users to be authenticated. If they're not already authenticated they should be redirected to the login page.
In Yii1 I did this by creating a class that would check if a user was logged in and attaching that class to the onBeginRequest behavior in my main config file.
// Yii 1
'behaviors' => array(
'onBeginRequest' => array(
'class' => 'application.components.RequireLogin',
)
),
How can I get the same behavior in Yii2? I know I can use behavior to do this, but I wan't to add this behavior to my main config file so all requests are first checked for authentication.
The working behaviors method looks like this:
// Yii2
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
Ok, so I had to add the following code below 'components' => [...]
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
Read more about the format: http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#configuration-format
I'm actually not versed into Yii2 (but very much so into Yii1).
One solution that can be employed in Yii1 and I guess also in Yii2 is having a filter method in a master Controller class. Typically a single controller serves as a master controller. If you don't have one, create it and everyone should extend it. You can implement this probably not as a filter but in other methods of this 'master controller' (init() ?)
If all activity is going through controller class then you're set.