Zend Create User and Automatically Sign them in - zend-framework

I have search and search but no answer I am using Zend Framework to create a user and on success store the record in zend auth so they are automatically logged in.
I have the create user working perfect but after the success I need to start the _getAuthAdpater() and sign the user in.
I have implemented the below code but it will not store the users data in the session. Here is my function.
public function registerAction()
$proUser = new Application_Model_DbTable_ProUser;
$userId = $proUser->addProUser($data['email'], $data['name'], $data['password']);if($userId){
// add new row into proBasic
$proBasic = new Application_Model_DbTable_proBasic;
$proBasic->addProBasic($userId);
// add new row into proService
$proService = new Application_Model_DbTable_proService;
$proService->addProService($userId);
// Create auth session for proUser
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($data['email']);
$adapter->setCredential($data['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$user = $adapter->getResultRowObject(array(
'proId',
'proName',
'proEmail',
));
$auth->getStorage()->write($user);
return true;
}
return $this->_redirect('/auth/probasic/');
}
Here is the _getAuthAdapter() function:
private function _getAuthAdapter()
{
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('proUser')
->setIdentityColumn('proEmail')
->setCredentialColumn('proPassword');
return $authAdapter;
}
I am getting no errors for this code but it isnt store the users details in the Auth. I have found 100's of example of how to create a login/sign up system in Zend and none of them automatically login the user, so I am wondering if I am trying to do something different.
Cheers
J.

You don't really need to authenticate them if you're creating the session immediately after registration. What happens if you replace all your code after $proService->addProService($userId) with just this:
$auth = Zend_Auth::getInstance();
$auth->getStorage()->write($data['email']);

Related

Google Analytics Reporting API - Get Activity data via Client ID

I am trying to get user activity data via his client id using Google Analytics api. Take a look at the below image:
Now highlighted text is users client id, it could be user id too, and when I trying to get it via Google's playground, I get the correct response and activity data which is required, like:
and this is the response:
which is required and OK.
but I want this data via API, and have searched the web to get it, but nothing helped me.
Here is sample code Google showing i.e.
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
I do found a class for adding user to request i.e.
$user = new Google_Service_AnalyticsReporting_User();
$user->setType("CLIENT_ID");
$user->setUserId("660467279.1539972080");
but this class Google_Service_AnalyticsReporting_ReportRequest which accepts conditions/filters for query does not have such method to accept user object.
How can I achieve this?
You should use this function: $analytics->userActivity->search().
$search = new Google_Service_AnalyticsReporting_SearchUserActivityRequest();
$search->setViewId($VIEW_ID); // Google Analytics View ID
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
$search->setDateRange($dateRange);
$user = new Google_Service_AnalyticsReporting_User();
$user->setType("USER_ID"); // or CLIENT_ID if you are not using custom USER ID views
$user->setUserId($user_id); // The actual user's ID as stored in your DB passed to GA
$search->setPageSize(10); // Number of results you want to pull
$search->setUser($user);
return $analytics->userActivity->search($search); // Perform the search query.
Alternatively you can also pass the params to search() like:
$params = [
'metrics' => //Your comma separated desired metrics
'dimmensions' => //Your comma separated custom dimmentions
]
return $analytics->userActivity->search($search, $params);

Exchanging Facebook Auth Code for Access Token using the PHP SDK

I am trying to build a server-to-server auth flow using the Facebook PHP SDK and no Javascript, as outlined here. So far, I have successfully created a LoginUrl that lets the User sign in with Facebook, then redirect back to my App and check the state parameter for CSFR protection.
My Problem is, that I can't seem to get the API-call working that should swap my Auth Code for an access token. I pillaged every similar problem anyone else that Google was able to find had encountered for possible solutions.
Yet the end result was always the same: no access token, no error message that I could evaluate.
Researching the topic yielded the following advice, which I tested:
The URL specified in the App Settings must be a parent folder of $appUrl.
use curl to make the request instead of the SDK function api()
I've been at this for 2 days straight now and really could use some help.
<?php
require '../inc/php-sdk/src/facebook.php';
// Setting some config vars
$appId = 'MY_APP_ID';
$secret = 'MY_APP_SECRET';
$appUrl = 'https://MY_DOMAIN/appFolder';
$fbconfig = array('appId'=>$appId, 'secret'=>$secret);
$facebook = new Facebook($fbconfig);
// Log User in with Facebook and come back with Auth Code if not yet done
if(!(isset($_SESSION['login']))){
$_SESSION['login']=1;
header('Location: '.$facebook->getLoginUrl());
}
// process Callback from Facebook User Login
if($_SESSION['login']===1) {
/* CSFR Protection: getLoginUrl() generates a state string and stores it
in "$_SESSION['fb_'.$fbconfig['appId'].'_state']". This checks if it matches the state
obtained via $_GET['state']*/
if (isset($_SESSION['fb_'.$fbconfig['appId'].'_state'])&&isset($_GET['state'])){
// Good Case
if ($_SESSION['fb_'.$fbconfig['appId'].'_state']===$_GET['state']) {
$_SESSION['login']=2;
}
else {
unset($_SESSION['login']);
echo 'You may be a victim of CSFR Attacks. Try logging in again.';
}
}
}
// State check O.K., swap Code for Token now
if($_SESSION['login']===2) {
$path = '/oauth/access_token';
$api_params = array (
'client_id'=>$appId,
'redirect_uri'=>$appUrl,
'client_secret'=>$secret,
'code'=>$_GET['code']
);
$access_token = $facebook->api($path, 'GET', $api_params);
var_dump($access_token);
}
The easiest way I found to do this is to extend the Facebook class and expose the protected getAccessTokenFromCode() method:
<?php
class MyFacebook extends Facebook {
/** If you simply want to get the token, use this method */
public function getAccessTokenFromCode($code, $redirectUri = null)
{
return parent::getAccessTokenFromCode($code, $redirectUri);
}
/** If you would like to get and set (and extend), use this method instead */
public function setAccessTokenFromCode($code)
{
$token = parent::getAccessTokenFromCode($code);
if (empty($token)) {
return false;
}
$this->setAccessToken($token);
if (!$this->setExtendedAccessToken()) {
return false;
}
return $this->getAccessToken();
}
}
I also included a variation on the convenience method I use to set the access token, since I don't actually need a public "get" method in my own code.

Using Zend Auth with external authentication mechanism

I have a Drupal site and a Zend application. The main thing is the Drupal site, where the users are stored & everything.
I want my users to be automatically logged in to the Zend app when they log in on Drupal. The problem is that Drupal changes the session cookie to SESS* where * is some random (EDIT: not random, but based on protocol and domain) string.
Is there any way I can tell Zend to use this cookie as a session identifier and to log the user automatically?
You have to write your own authentication adapter:
class YourApp_Auth_Adapter_DrupalBridge implements Zend_Auth_Adapter_Interface
{
/**
* #return Zend_Auth_Result
*/
public function authenticate()
{
// Check if the Drupal session is set by reading the cookie.
// ...
// Read the current user's login into $username.
// ...
// Create the authentication result object.
// Failure
if (null === $username) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, null);
}
// Success
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $username);
}
}
Then process your authentication:
$adapter = new YourApp_Auth_Adapter_DrupalBridge();
$result = Zend_Auth::getInstance()->authenticate($adapter);
if ($result->isValid()) {
// User is logged in
}

Zend_Auth not working

In my model, "Users", I have the following authorization after validating the username/password
$db = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($db,'users','username','password');
$authAdapter->setIdentity($username);
$authAdapter->setCredential(md5($password));
$auth_result = $authAdapter->authenticate();
if( $auth_result->isValid() )
{
$auth = Zend_Auth::getInstance();
$storage = $auth->getStorage();
$storage->write($authAdapter->getResultRowObject(array('id','username')));
return 'logged_in';
}
return 'auth_failed';
it keeps returning 'auth_failed'. I had the code running on a localhost, and everything works fine, but when I upload it online, it fails to authorize the user. What is going on?
Thanks
I can't tell what's wrong without checkin the logs, so perhaps you might want to use the method I use for storing auth data. Basically you validate manually and set the storageThis doesn't solve the problem, but its impossible to do so without accessing your code.
function login($userNameSupplied,$passwordSupplied){
$table= new Application_Model_Dbtable_Users();//Or Whatever Table you're using
$row=$table->fetchRow($table->select()->where('username=?',$userNameSupplied)->where('password=?',md5($passwordSupplied));
if($row){
Zend_Auth::getInstance()->getStorage()->write($row->toArray());
return 'logged_in';
}
else{return 'failed';}
}
//To check if the user is logged in, use
$userInfo=Zend_Auth::getInstance()->getStorage()->read();
if($userInfo)//user is logged in

Joomla JUser getinstance Questions

I am attempting to make an authentication plugin. JUser::getInstance() takes one input, and it is supposed to be the id. Is there any way to get an instance of a User using some other indentifier? such as username, email etc.
Probably there isnt any such method. But yes if you are sure that username or email are unique then you can modify your file user.php in libraries/joomla/user/ and add a method there.
getInstanceByEmail($email)
{
$query = "select id from jos_users where email=".email;
// use the code to get the id;
return getInstance($id);
} // this is just a sample code of how it can be achieved
Since Joomla's own authentication is done by checking the user's username (and password of course), it has to be unique. And yes you can do something like what #Rixius suggested.
Here's my version:
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, password');
$query->from('#__users');
$query->where('username=' . $db->Quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
$user = JFactory::getUser();
if ($result)
{
$user = JUser::getInstance($result->id);
}