How to get user id from Zend_Auth - php

I have big problem with getting user_id with zend..
My auth login code:
if($form->isValid($this->getRequest()->getPost())){
$adapter = new Zend_Auth_Adapter_DbTable(
null,
'sprzedawca',
'email',
'haslo',
'MD5(CONCAT(?, salt))'
);
$adapter->setIdentity($form->getValue('email'));
$adapter->setCredential($form->getValue('haslo'));
$auth = Zend_Auth::getInstance();
$wynik = $auth->authenticate($adapter);
if($wynik->isValid()){
//return $this->_helper->FlashMessenger('Pomyślnie zalogowano');
return $this->_helper->redirector(
'index',
'sprzedawca',
'default'
);
Now when i try write user id using:
Zend_Auth::getInstance()->getIdentity()
I got only 'username' but i want to get user_id
Zend_Auth::getInstance()->getIdentity()->user_id
doesn't work too..

okay, i didn't store item while loggin
Should be:
if($wynik->isValid()){
$storage = $auth->getStorage();
$storage->write($adapter->getResultRowObject('sprzedawca_id'));
and now works perfectly

I can't see your database Scheme now, but i can tell you that this has worked for me.
<?php
$auth = Zend_Auth::getInstance();
$userId = $auth->getIdentity()->id;//user_id OR id depending your primary key of the user table.
echo $userId;
?>
Attention:- $userId = $auth->getIdentity()->id; //id must written as it is your user table, other it wise won't work

I managed to get this through a Google search, try it.
Zend_Auth::getInstance()->getIdentity()->User_ID

Related

Laravel Entrust, how to attach existing permission to role

Here is my code I am using, it runs fine but when I'm inside the database checking if everything went okay I get this result
Why am I getting 0 for the permission ID and Role ID?
$developer = new Role();
$developer->name = 'Test';
$view_customers = new Permission();
$view_customers->name = 'view_customers';
$view_customers->display_name = 'View Customers';
$developer->attachPermission($view_customers->id);
try this
$developer = Role::where('name','=','Test')->get->first();
//if you want to attach new permission
$view_customers = new Permission();
$view_customers->name = 'view_customers';
$view_customers->display_name = 'View Customers';
//if you want to attach existing permission ex. you already have 'view_customers' in permission table
$view_customers = Permission::where('name','=','view_customers')->get->first();
$developer->attachPermission($view_customers);
attachPermission() works by model or array, if you want atach or detach by id use this
$developer->perms()->attach($view_customers->id);

How to clone/copy a sql record with CakePhp, and then grab the ID of the clone?

I have cloned/saved a copy of an SQL record using CakePhp like so:
$contract = $this->Contract->findById($id);
$contract['Contract']['id'] = NULL;
$this->Contract->save($contract); // And save it
I want to be able to redirect the user to the 'Edit' view of the cloned record after the clone is complete. Basically, I need to do something like this:
$this->redirect(array('controller' => 'contracts', 'action' => 'edit', $cloneId));
My question is, how do I get the ID of the clone immediately after saving the new record?
you can also get the last inserted record id in these ways.
$cloneId = $this->Contract->id;
or
$cloneId = $this->Contract->getLastInsertID();
or
$contract = $this->Contract->save($contract);
$cloneId = $contract['Contract']['id']

Please help me guess this hybridAuth code

Can somebody help me guess out this code..this is just a snippet and I think I included all the codes needed for my question. Actually this code is from hybridAuth. My question is, where does "user_id" from the last line came from? I wanted to know because $_SESSION["user"] gives the value of the "id". And I wanted to make another $_SESSION[" "] where I can place the value of email-add from the database (same location where that user_id's "id" exist)
// create an instance for Hybridauth with the configuration file path as parameter
$hybridauth = new Hybrid_Auth( $hybridauth_config );
// try to authenticate the selected $provider
$adapter = $hybridauth->authenticate( $provider );
// grab the user profile
$user_profile = $adapter->getUserProfile();
// load user and authentication models, we will need them...
$authentication = $this->loadModel( "authentication" );
$user = $this->loadModel( "user" );
# 1 - check if user already have authenticated using this provider before
$authentication_info = $authentication->find_by_provider_uid( $provider, $user_profile->identifier );
# 2 - if authentication exists in the database, then we set the user as connected and redirect him to his profile page
if( $authentication_info ){
// 2.1 - store user_id in session
$_SESSION["user"] = $authentication_info["user_id"];
The call to $authentication->find_by_provider_uid() returns an associative array, one key of which is user_id.
To see what other columns are returned by that call:
var_dump($authentication_info);
If the email is among the keys in that array, you may then set it in $_SESSION:
// Store the email into session if it is present in $authentication_info
// Use whatever the appropriate key you find, be it email, email_address, user_email, whatever...
$_SESSION['user_email'] = $authentication_info['email'];

Retrieve the group id of user in Ion Auth - Codeigniter

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?>

Zend AUTH disable multiple login on diff computer or browser

I have a concern about Zend Auth. I've searched throughout the internet, but haven't found any tutorial, article or discussion;
scenario: Login as 'ADMIN' on 'COMPUTER 01' and 'COMPUTER 02' concurrently.
I want my user login system to prevent the 'ADMIN' user from logging in on two computers at the same time. So that when a User is already logged in, the system disables login on another machine.
As far as I am aware this functionality is not built in to Zend_Auth, but you could achieve what you want by extending the Zend_Auth_Adapter that you are currently using and overiding the authenticate() method as danielrsmith suggests.
You would need to add a table to your DB that is set/unset by the login process. The problem is going to be the unset if the user does not specifically log out, but you could store a timestamp in the DB and allow the login to expire for the next login attempt.
My_Auth_Adapter_DbTable extends Zend_Auth_Adapter_DbTable
{
public function authenticate()
{
$authResult = parent::authenticate();
if($this->alreadyLoggedIn(){
$authResult = new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_UNCATEGORIZED,
$this->_identity,
array('User already logged in')
);
} else {
$this->setLoggedIn();
}
return $authResult;
}
private function alreadyLoggedIn()
{
//check db table to see if $this->_identity is already logged in
//then return true or false as appropriate
}
private function setLoggedIn()
{
//update table in DB to reflect logged in status
}
}
I haven't tested this code, but it will, hopefully, get you started in the right direction.
Also, doing it this way will, I think, avoid the need to alter the session handler in any way.
Try this:
Create session table in database:
CREATE TABLE session (
id char(32),
modified int,
lifetime int,
data text,
PRIMARY KEY (id)
);
Store session in database by Zend_Session_SaveHandler_DbTable. Put the following code in bootstrap.php
protected function _initDoctrineSession()
{
$url=constant("APPLICATION_PATH").DIRECTORY_SEPARATOR ."configs".DIRECTORY_SEPARATOR."application.ini";
$config=new Zend_Config_Ini($url,"mysql");
$db=Zend_Db::factory($config->db);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
$config = array(
'name' => 'session',
'primary' => 'id',
'modifiedColumn' => 'modified',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime'
);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
Zend_Session::start();
}
When log in, save user id or user name in session:
$logged_user = new Zend_Session_Namespace('logged_user');
$logged_user->logged_user = $user->name;
Another log in deletes all expired sessions in database firstly:
$sessionModel = new Session();
$sessionModel->removeExpiredSessions();
5.After log in, search session table records to see if current user already logged in:
$sessions = $sessionModel->querySessions();
$flag=true;
foreach ($sessions as $session){
if(strpos($session['data'], $user->name)>0 and strpos($session['data'],"Zend_Auth")>0
){
$flag=false;
}
}
if($flag == false){
$this->_forward('index','index');
return;
}
This will work. But there is a problem, if a user closes the Web browser before log out, the user will not be able to log in again before the session expired. Anyone can help to fix the last problem?

Categories