I have a 'User' model which is related to a 'Group' model via HABTM relationship. I am able to query the model to determine which memberships the authenticated user belongs to but am unable to conceptually come up with a method of easily accessing that data on a page’s isAuthorized() function call.
Ideally I’m hoping there’s a way I can link into the authentication method and cache the authorized user’s group memberships so I can do a quick lookup on isAuthorized() calls. Is there some functionality in cake that would allow this? I’m obviously open to recommendations as I am fairly new to the framework after inheriting this project from a past employee.
From what I’ve been able to gather is that I would want to be able to access or search the group memberships of the user returned by AuthComponent::user() but since that’s a static method I don’t get access to its Model. Is this possible?
EDIT:
Solution was a mixture of the discussion I had with ndm as well as finding out that the application seemed to break authentication. This might be the fault of the last dev who created the application but I managed to resolve it by overriding part of the BaseAuthenticate._findUser($username,$password) function to inherit the ‘Group’ Array along with the ‘User’ array. It was being fetched on login but only the ‘User’ portion of the model returned back to the Controller that called Auth.
Retreiving the groups of the currently logged in user should be simple, you’d just need to configure your authentication handler appropriately so that it fetches the associated models. This can be done using the resurive or contain setting, though the latter seems to be kinda broken currently (at least the behaviour is unexpected).
Example using
recursive:Example using
contain:In order for the
containmethod to work, theUsermodel needs to act asContainable! However, as mentioned, this seems to be broken, becauserecursiveis always used, and it’s not possible to set it tonullbecause it’s being casted to an integer. So you’d need to supply the appropriaterecursivesetting too (ie recursive = 1), however this somehow defeats the purpose of theContainablebehaviour which should figure out the appropriate recursive setting automatically (unless configured otherwise).Anyway, both would make the authenticator fetch your
UserHABTMGroupassociation. Either way you should then be able to access the data viaAuthComponent::user()from anywhere you want:Edit (07.11.2012): The problem with using
containin the authentication handler configuration is now fixed for 2.2.4, making it possible to passnullfor therecursivesetting.