Joomla 3 - How to find if logged in user is registered? - joomla

I have the following code
<?php if ($user->id >= 1): // logged in ?>
This checks to see if the user is logged in but not which group the user belongs to. I'm trying to show content only for registered users.

//Get the logged user
$user = JFactory::getUser($user->id >= 1);
//Set the group id to check against
$group_id = 9;
//see if the user is in bo
if( in_array($group_id, $user->groups ) ){
echo "User is in group"
}else{
echo "user not in group";
}
//Side note: You can also get user groups with the following method
$user->getAuthorisedGroups();

Related

Get user group ID by login user id in joomla?

How to get user group ID by login user id in Joomla?
I try this
$user = JFactory::getUser();
$user_groups = $user->groups;
this return an array.
I want only current group ID.
And is this possible to disable admin menu in Joomla and redirect to any component.
Try this code -
$user = JFactory::getUser();
$groups = $user->get('groups');
foreach($groups as $group) {
echo "<p>You're group ID is:" . $group . "</p>";
}

Add user to group in Joomla not working

I am trying to add a user to a group. I can run this PHP code without any errors, but the user group is still not changed.
<?php
define('_JEXEC', 1);
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
$userId = 358;
$groupId = 11;
echo JUserHelper::addUserToGroup($userId, $groupId);
?>
I run in the same issue with payment callback. I found that user groups save in the database correctly, but are not refreshed in Juser object (becouse You add user to group in different session). When user interacts on a page groups are restored.
Another think that i found is that changing groups in administrator panel works the same way if user is logged in.
To deal with it I made system plugin and in onAfterInitialise function i do:
//get user
$me = JFactory::getUser();
//check if user is logged in
if($me->id){
//get groups
$groups = JUserHelper::getUserGroups($me->id);
//check if current user object has right groups
if($me->groups != $groups){
//if not update groups and clear session access levels
$me->groups = $groups;
$me->set('_authLevels', null);
}
}
Hope it will help.
Possible "Easy" Solution:
The code is correct and it should put your $userId and $groupId in the db to be precise in #__user_usergroup_map .
Btw consider that this method is rising an error if you use a wrong groupId but it's not raising any error if you insert a wrong $userId and for wrong I mean that it doesn't exist.
So there are canches that the user with $userId = 358; doesn't exist.
Update - Hard Debugging:
Ok in this case I suggest you to digg in the code of the helper.
The file is :
libraries/joomla/user/helper.php
On line 33 You have JUserHelper::addUserToGroup.
This is the code:
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();
// If the group does not exist, return an exception.
if (!$title)
{
throw new RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$title] = $groupId;
// Store the user object.
$user->save();
}
if (session_id())
{
// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}
}
return true;
}
The bit that save the group is $user->save();.
Try to var_dump() till there and see where is the issue.
Author already halfish solved this problem so this answer may help to others. It took me hours of debugging with Eclipse and XDebug to find the issue. This error was very tricky because addUserToGroup() was returning true for me and user object was as well with successful changes, but they were not saved in database. The problem was that onUserBeforeSave() method in my plugin was throwing exception whenever addUserToGroup() was trying to save a user. So check your implementation of onUserBeforeSave() if you touched it. If not you must install Eclipse with XDebug and try to debug what is your exact problem.

How to build login api to other sites in Codeigniter different sites ex. IP.Board / wordpress

I'm starting with Codeigniter and i have a question. How (if possible) to create authorization api to other sites (no facebook, twitter etc.).
I have three sites - CI system, IP.Board and WordPress, and my point is a integrating all those systems in one auth api.
I heared about Oauth and OpenId, but I don't know how this things has postponement to CI. Is complicated?
Hello It can be possible
I can suggestion you can use temporary table store that table logged user id and current date& time and also ip address ,and store that one in to Sharing Cookies Across Multiple Domains/send hidden stored id to your multiple site.based on id and ip and time you can implement logic
note: logout and session time out times you can delete the record form table
I have written small example plz check it once . it my be helpful you
Session will most likely not to work. I thought of using JSON but I failed to figure out how to make the Javascript to be dynamic as I always prefer to use jQuery (if you have an idea, feel free to share). In the end, I decided to use PHP along with MySQL and cURL.
We will first start by creating a table to handle the login session:
CREATE TABLE IF NOT EXISTS `sso_login` (`user_id` int(11) NOT NULL)
Purpose of the table is to store logged in users and remove then upon signing out.
Next is the PHP script which will insert new user id upon signing in (file name: register.php):
<?php
/**
*
* #
*/
$userId = $_GET['id'];
$sql = sprintf("INSERT INTO sso_login VALUES ('%s')", $userId);
mysql_query($sql);
?>
Simple, isn’t it? All it does is inserting the user id into the table.
Next is the file which delete the user id when user is signing out (file name: drop.php):
<?php
/**
*
*
*/
$userId = $_GET['id'];
$sql = sprintf("DELETE FROM sso_login WHERE user_id = '%s'", $userId);
mysql_query($sql);
?>
I believe the script is pretty much self-explainatory.
Next is the file which checks whether user is already logged in or vice versa (file name: check.php):
<?php
/**
*
*
*/
$userId = $_GET['userId'];
$sql = sprintf("SELECT COUNT(*) FROM sso_login WHERE user_id = '%s'", $userId);
$query = mysql_query($sql);
if (mysql_result($query, 0, 0) > 0)
{
echo 'User '.$userId.' has logged in';
}
else
{
echo 'User '.$userId.' is not logged in.';
}
?>
This script will check whether the user id being passed is available in the table or not. If not it means that the user have not logged in.
These three scripts will be store on the other party’s server. Next are scripts which will be store on BC’s server where the login and logout process being done. All these processes are using cURL.
First is the script which will update the other site when user is logged in (file name: login.php):
<
?php
/**
*
*
*/
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
if (($username == "bcoffee") && ($password == "demo"))
{
$userId = 10;
$target_site = sprintf("http://the-other-site.com/register.php?id=%s", $userId);
$timeout = 5;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_site);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_exec($ch);
curl_close($ch);
header('location: index.php');
}
}
?>
You might notice that the username and password are hard coded, this was for P.O.C purpose, so it does not matter. Back to the tutorial.
As you can see, it will reach register.php with the user’s id. Refer back to content of register.php which will then insert the user id into the table. This way, the other server will know that user is already logged in.
Next is the script which will notify the other server when the user is signing out (file name: logout.php):
<?php
/**
*
*
*/
$userId = 10;
$target_site = sprintf("http://the-other-site.com/drop.php?id=%s", $userId);
$timeout = 5;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_site);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_exec($ch);
curl_close($ch);
header('location: login.html');
?>
Similar to login.php but this time, it will remove the user id when user is signing out. Hence when the system checks (using check.php) and found that the user id is not available, it will know that the user is not currently logged in.

Joomla 2.5 - How to correctly check if user is guest or member

What is the best (fastest/safest/better for the long run) way to check if a member is signed in Joomla.
1# way: $user =& JFactory::getUser();
if($user->id!=0){
2# way: $user =JFactory::getUser()->guest;
or another way?
These are snippets out of a custom script to check if a user is a guest to tell him to signup and if he signed in to welcome him.
I am using Joomla 2.5
I have read on Joomla 2.5 check user logged in that some codes are different depending on the php version I am using? I am puzzled.
Thanks
You can use either assuming you're running PHP 5.3, however, if you're running anything below that, then use:
$user = JFactory::getUser();
if($user->id!=0){
//your code goes here
}
Personally, I would go for the second method as it goes through the Joomla API and is a tad more thorough.
On a side note, if you do use the first method, you can remove the &.
/* some information about the current logged in user is displayed, but only when the user is actually logged in. */
$user =& JFactory::getUser();
if (!$user->guest) {
echo 'You are logged in as:<br />';
echo 'User name: ' . $user->username . '<br />';
echo 'Real name: ' . $user->name . '<br />';
echo 'User ID : ' . $user->id . '<br />';
}
For Joomla there are two ways you can check if user is loged in
$user = JFactory::getUser();
if($user->guest = 1){
//User in not logged in
}
else
{
//User is logged in
}
Or second one is
$user = JFactory::getUser();
if($user->id != 0){
//User is logged in
$id = $user->id; // You can use this ID for further Use
}
else
{
//User is no logged in
}
I personally Prefer Second one as it fulfill two usability at same time.

Magento, see if back-end user is online?

I have a Magento website.
There is admin user, thats me, and a other user.
How can I see if the other user is logged in (back-end) ?
EDIT
Thanks to Sandeep I now have this:
<?php
$session = Mage::getSingleton('admin/session');
$userDetails = Mage::getSingleton('admin/session');
// Get data from the session $userID =
$userDetails->getUser()->getUserId();
// Get user ID $userID =
$userDetails->getUser()->getEmail();
// Use the 'admin/session' object to check loggedIn status
if ( $session->isLoggedIn() ) {
echo "Ingelogd";
} else {
echo "Niet ingelogt";
}
?>
$session = Mage::getSingleton('admin/session');
// Use the 'admin/session' object to check loggedIn status
if ( $session->isLoggedIn() ) {
echo "logged in";
} else {
echo "not logged in";
}

Resources