Joomla User login check - authentication

First I am not a joomla developer. My friend has a web site created with joomla 1.5. In webroot there are some joomla files. I created a directory in webroot "mydirectory" and i have an index file in this directory. I try to access joomla's user info in this page i grab the user object but it doesn't work.
//i included joomla core files
$user =& JFactory::getUser();
if ($user->get('guest')) {
echo 'guest';
} else {
echo 'not guest';
}
when I log in to my account, it says 'guest' again.
Also, I can't find anything in Joomla's session class.
$session =& JFactory::getSession();
Thanks

You should do this:
$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 />';
}
This is from here: http://docs.joomla.org/JFactory/getUser

Try print_r($user) to see what items you are getting back.

Try to check for $user->id
See if you are missing including any file e.g. framework.php

Related

How to find user's email ID? - Google Oauth2 API PHP Client

I am implementing an Audio library manager which uses user's google drive as backend storage. I am using PHP (google-api-php-client-2.2.1) to get the user's authorization for accessing his/her google drive.
So far I am able to receive access token and refresh token using example code from google (https://developers.google.com/api-client-library/php/auth/web-app), and also tested by listing files of user's google drive.
However, I am not able to figure out programmatically which user has given authorization to my application. Just user's email address will do. I don't need any other information.
I am using the following code.
<?php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secret.json'); //downloaded from google oauth credentials portal. It includes redirect URL
$client->setAccessType("offline"); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
if (! isset($_GET['code'])) {
//Get authorization and User consent from Google
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else { //Authorization completed
//Get access token
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
echo "Access Token<br>";
var_dump ($_SESSION['access_token']); //works
echo "<br>";
echo "Refresh Token<br>";
var_dump ($_SESSION['refresh_token']); //works
echo "<br>";
$service=new Google_Service_Oauth2($client);
echo "Auth2 Service created<br>"; //Getting this print
$usr_info=$service->userinfo;
echo "User Info<br>"; //Getting this print
var_dump ($usr_info); //Getting this print, Very long JSON structure. But info is mostly pertaining to my app...no user information showing here
echo "<br>";
//$usr_info_get = $usr_info->get(); //Throwing Error
//$usr_info_get = $usr_info->get(['email']); //Throwing Error
//$usr_info_get = $usr_info->get()['email']; //Throwing Error
echo "User Info Get<br>";
//var_dump ($usr_info_get);
echo "<br>";
}
?>
The class for userInfo is like this
class Google_Service_Oauth2_Resource_Userinfo extends Google_Service_Resource
{
/**
* (userinfo.get)
*
* #param array $optParams Optional parameters.
* #return Google_Service_Oauth2_Userinfoplus
*/
public function get($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Oauth2_Userinfoplus");
}
}
The params for get() method should be optional, but
$userInfo->get()
also given me Server Error.
I am not finding anything else from my google search on this.
I tried this (6 year old thread) but code errors out (apiHttpRequest class not found)
How to identify a Google OAuth2 user?
I tried reading about openID but seems kinda complex. Also, not sure if google-api-php-client has helper class for openID.
I would really appreciate your help. Already spent 2+ days reading google api client php code but now up against the wall.

how to send an HTML content via php mail()

I am trying to send an HTML e-mail using this code but all i am getting is FALSE from the mail() function.
The error_log is empty.
Can someone tell me why mail() is not working?
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>SDFSDF</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>VXCVSDF</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$to = 'my_mail#gmail.com';
$subject = 'Website Change Reqest';
$headers = "From: USER NAME"."\r\n";
$headers .= "Reply-To: USER EMAIL"."\r\n";
$headers .= "MIME-Version: 1.0"."\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1"."\r\n";
if (mail($to, $subject, $message, $headers)) {
echo 'Your message has been sent.';
} else {
echo 'There was a problem sending the email.';
}
It's hard to debug PHP mail() function.
After checking your script, I can confirm that your code is working fine. It's something with your server or/and PHP configuration.
Start with this little snippet to see what is happening:
error_reporting(E_ALL);
ini_set('display_errors', -1);
echo '<br>I am : ' . `whoami`.'<br>';
$result = mail('myaddress#mydomain.com','This is the test','This is a test.');
echo '<hr>Result was: ' . ( $result === FALSE ? 'FALSE' : 'TRUE') . ' ('. $result. ')';
echo '<hr>';
echo phpinfo();
After output, check your sendmail_path, in most case sendmail_path uses sendmail MTA:
/usr/sbin/sendmail -t -i
Edit your php.ini file, set the following and don't forget to restart httpd server:
sendmail_path = /usr/sbin/sendmail -t -i
Check log files at /var/log/maillog, it could really help you to solve the problem.
If you still have a problem, just take a good look at PHPMailer, SwiftMailer, PEAR's Mail or Zend Framework's Zend_Mail an excellent, comprehensive, modern PHP mailing library. It will be easy to debug your problem after all.
You can using phpmailer for this way!
https://code.google.com/a/apache-extras.org/p/phpmailer/
Hope this help!

Google Plus Api create a public profile

Hi I an issue trying to implement the google plus Api for non google plus accounts. I followed the code samples from the google developer site. In trying to authenticate a user i noticed that if you cancel/deny the creation of a google plus profile it gives a blank screen with a url "https://plus.google.com/up?continue=". If i reload the page i am giving the create google plus profile dialog , and upon cancelling again presented with a blank screen. I want to be able to let user's cancel and be returned to my site.
<?php
require_once ('includes/utilities.inc.php');
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
$client = new Google_Client();
$client->setApplicationName("Google Plus PHP Starter Application");
// Visit https://code.google.com/apis/console?api=plus to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('******************');
$client->setClientSecret('****************');
$client->setRedirectUri("***********************");
$client->setDeveloperKey('***********************');
$plus = new Google_PlusService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$activities = $plus->activities->listActivities('me', 'public');
print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
}
echo "<pre>";
print_r($user_google);
print_r( $_SESSION['token']);
echo"</pre>";
?>

Authentication without password on Moodle

Actually I am trying to integrate my system with moodle. I need a functionality that supposed to work like that:
Login into my system (same username as in moodle db)
User decide to switch to moodle, so his clicking a link to script (on moodle server - both systems are on other servers), and I getting all data from database about user that I want to log in (whole row from database) ...
Because password is encrypted, I can't redirect now to login form with post params, because it won't work.
Is there any good and easy way to achieve this goal? I have username and hashed and eventually hashed password.
I am using moodle 1.9 (system requirments).
Thanks in advance for any help,
Regards David
Some things to look at for SSO and Moodle 1.9:
If you are ready to spend quite some hours you could use Mnet: http://docs.moodle.org/en/MNet
There is also a phpcas authentication method that could do what you want: http://docs.moodle.org/en/CAS_server_(SSO)
Here is what I did
1 - I enabled the (External database) Authentication Plugin
2 - Create this php file in folder (my/moodle/root/login/)
<?php
require('../config.php');
$username = $_GET['id'];// 's3265';
$serverName = 'moodle' ;
$connectionInfo = array( "UID"=>"mssqlUser","PWD"=>"********","Database"=>"external_Database");
//I am using MSSQL2008
echo '<form action="' . $CFG->wwwroot .
'/login/index.php" method="post" name="login" id="form">';
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if (!$conn)
{die('Could not connect: ' . sqlsrv_error());}
$result = sqlsrv_query($conn , "SELECT * FROM Users WHERE LoginID = '" . $username . "'");
var_dump($conn, $result);
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
echo $row['FName'] . " " . $row['LName'] . ", please wait. . .";
$password = $row['LoginPassword'];
}
sqlsrv_close($conn);
?>
<p><input type="hidden" name="username" value="<?php echo $username ?>">
<p><input type="hidden" name="password" value="<?php echo $password ?>">
<script language="JavaScript">
function Validate(){document.login.submit();}
Validate();
</script>
</form>
3 - assume you named the rhr file (test.php)
now your link should look like (http://your_domain/moodle/login/test.php?id=yourusername)
for me it is working , but . . . I am not concerned about security . . . if you do . . . you have to add something to this

Symfony and uploadify

I want to use uploadify with Symfony 1.4, but so far I couldn't.
Uploadify loads correctly, I choose my files, it says that the files were successfully uploaded, but the are nowhere.
(I'm doing this on localhost)
Is there anybody who met this problem before?
Thanks, Tom
$file = $request->getParameter('file');
$filename = sha1($file->getOriginalName()).$file->getExtension($file->getOriginalExtension());
$file->save(sfConfig::get('sf_upload_dir').'/'.$filename);
in my project session stored in cookies so I found solution by create extra session storage class
class MySessionStorage extends sfSessionStorage
{
public function initialize($options = null)
{
$request = sfContext::getInstance()->getRequest();
// work-around for uploadify
if ($request->getParameter('uploadify') == "onUpload")
{
$sessionName = $options["session_name"];
if($value = $request->getParameter($sessionName))
{
session_name($sessionName);
session_id($value);
}
}
parent::initialize($options);
}
}
then changed factories.yml to
all:
storage:
class: MySessionStorage
and then "uploader" param will like this
uploader : '<?php echo url_for("attachments/upload?uploadify=onUpload&" . session_name() . "=" . session_id(), true)?>',
I can only guess that it's because you're trying to upload while logged into a system, but flash does not inherit session data from the browser, this means you will always be denied permission to whatever function you are trying to access since symfony thinks you're not logged in.
So you need to manually set variables in order for flash to use the same login session as the browser:
jQuery Code (needs to be in a php file, will not work in a js file):
$('#file_upload').uploadify({
.... config here
'scriptData': { '<?php echo session_name() ?>': '<?php echo session_id() ?>' }
});