I need a solution where authenticated users are allowed access to certain Controllers/Actions based not on their user type :ie. admin or normal user (although I may add this using standard ACL later) but according to the current status of their user.
For example :
Have they been a member of the site for more than 1 week?
Have they filled in their profile fully?
Actually, now that I think about it, kind of like they have on this site with their priviledges and badges.
For dynamic condition-based tests like you are describing, you can use dynamic assertions in your Zend_Acl rules.
For example:
class My_Acl_IsProfileComplete implements Zend_Acl_Assert_Interface
{
protected $user;
public function __construct($user)
{
$this->user = $user;
}
public function assert(Zend_Acl $acl,
Zend_Acl_Role_Interface $role = null,
Zend_Acl_Resource_Interface $resource = null,
$privilege = null)
{
// check the user's profile
if (null === $this->user){
return false;
}
return $this->user->isProfileComplete(); // for example
}
}
Then when defining your Acl object:
$user = Zend_Auth::getInstance()->getIdentity();
$assertion = new My_Acl_Assertion_IsProfileComplete($user);
$acl->allow($role, $resource, $privilege, $assertion);
Of course, some of the details depend upon the specifics of what you need to check and what you can use in your depend upon what you store in your Zend_Auth::setIdentity() call - only a user Id, a full user object, etc. And the roles, resources, and privileges are completely app-specific. But hopefully this gives the idea.
Also, since the assertion object requires a user object at instantiation, this dynamic rule cannot be added at Bootstrap. But, you can create the core Acl instance with static rules during bootstrap and then register a front controller plugin (to run at preDispatch(), say) that adds the dynamic assertion. This way, the Acl is fully populated by the time you get to your controllers where presumably you would be checking them.
Just thinking out loud.
Related
I'm trying to add some functionality to the back end of a Bolt CMS installation that does the following:
Check if the user is a member of the "limited editor" group.
If so, only list content which they, personally, own.
This needs to be within the controller, not using Twig.
I've got the user object using
$user = $app['users']->getCurrentUser();
I guess I could use
in_array('limitededitor', $user["roles"]);
But I wondered if there was any existing function in Bolt that would streamline this, like "isAllowed" but for checking role membership?
This is what I've used in the past to determine whether I mount a controller (and thus give access to the new urls), the key part is the users service has a hasRole method but you need to check by user id.
public function checkAuth()
{
$currentUser = $this->app['users']->getCurrentUser();
$currentUserId = $currentUser['id'];
foreach (['admin', 'root', 'developer', 'editor'] as $role) {
if ($this->app['users']->hasRole($currentUserId, $role)) {
return true;
}
}
return false;
}
Case: I'm building a forum using Laravel's Authorization as a backbone using policies. Examples of checks I run are stuff like #can('view', $forum), and #can('reply', $topic), Gate::allows('create_topic', $forum) etc. These checks basically checks if the users role has that permission for the specific forum, topic or post. That way I can give roles very specific permissions for each forum in my application.
The issue is that all of these checks go through the Gate class, specifically a method called raw() which in its first line does this:
if (! $user = $this->resolveUser()) {
return false;
}
This presents an issue when dealing with forums. Guests to my application should also be allowed to view my forum, however as you can see from the code above, Laravels Gate class automatically returns false if the user is not logged in.
I need to be able to trigger my policies even if there is no user. Say in my ForumPolicy#view method, I do if(User::guest() && $forum->hasGuestViewAccess()) { return true }
But as you can see, this method will never trigger.
Is there a way for me to still use Laravel's authorization feature with guest users?
I'm not aware of a super natural way to accomplish this, but if it's necessary, you could change the gate's user resolver, which is responsible for finding users (by default it reads from Auth::user()).
Since the resolver is protected and has no setters, you'll need to modify it on creation. The gate is instantiated in Laravel's AuthServiceProvider. You can extend this class and replace the reference to it in the app.providers config with your subclass.
It's going to be up to you what kind of guest object to return (as long as it's truthy), but I'd probably use something like an empty User model:
protected function registerAccessGate()
{
$this->app->singleton(GateContract::class, function ($app) {
return new Gate($app, function () use ($app) {
$user = $app['auth']->user();
if ($user) {
return $user;
}
return new \App\User;
});
});
}
You could go a step further and set a special property on it like $user->isGuest, or even define a special guest class or constant.
Alternatively you could adjust your process at the Auth level so that all logged-out sessions are wrapped in a call to Auth::setUser($guestUserObject).
I just released a package that allows permission logic to be applied to guest users. It slightly modifies Laravel's Authorization to return a Guest object instead of null when no user is resolved. Also every authorization check now makes it to the Gate instead of failing authorization instantly because there isn't an authenticated user.
I am making a social website using Zend. The site allows users to become friends and access each other's profiles and blogs. I also want users to have control over their privacy, which can take parameters "Friends Only" and "Public". I looked at Zend_Acl but it seems to be only able to to handle single user's accessibility not users have relationship. Any ideas about the best way to do this?
For your purposes, if you use Zend_Acl, you should look at assertions.
Given the complex nature of the relationships between users in your applications, most of the access rules you will query seem very dynamic so they will largely rely on assertions that can use more complex logic to determine accessibility.
You should be able to accomplish what you want using Zend_Acl though.
You may set up an ACL rule like this:
$acl->allow('user', 'profile', 'view', new My_Acl_Assertion_UsersAreFriends());
The ACL assertion itself:
<?php
class My_Acl_Assertion_UsersAreFriends implements Zend_Acl_Assert_Interface
{
public function assert(Zend_Acl $acl,
Zend_Acl_Role_Interface $role = null,
Zend_Acl_Resource_Interface $resource = null,
$privilege = null)
{
return $this->_usersAreFriends();
}
protected function _usersAreFriends()
{
// get UserID of current logged in user
// assumes Zend_Auth has stored a User object of the logged in user
$user = Zend_Auth::getInstance()->getStorage();
$userId = $user->getId();
// get the ID of the user profile they are trying to view
// assume you can pull it from the URL
// or your controller or a plugin can set this value another way
$userToView = $this->getRequest()->getParam('id', null);
// call your function that checks the database for the friendship
$usersAreFriends = usersAreFriends($userId, $userToView);
return $usersAreFriends;
}
}
Now with this assertion in place, the access will be denied if the 2 user IDs are not friends.
Check it like:
if ($acl->isAllowed('user', 'profile', 'view')) {
// This will use the UsersAreFriends assertion
// they can view profile
} else {
// sorry, friend this person to view their profile
}
Hope that helps.
I can't get my Zend_Navigation to work properly,
When logging in user with AUth/Doctrine, I am pulling out the roles assigned to the user (usually it's a few of them) from a Many-to-many table,
Then in the bootstrap.php on line:
$view->navigation($navContainer)->setAcl($this->_acl)->setRole($this->_role);
I get error:
'$role must be a string, null, or an instance of Zend_Acl_Role_Interface; array given'
However if I loop through the roles with foreach - the previous roles are being overwritten by the following ones and I get the nav only for last role,
Does anyone have any logical solution for this ?
Really appreciate,
Adam
I had the same problem but approached the solution from a slightly different angle. Instead of modifying the Zend_Navigation object to accept two or more roles, I extended Zend_Acl and modified the isAllowed() method to check against all those roles. The Zend_Navigation objects use the isAllowed() method, so overriding this solved the issue.
My_Acl.php
<pre><code>
class My_Acl extends Zend_Acl
{
public function isAllowed($role = null, $resource = null, $privilege = null)
{
// Get all the roles to check against
$userRoles = Zend_Registry::get('aclUserRoles');
$isAllowed = false;
// Loop through them one by one and check if they're allowed
foreach ($userRoles as $role)
{
// Using the actual ACL isAllowed method here
if (parent::isAllowed($role->code, $resource))
{
$isAllowed = true;
}
}
return $isAllowed;
}
}
</code></pre>
Then, instead of creating an instance of Zend_Acl, use My_Acl, pass that to your navigation object and it should work.
You should really never, ever override isAllowed(), and yes there is a solution. Create a class that implements Zend_Acl_Role_Interface and if memory serves it requires defining a single method getRole(), this could, in fact, be your model that you use to authenticate a user against and allow that class to handle determining the role. A user should only have a single role. If access to the resource should be granted to users of multiple roles but only under certain conditions, then you should use an assertion, thats why they are there.
I have a CMS built on the Zend Framework. It uses Zend_Auth for "CMS User" authentication. CMS users have roles and permissions that are enforced with Zend_Acl. I am now trying to create "Site Users" for things like an online store. For simplicity sake I would like to use a separate instance of Zend_Auth for site users. Zend_Auth is written as a singleton, so I'm not sure how to accomplish this.
Reasons I don't want to accomplish this by roles:
Pollution of the CMS Users with Site Users (visitors)
A Site User could accidentally get elevated permissions
The users are more accurately defined as different types than different roles
The two user types are stored in separate databases/tables
One user of each type could be signed in simultaneously
Different types of information are needed for the two user types
Refactoring that would need to take place on existing code
In that case, you want to create your own 'Auth' class to extend and remove the 'singleton' design pattern that exists in Zend_Auth
This is by no means complete, but you can create an instance and pass it a 'namespace'. The rest of Zend_Auth's public methods should be fine for you.
<?php
class My_Auth extends Zend_Auth
{
public function __construct($namespace) {
$this->setStorage(new Zend_Auth_Storage_Session($namespace));
// do other stuff
}
static function getInstance() {
throw new Zend_Auth_Exception('I do not support getInstance');
}
}
Then where you want to use it, $auth = new My_Auth('CMSUser'); or $auth = new My_Auth('SiteUser');
class App_Auth
{
const DEFAULT_NS = 'default';
protected static $instance = array();
protected function __clone(){}
protected function __construct() {}
static function getInstance($namespace = self::DEFAULT_NS) {
if(!isset(self::$instance[$namespace]) || is_null(self::$instance[$namespace])) {
self::$instance[$namespace] = Zend_Auth::getInstance();
self::$instance[$namespace]->setStorage(new Zend_Auth_Storage_Session($namespace));
}
return self::$instance[$namespace];
}
}
Try this one , just will need to use App_Auth instead of Zend_Auth everywhere, or App_auth on admin's area, Zend_Auth on front
that is my suggestion :
i think you are in case that you should calculate ACL , recourses , roles dynamically ,
example {md5(siteuser or cmsuser + module + controller)= random number for each roles }
and a simple plugin would this role is allowed to this recourse
or you can build like unix permission style but i guess this idea need alot of testing
one day i will build one like it in ZF :)
i hope my idea helps you
You're mixing problems. (not that I didn't when I first faced id)
Zend_Auth answers the question "is that user who he claims to be"? What you can do is to add some more info to your persistence object. Easiest option is to add one more column into your DB and add it to result.