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

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.

Related

Get User Entity from AuthComponent::user()

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.

Filter datasource by auth.user.id

I'm a newbie to cakephp and I don't quit get it.
I'm building a system where users login and register some data. And I want the users to only see their own data. How do I do this? I was thinking about making a kind of restriction in the model or do I have to code this in every function (Connected to the views)?
I have a well functioning system With user login etc, but I can't separate the data access to the users.
I can't figure this out and I might think that's a bit because I might not know what to ask about. Hoping that some can give me a hand.
You have the logged in users id via $this->Auth->user('id');. You then have to set a condition on your find calls where user_id = $userId.
$userId = $this->Auth->user('id');
$this->SomeRelatedModel->find('all', array(
'conditions' => array(
'SomeRelatedModel.user_id' => $userId,
),
));
You can also pass the $userId variable to the model and do your find calls in there (either methods or custom find calls).
If a lot of your models/find calls need to filter by user id, you may want to create a behavior and use beforeFind callback to add the condition to the query.
When user will login, Auth will store Id in session. you can access it by using
$this->Session->read('Auth.User.id') or $this->Auth->user('id') or AuthComponent::user('id')
$this->User->find('all',array(
'conditions'=>array('id'=>$this->Session->read('Auth.User.id')),
'fields'=>'...............'));

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

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

Cake php auth and acl unlogged usergroup

I want to control access for unregisteres/unlogged users using Acl - i've setup it , tested it's working i can create new groups , users, add user to group and setup group premissions for specific controller actions
I've created usergroup called unregistered and user called temp but have no idea how to assign (map) unlogged person who entered the page to that user and group ?
Why would you specify the default allow rule in the ACL structure?
Suppose you want to allow anonymous access to the following actions: register, about, someotherpage
And you want to control access via ACLs to: edit, reply, profile
In the Auth component, you can set the Auth::allow property, which specifies different controller actions that you want to allow everyone (logged in and non-logged in users alike) access to. So, in your controller (can either be AppController to apply globally, or SpecificController to apply only to that controller), specify (usually in the Controller::beforeFilter() method):
$this->Auth->allow = array( 'register', 'about', 'someotherpage' );
Then Auth will only restrict access to the other pages. This should be much simpler than what you were trying to do, assuming that I read you question correctly.
HTH!
You're on the right track - you have defined an "anonymous" user and group. The next step you need to do is to automatically log in any anonymous user as the "anonymous" user (it sounds stupid, but trust me). That way you can set up the ACL permissions in the tables just as if they were a registered user.
#Travis Leleu - The tables for auth already exist, to define the permissions for registered users/groups, so why have a second, separate table for non-registered, anonymous users?

Resources