Yii2 get role of the logged in user - yii2

Can someone please explain to me how to use this function
getRoleByUser()
for related tables to get role of logged in user
I tried this
$Role = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
print_r($Role);
exit();
but I got the following error
Getting unknown property: yii\web\Application::findByUsername

Try this
\Yii::$app->authManager->getRolesByUser($user_id);
From the auth manager you can get it.

use
$userRole = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
like
if ($userRole) {
foreach ($userRole as $role) {
$roles[] = $role->name;
}
// if user have 1 role then $userRole will be a string containing it
// othewhise let $userRole be an array containing them all
$userRole = count($roles) === 1 ? $roles[0] : $roles ;
}

Related

Token cannot be null on the instantiation of the Product Query Builder. / Query Akeneo 2

I would like to create a command akeneo into my bundle who query my products like this.
So, after multiple test, i have always this error:
In ProductQueryBuilderFactory.php line 68:
Token cannot be null on the instantiation of the Product Query
Builder.
Here is my code :
$pqbFactory = $this->getApplication()->getKernel()->getContainer()->get('pim_catalog.query.product_query_builder_factory');
$pqb = $pqbFactory->create(['default_locale' => 'fr_FR', 'default_scope' => 'ecommerce']); // error
To complete Julien's answer, note that this error comes only if you are using the Enterprise Edition (EE). Indeed, in the EE, we decorate the normal product_query_builder_factory to apply permission.
If you don't want to apply permission (and don't use any token), you can use the pim_catalog.query.product_query_builder_factory_without_permission:
<?php
require __DIR__.'/vendor/autoload.php';
$kernel = new AppKernel('dev', true);
$kernel->boot();
$pqbFactory = $kernel->getContainer()->get('pim_catalog.query.product_query_builder_factory_without_permission');
$pqb = $pqbFactory->create(['default_locale' => 'fr_FR', 'default_scope' => 'ecommerce']); // you won't have any error
The PQB needs to have an authenticated user to be able to apply right filters on the results. To authenticate a user in your command you can take inspiration from the get product command. We simply take a --username argument and manually add it to the token storage.
$userManager = $this->getContainer()->get('pim_user.manager');
$user = $userManager->findUserByUsername($username);
if (null === $user) {
$output->writeln(sprintf('<error>Username "%s" is unknown<error>', $username));
return false;
}
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->getTokenStorage()->setToken($token);

Set user permissions on each module in Yii2

I would like to set user permissions on each module.
Each module would have its table with the permissions. What is the most recommended way to do this?
Reason: My application has some optional modules for only a few clients.
UPDATE
Something like:
Table: mod_inventory_permission
id int
User_id int
Read_permission boolean
Write_permission boolean
Admin_permission boolean
You can use RBAC for it! you can set different modules in it and different permission for each module.
Yes you can do it by using Rbac which facilitate you to restrict user in same application to limited modules,controllers, or actions
You have to follow the following step i hope it will help you.
I suggest you to use the auth_ tables provided by yii2 for rbac
step 1: import all auth tables
step 2: Create different roles in auth_item tables with type = 1 and all permission with type = 2
Note
Please make sure you enter your permission in some specific pattern,i am using module/controller/action,
its up to you how you are going to implement it.
step 3: Create generic controller and extend all of your controller from this generic controller,
In your generic controller you have to check whether the user is allow to access the module,controller or action he/she want to access of not.
public function beforeAction($action) {
$module = Yii::$app->controller->module->id;
$controller = ucfirst(Yii::$app->controller->id);
$action = Yii::$app->controller->action->id;
if (Yii::$app->user->can($module)) {
if (Yii::$app->user->can($module . '/' . $controller)) {
return true;
}
if (Yii::$app->user->can($module . '/' . $controller . '/' . $action)) {
return true;
}
else {
throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
}
} else {
throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
}
}
The beforeAction function implement 3 layer authentication you can change it according to your requirements....
i hope it will help you

How to conditionally use different database in CodeIgniter

Here is my scenario.
A user will login to the system. Based on the username, I need to set the database in codeigniter configuration.
I know that the line $this->load->database() in each model loads the default database.
So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?
Below is something that I am looking for:
if(username == 'foo'){
$this->load->database('database_name');
}
An example of a model function that I have written is as follows:
public function check_valid_login($username, $password){
$this->db->from('tbl_user_details');
$this->db->where('email_address', $username);
$this->db->where('password', md5($password));
$query = $this->db->get();
$rowcount = $query->num_rows();
return $rowcount ;
}
On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution.
This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user.
The following logic is used for selecting the database dynamically. The below code is written in config/database.php
/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
$dynamic_db_username = $_SESSION['dynamic_db_username'];
if($dynamic_db_username == 'sample#domain.com')
{
$db['default']['database'] = 'database_1';
}
elseif($dynamic_db_username == 'sample2#domain.com')
{
$db['default']['database'] = 'database_2';
}
else
{
$db['default']['database'] = 'database_1';
}
}
else
{
$db['default']['database'] = 'database_1';
}
/*End*/
Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php
open the file
find first this code below
$autoload['libraries'] = array('');
you have to put "database" in the array , changed code will be like
$autoload['libraries'] = array('database');
after that you can use your database anytime and anywhere without loading it manually .

How to update the changed username in session variable without logout or session destroy

Question:
How to update the changed username in session variable without logout or session destroy ?
For Example:
I am login with username "Ram" and this username storing in session variable User_Name,after logged in i am changing my username "Ram" into "Kumar". So this newly changed username should get updated in session variable User_Name automatically without logout from my account.
Sample Controller Code for Login:
function check_database($password)
{
// Field validation succeeded. Validate against database
$username = $this->input->post('username');
// query the database
$result = $this->civic_soft_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'UID' => $row->UID,
'User_Name' => $row->User_Name,
'User_Type' => $row->User_Type,
'User_OTP' => $row->User_OTP
// 'Login_Status' => $row->Login_Status
// 'Node_Id' => $row->Node_Id
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
NOTE:
I am using PHP,MySQL and CodeIgniter MVC Framework.
Please Help Me Friends...
I actually see what the problem is now. You are setting 'logged_in' to be an array. Not sure if that's common, but what I usually do is set 'logged_in' as a boolean and I set userdata the data that I need in another array.
However, for you case you can try this:
$newUserData = $this->session->userdata('logged_in');
if (is_array($newUserData)) {
$newUserData['User_Name'] = $new_username;
$this->session->set_userdata('logged_in', $newUserData);
}
For better usability, I would addd a function to $this->civic_soft_model called "updateUser" or something of that nature. And when that function is called, you can update all of the session data that you need to.
Insert this function to your controller and call it whenever there is an update made on the users information.
//$new_username : the username inputted by user when he is trying to update his account
function update_session($new_username){
$this->session->set_userdata('User_Name', $new_username);
}

Return id from combined functions

I'm trying to optimize a platform I created, and removing code that maybe aren't necessary. and since I started read about PHP classes and decided to rewrite the entire function page.
I'm having two functions for my login page.
valid_credientials($email,$password){} and
function fetch_user_id($email){ }
the fetch_user_id returns the id from logged in user, so my session would change from session email to session uid.
Now Am i trying to combine this two function, but i get only error messages so i was thinking, that maybe i need this two function ?
This is what i have for now.
public function valid_credientials($email,$password){
if(!empty($email) && !empty($password)){
$query = $this->db->prepare("SELECT id FROM user WHERE email=? AND password=?" );
$query-> bindParam(1, $email);
$query-> bindParam(2, $password);
$query-> execute();
if($query->rowCount() == 1){
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row[id];
echo "user verified Access granted";
}
}else{
echo 'Wrong Username of password';}
}
}
function fetch_user_id($email){
global $db;
$query = $db->query("SELECT id FROM user WHERE email='{$_SESSION['email']}'");
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row[id];
}
As you see am i trying to use the $row = query inside the valid_credential function.
but it only returns error - undefined constant id - assumed 'id' in.
thanks!