Zend_Auth not working - zend-framework

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

Related

Not able to fetch contacts from yahoo api

I've included yahoo API to read user's yahoo contacts. However it's not fetching any data.
Please have a look at my code:
session_start();
include_once 'config.php'; //This file contains consumer key & all data
require_once ('Yahoo.inc'); //This is a standard Yahoo file, just copied it
$session = YahooSession::requireSession($consumer_key,$consumer_secret,$app_id);
if (is_object($session))
{
$user = $session->getSessionedUser(); //This is NOT NULL
$profile = $user->getProfile(); //This is NULL
$name = $profile->givenNme;
$guid = $profile->guid;
$contacts=$user->getContacts()->contacts; //This is NULL
if($contacts==NULL){
echo "No contacts";
}
}
Somehow getProfile() & getContacts() are not working at all, anyone can help spot the mistake?
Please check this thread: yahoo oauth $user->getProfile(); returns null. It solves the problem. You need to switch over to the new API. Otherwise, you may experience this kind of problems.

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.

silverstripe external authentification

there is a custom login form that should give users access to certain contents on the same page. That works so far with Users stored as Members in the SS database and I was checking after Login if the user has permissions like this in the Page Class:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
}
in the Template I just did this:
<% if isAllowed %>
SecretContent
<% end_if %>
OK so far, but now the users will not be stored in the silverstripe database - they are stored on a another server.
On that external server is running a little php script accepting the username and password. The script just returns user has permission: true or false.
I´m calling that script via cURL.
I planned to overwrite the dologin Function of MemberLoginForm. Now I just wonder how to check after Login that the User got the permission and display the contents... I tried to set a variable in the controller of the Page or should I set a session Variable? Thats my attempt (CustomLoginForm extends MemberLoginForm):
public function dologin($data) {
if(userHasPermission("user1", "pw")==true){
$this->controller->Test("test");
}
$link = $this->controller->Link();
$this->performLogin($data);
$this->controller->redirect($link);
}
I hope someone can help me with that - I know very specific - problem.
Many thanx,
Florian
In SilverStripe you can create a custom authenticator, which means users can log in on your website with accounts that are stored somewhere else, or even just a hard coded user and password.
You can check out the OpenID Authentication Module for example code on how to do it
But for your task this might even be to complex of a solution, how about after login just do something like Session::set('isAllowed', true); and to check if the user is allowed to view:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
// if Member::currentUser() is not allowed to view,
// return the session, which is either set to true or it returns null if not set
return Session::get('isAllowed');
}

Zend Create User and Automatically Sign them in

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']);

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);
}