Get User Entity from AuthComponent::user() - cakephp

Using the AuthComponent in CakePHP 3, you can access the currently logged in user in a Controller using $this->Auth->user(). However, this method returns only an array, not a User Entity.
In many places, I have to work with the User Entity of the logged in user, but have to query the UsersTable manually after getting the id from the AuthComponent, which seems quite silly, as the AuthComponent fetches a hydrated User Entity anyway and flattens it to an array. So the User Entity is fetched twice.
Is there a way to get the hydrated User Entity from the AuthComponent instead of an array?
$authUser = $this->Auth->user('id');
if($authUser !== null) {
$authUser = $users->get($authUser);
}

The main reason entities are not stored in the sessions is because there is no guarantee that the auth data is an actual database user. For example, you may be authenticating some credentials from an external system, such as a single sign on in a remote server.
Another reason is that user info can be expected to change from request to request and doing a db lookup on each request is less than ideal.
Finally, people could think that by changing the data in the session entity they would be modifying the user (or modifying the data in the table would refresh the session).
I would suggest just converting your array data to an entity using new User($data) whenever you need an entity.

Related

Codeigniter database session update inconsistency

In Codeigniter, the function session->userdata($item) is used to retrieve session data and the definition of this function in Session class is :
function userdata($item)
{
return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
}
Now the problem is this:
Each time a script is executed, a session object is created and the retrieved data is persistent untill end of the script. So if another script for example update session values, new values will be stored in DB, but retrieved data in other session objects are not updated and it makes an obvious inconsistency and inaccuracy in data.
I think it can be a serious problem in many cases.
Is it right or I'm misunderstanding something here? And if
IN codeigniter session object is created during the class initialization and userdata(session values) are updated every time user makes request. You can view whole session object via below piece of code:
print_r($this->session);
This will show you the complete session object with all necessary configurations you have set in your config file for session related variables like:
sess_encrypt_cookie, sess_use_database,sess_expiration ..etc
plus your current session user data. Now when you make next request session values are overridden by the new one or old values are just replaced by the new one. So there is no chance of data duplicacy or inconsistancy. It is recommended to use session table whenever you are saving large amount of data in session.

Cakephp: $this->Auth->user vs $this->User vs $user

I realize this might not be a clear cut "problem/answer" question, but I think it's worth asking.
In controllers, it seems that there are three options which access the Auth object:
$this->Auth->user
$this->User
$user
They each return the record for the logged in user, and I cannot see much of a difference between them.
Now, it occurs to me that, at a glance, $this->User could be a bit confusing or unclear if working in an associated model $this->Posts->User.
But apart from that, is there a difference between these three options?
$this->Auth->user() returns the currently authenticated user from the session.
$this->User is a model and you won't get the currently authenticated user unless you use the session data (either from Session or Auth component) to get the user id. Either way you'd have to do a query every request to get info about the logged in user.
$user .. is just a variable. I don't understand how this is an "options which access the Auth object"
If you want info about the currently logged in user, use $this->Auth->user();
In cakephp 2 you must use AuthComponent::user($user_field) to access authenticated user data , for example :
for id of user that authenticated you must use AuthComponent::user('id').
As tirang said $this->User is a model and $user just a variable.

Cake PHP: How do I make one variable avaiable across all view and elements

I want to access
id of current logged user
name of current logged user
group_id of current logged user
group_name of current logged user
across the view files, to switch menus and tabs on and off according to group_id.
How can I achieve this with minimum sacrifice of performance?
Thanks
If you use the AuthComponent, it'll store the record of the currently logged-in user in the Session under the key Auth. You can access this anywhere through the session component or helper:
$this->Session->read('Auth.User.name')
Even if you're not using the AuthComponent, the Session is the best place to store information about the current user.
Otherwise and in general, the Configure class is usually a good place to store this kind of global information:
Configure::write('User', array('id' => $id, ...));
Configure::read('User.id');
What I always do is create a AppHelper and create a method for this.
Off course this is similar to deceze's answer but it reduces some code you need to write ;)
function user($key) {
$user = $this->Session->read('Auth.User');
if (isset($user[$key])) {
return $user[$key];
}
return false;
}
Then you can call the id of the user by $this->Html->user('id');
Perhaps you could set the variables you want in your AppController (extended by all sub controllers). You should then be able to access them from all views, though be careful to name them uniquely.
CakePHP book - App Controller

Get a Google App Engine user by their user_id

In GAE, can you look up a User with the User object's user_id?
In other words, is there something equivalent to:
from google.appengine.api.users import User
user = User.get_by_id(user_id)
I don't think so.
... they certainly wouldn't just give you access to every holder of a google account!
The idea is that you store user ids as properties in your datastore, once they've logged in to your app.
There is a property type called UserProperty
http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html
So, you can query your list of users from your own datastore definition.
hth
This seems to be the only post on the internet regarding this and since I was looking for a solution, I thought I'd post what I found here.
What amir75 said about using the UserProperty is fine for storing the User object itself returned by the google.appengine.users module.
But if you need to lookup a User by the user_id field instead of the default email field, usually something like user = User(email = 'validmail#gmailorgapps.com')
You can use this to query by user_id. user = User(_user_id = 'validuserid') The valid user_id is something that you got earlier from calling user.user_id()
I'm not sure what amir75 is referring to about having access to all google accounts since the User object returned will only have the email address and nickname, and that too only if the user authorizes the application to access that information.
My use case for this is I want people to sign up on the site, but they need an administrator to confirm them for using the site. The form used by the administrator for confirming the users can use email id as the field to identify the checkbox for confirming the user, but given that it might change, the user_id seems to be a safer field to use.

how to find out my current user id in other page controller after i login?

i am planing to set a permission on my event index page, which just allow certain user to view which had set when i add the event. After user click into my event, the event controller will 1st check the user id and check the event database which control the user can see which event in his calendar. The permission is added when user create a event and share to other user. Beside, how can i find the current user id to compare with my event database which is the accurate 1?
any suggestion for me to did this function?
i need to know the code and concept how i get the current user id to compare with all the event database, and allow the current user see the certain event.
thanks alot for your information.
The recommended approach for getting logged in user data is via the AuthComponent itself:
// in any controller
$userId = $this->Auth->user('id');
See Accessing the logged in user in the Auth section of the CakePHP Book.
Use sessions to save and read data for a user between pages.
Within Controllers:
// store a user id in the session
$this->Session->write('User.id', $userId);
// read a user id from the session
$userId = $this->Session->read('User.id');
Within Views:
// read a user id from the session
$userId = $session->read('User.id');
You can use any key you want if you prefer something over "User.id". I simply use this since it is what the AuthComponent defaults to if you are using that.
What you're looking for are ACLs (Access Control Lists). There's an AclComponent built into Cake which you should look into. It works together with the AuthComponent, which will hold the user id. It's a little complicated at first, but worth the hassle.
Also, for a simple approach, have a look at the model and controller settings of AuthComponent::authorize. This allows you to define an isAuthorized() method in your controller or model (your choice) which will store logic that determines access (should return true if access allowed and false if denied).
to see sessions, queries, data, and everything else that is passed from page to page in cake use this amazing little helper http://thechaw.com/debug_kit

Resources