I am using Ion Auth for my codeigniter application and all seems good except for one thing.
I need to display a list of users along with the groups they are in. How can I retrieve the group id of a particular user without making my own models and querying for it.
$this->ion_auth->user($id)->row(); does not retrieve the group id.
Ion Auth has updated and removed the get_user function in the latest version. As a result of this, the below should return the current group id of the logged in user:
$this->ion_auth->get_users_groups()->row()->id
If you're wanting to get the group id of a particular user, you can pass the user id into the get_users_groups method.
get the Object:
$user_groups = $this->ion_auth->get_users_groups($user->id)->result();
Get the name of the group:
$this->ion_auth->get_users_groups($data['id'])->row()->name;
In my case:
$data['groups'] = $this->ion_auth->get_users_groups($data['id'])->row()
You can check the offcial doc about get users groups:
http://benedmunds.com/ion_auth/#get_users_groups
I came across this because I wanted to add a user's group_id(s) to the session upon successful login. In case anyone is interested, here's how I did it (once i managed to figure out where everything was being done).
In ion_auth_model.php, I took the set_session function:
public function set_session($user)
{
$this->trigger_events('pre_set_session');
$session_data = array(
'identity' => $user->{$this->identity_column},
'username' => $user->username,
'email' => $user->email,
'user_id' => $user->id, //everyone likes to overwrite id so we'll use user_id
'old_last_login' => $user->last_login
);
$this->session->set_userdata($session_data);
$this->trigger_events('post_set_session');
return TRUE;
}
and modified it to this:
public function set_session($user)
{
$this->trigger_events('pre_set_session');
$session_data = array(
'identity' => $user->{$this->identity_column},
'username' => $user->username,
'email' => $user->email,
'user_id' => $user->id, //everyone likes to overwrite id so we'll use user_id
'old_last_login' => $user->last_login
);
//get user group ids for user and pass to session
$groups = $this->ion_auth->get_users_groups($user->id)->result();
foreach ($groups as $row){
$session_data['groups'][] = $row->id;
}
$this->session->set_userdata($session_data);
$this->trigger_events('post_set_session');
return TRUE;
}
now it writes an array to the session called groups that is a list of all the groups the user belongs to.
The only other thing I had to do was to modify the logout function in Ion_auth.php (in application/libraries) to make sure the group session variable is unset by adding
$this->session->unset_userdata('groups');
to the list of other unset_userdata() statements.
I know I probably should have just extended the libraries/models to keep the core untouched, but you could take what I did and easily do that.
hope this helps someone.
Rob
Try adding this to ion_auth_model.php
(Or place the query somewhere else)
/**
* get_all_users_with_group
*
* #return array
**/
public function get_all_users_with_group()
{
$this->trigger_events('get_all_users_with_groups');
return $this->db->select(
$this->tables['users'].'.*, '.
$this->tables['users_groups'].'.'.$this->join['groups'].' as group_id, '.
$this->tables['groups'].'.name as group_name, '.
$this->tables['groups'].'.description as group_desc'
)
->join($this->tables['users_groups'], $this->tables['users_groups'].'.'.$this->join['users'].'='.$this->tables['users'].'.id')
->join($this->tables['groups'], $this->tables['users_groups'].'.'.$this->join['groups'].'='.$this->tables['groups'].'.id')
->get($this->tables['users']);
}
use in the controller:
$groups = array(1,2,3,4);
$this->data['list_staff'] = $this->ion_auth->users($groups)->result(); // выбираем всех teachers из зарегистрированных пользователей
foreach ($this->data['list_staff'] as $k => $one_staff)
{
$this->data['list_staff'][$k]->groups = $this->ion_auth->get_users_groups($one_staff->id)->result();
}
and in view use:
<?php foreach($list_staff as $one):?>
<?php foreach ($one->groups as $group):?>
<?php echo $group->description;?>,
<?php endforeach?>
<?endforeach;?>
but what about query to get groups for current logged in user (for example in my profile) I find next decision.
Controller:
$this->data['this_user_groups'] = $this->ion_auth->get_users_groups()->result();
and view just:
<?php foreach ($this_user_groups as $group):?>
<?php echo $group->description;?>,
<?php endforeach?>
Related
How to fetch data from database based on current user login? As example, when user login and click the profile bar, it only display his/her data only. I've tried before but it display all data of user.
At personalinfo.php
<?php foreach ($personals as $user):?><?=Html::encode("{$user->username}")?><?php endforeach;?>
<?php foreach ($personals as $user):?><?=Html::encode("{$user->user_id}")?><?php endforeach;?>
<?php foreach ($personals as $user):?><?=Html::encode("{$user->email}")?><?php endforeach;?>
At controller
public function actionPersonalinfo()
{
$query = User::find()->all();
return $this->render('personalinfo', [
'personals' => $query
]);
}
I think because of $query = User::find()->all();. But I dont know how to replace it so that it will retrieve data based on current user login. I'm very new with yii2. Sorry and thank you
Replace your code with :
At personalinfo.php
User Id : <?php echo $personals->user_id; ?>
Username: <?php echo $personals->username; ?>
Email : <?php echo $personals->email; ?>
At controller
public function actionPersonalinfo() {
$query = User::findOne(Yii::$app->user->id);
return $this->render('personalinfo', [ 'personals' => $query ]);
}
if you want to retrieve data based on current logged in user. you should add condition on your query.
something like:
$user = User::findOne(Yii::$app->user->id);
also, if you are only need to returns a single Active Record instance, you don't need to loop on your view.
I am adding AWeber as an autoresponder in a web application. Using AWeber API, I am able to add a new subscriber to list with a known name which is in this case is firstlist:
$app = new MyApp();
$app->findSubscriber('whtever#aol.com');
$list = $app->findList('firstlist');
$subscriber = array(
'email' => 'someemail#gmail.com',
'name' => 'Name here'
);
$app->addSubscriber($subscriber, $list);
Function definition for findList() is:
function findList($listName) {
try {
$foundLists = $this->account->lists->find(array('name' => $listName));
return $foundLists[0];
}
catch(Exception $exc) {
print $exc;
}
}
As I am developing a public application, so I need to provide users an option to select from their available lists.
Please guide me how I can retrieve all the lists name.
You are returning $foundLists[0] so it will return single list. Try to return foundLists and check what it returns.
This may help you: https://labs.aweber.com/snippets/lists
In short, I pulled the lists by first finding the Aweber User Id so that I could use it in the URL https://api.aweber.com/1.0/accounts/<id>/lists
To find the User ID, I first got the account.
$this->aweber->getAccount($token['access'], $token['secret']);
Then, I retrieve the user's information.
$aweber_user = $this->aweber->loadFromUrl('https://api.aweber.com/1.0/accounts');
From that, I grabbed the user ID with...
$id = $aweber_user->data['entries'][0]['id'];
Once I had the user ID, I could then retrieve their lists with...
$lists = $this->aweber->loadFromUrl('https://api.aweber.com/1.0/accounts/'.$id.'/lists');
This example is more of a procedural approach, of course, I recommend utilizing classes.
I'm currently busy with a project that needs users to go to a specific page to create a profile when they log in for the first time (and haven't created one yet). Honestly, I don't know where to start. I would like to do it in a good way.
So in short:
User signs up -> logs in -> needs to fill in form before anything else is allowed -> continue to rest of application
Question: What is a neat way to do this? A solution that isn't going to give me problems in the future development of the application.
I suggest you to use filters. In every controller where the completed profile is neeeded add this code:
public function filters() {
return array(
'completedProfile + method1, method2, method3', // Replace your actions here
);
}
In your base controller (if you don't use base controller, in any controllers) you need to create the filter named completedProfile with the simular code:
public function filterCompletedProfile($filterChain) {
$criteria = new CDBCriteria(array(
'condition' => 'id = :id AND firstname IS NOT NULL AND lastname IS NOT NULL',
'params' => array(':id' => Yii::app()->user->getId())
));
$count = User::model()->count($criteria);
if ($count == 1) {
$filterChain->run();
} else {
$this->redirect(array('user/profile'));
}
}
Possibly add a field to the user profile database table which denotes if they have filled out their profile information. Something like profile_complete. Then you can do a test on pages to see if profile_complete is true and display the page if so, and display the profile page if not.
I already created as session named "verified" as shown below (in my login controller):
foreach($result as $row)
{
$sess_array = array(
'id' => $row->memberid, //Session field: id.
'username' => $row->member_userunique //Session field: username.
);
// Create a session with a name verified, with the content from the array above.
$this->session->set_userdata('verified', $sess_array);
}
Now, when a user open a page called book (with a controller named book) i want to add one more additional variable called "book_id" to my "verified" session.
This is what i have done
function index()
{
//Add a new varible called book_id
$this->session->set_userdata('book_id', $titleID);
}
When i tried to retrieve the 'book_id' using the following method:
$session_data = $this->session->userdata('verified');
$article_id = $session_data['book_id'];
$user_id = $session_data['id'];
It only able to retrieve the 'id' however the 'book_id' is not defined. But if do a var_dump() on $this->session->all_userdata() i can see that the 'book_id' session variable has been successfully appended.
After reading the CI documentation about session, i realized that the code above will not work as i have not tell it to which session should i add the variable to.
Can anyone point me to the right direction?
You do as follows in your index() method:
$session_data = $this->session->userdata('verified');
$session_data['book_id'] = "something";
$this->session->set_userdata("verified", $session_data);
This way you retrieve the contents of the variable (i.e. the array that you persisted earlier), you add another key to the array (book_id), and then store it again. Now you will be able to do, as I assume you want to:
$sess = $this->session->userdata("verified");
echo $sess['book_id'];
I'm trying to grant a specific role to users that order an amount equal or greater than 100.00 €: Conditional Actions is going really near the achievement, but I'm failing on the action (PHP required).
How can I grant a role using a PHP action in Ubercart Conditional Actions?
Based on a couple of related threads, I think you want to add an "Execute custom PHP code" action along the lines of the following (substituting in the appropriate role name in line #3):
if($account) {
$uid = $account->uid;
$role_name = 'YOUR SPECIFIC ROLE NAME GOES HERE';
$rid = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role_name));
// Load user object
$account = user_load(array('uid' => 1));
// Save the user object with the new roles.
if ($account !== FALSE) {
$roles = $account->roles + array($rid => $role_name);
user_save($account, array('roles' => $roles));
watchdog('user', 'uc ca added role to Ubercart created user');
Code provided needs to close two brackets. I dropped the if statements, grabbed the uid from the order and fixed the uid setting (it was '1'):
$uid = $order->uid;
$role_name = 'customer';
$rid = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role_name));
// Load user object
$account = user_load(array('uid' => $uid));
// Save the user object with the new roles.
$roles = $account->roles + array($rid => $role_name);
user_save($account, array('roles' => $roles));
watchdog('user', 'uc ca added role to Ubercart created user');