Symfony2, How to secure all controllers in one place using custom function? - security

I have defined my controller but I would like to secure ALL of them like below :
// In my Controller Class
public function chooseDateAction()
{
if($this->get('MY.roles_features')
->isGranted($this->container->get('request')->get('_route')))
{
// Do something
}
else
{
throw new AccessDeniedException();
}
return array( );
}
I had to design my own 'isGranted' function because roles are dynamic. BTW the function is working properly !
So my question is do I have to repeat the isGranted function in all of my Controllers or I can put it somewhere to reduce the code redundancy.
I know I have to place isGranted in some top level layer of my security, But the question is how and where ?

Try writing a base controller, which will check upon construction, if isGranted method passes, else throws exception. e.g.:
<?php
namespace Acme\DolanBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class BaseController extends Controller
{
public function __construct()
{
if(!$this->get('MY.roles_features')
->isGranted($this->container->get('request')->get('_route')))
{
throw new AccessDeniedException('Gooby pls');
}
}
}
Then just extend the BaseController in your other controllers.

Related

Get result of function in Laravel and add to another controller

I have this 1st controller.
class ValidatePassController extends Controller
{
protected function doShow(Post $post, Hash $hash)
{
return view('auth.cab.pcab');
}
}
I need to add if view was returned or something like that in the controller below.
class EditController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function xuibomja()
{
if (// in past controller view was returned))
{
return ('stassik');
}
return ('not stassik');
}
}
Any ideas? I have tried to set some vars, but it didn't work, so im out of ideas. Btw can't summary controllers to each other, codes needs to be in different controllers.
It's not the best practice to have a controller to call another controller.
what I recommend you to do is to create a class and move the functionality there, and create a facade to map to this class, and set both controllers to use that common functionality

Codeigniter 4 - call method from another controller

How to call "functionA" from "ClassA" in "functionB" inside "ClassB" ?
class Base extends BaseController
{
public function header()
{
echo view('common/header');
echo view('common/header-nav');
}
}
class Example extends BaseController
{
public function myfunction()
// how to call function header from base class
return view('internet/swiatlowod');
}
}
Well there are many ways to do this...
One such way, might be like...
Assume that example.php is the required Frontend so we will need a route to it.
In app\Config\Routes.php we need the entry
$routes->get('/example', 'Example::index');
This lets us use the URL your-site dot com/example
Now we need to decide how we want to use the functions in Base inside Example. So we could do the following...
<?php namespace App\Controllers;
class Example extends BaseController {
protected $base;
/**
* This is the main entry point for this example.
*/
public function index() {
$this->base = new Base(); // Create an instance
$this->myfunction();
}
public function myfunction() {
echo $this->base->header(); // Output from header
echo view('internet/swiatlowod'); // Output from local view
}
}
When and where you use new Base() is up to you, but you need to use before you need it (obviously).
You could do it in a constructor, you could do it in a parent class and extend it so it is common to a group of controllers.
It's up to you.

Symfony2 custom security voter not working

I implementend my own security voter for my symfony (2.6.1) based project. I did so following this blog entry: http://symfony.com/blog/new-in-symfony-2-6-simpler-security-voters and this documentation: http://symfony.com/doc/current/cookbook/security/voters_data_permission.html
My problem now is, that the method "isGranted" of my voter never gets called.
My voter class looks like this:
namespace AppBundle\SecurityVoter;
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter;
use Symfony\Component\Security\Core\User\UserInterface;
class FolderVoter extends AbstractVoter
{
const EDIT = 'edit';
protected function getSupportedClasses()
{
return array('\MyApp\Entity\Folder');
}
protected function getSupportedAttributes()
{
return array(self::EDIT);
}
protected function isGranted($attribute, $folder, $user = null)
{
if (!$user instanceof UserInterface) {
return false;
}
if ($folder->getUserId() == $user->getId()) {
return true;
}
return false;
}
}
The class is configured in the services.yml in the following way:
security.access.folder_voter:
class: AppBundle\SecurityVoter\FolderVoter
public: false
tags:
- { name: security.voter }
I'm using the method 'is_granted' from within a twig template. What did i miss to implement or what did i do wrong that it is not working ?
I just found the solution myself. It was pretty easy. But nasty in some way as well.
Insted of this:
protected function getSupportedClasses()
{
return array('\MyApp\Entity\Folder');
}
I had to declare the class name like this. So without the leading backslash:
protected function getSupportedClasses()
{
return array('MyApp\Entity\Folder');
}
Maybe this could be improved on the security voter implementation in general :-)

Using one Validator for multiple request DTOs? or multiple Validators for a single request DTO?

I have several ServiceStack request DTOs that implement an interface called IPageable. I have a validator that can validate the two properties that are on this interface. I think I'm going to end up having one validator per request type, but I'm trying to avoid having to duplicate that IPageable-related validation logic in all of them.
public class PageableValidator : AbstractValidator<IPageable>
{
public PageableValidator()
{
RuleFor(req => req.Page)
.GreaterThanOrEqualTo(1);
RuleFor(req => req.PageSize)
.GreaterThanOrEqualTo(1)
.When(req => req.Page > 1);
}
}
Some ideas I've had about this include:
It appears I can't just have container.RegisterValidators() apply
this to all request types that implement IPageable, but that was my
first thought.
can I specify multiple <Validator> attributes on all the request
definitions, so that both a request-specific validator runs, as well
as my IPageable validator?
can I specify at validator registration time that for all types
implementing IPageable, my IPageable validator should run?
can I write a base class for my request-specific validators that
gets the rules from my PageableValidator and includes / runs them?
I can make something sort of work by subclassing AbstractValidator<T> where T : IPageable , but I'd like to be able to do validation on more than one interface in more of an aspect-oriented way.
I don't know the answers to your questions but a few options came to mind to after reading your question.
I am not familiar with the <Validator> attribute, but in regards to question 2, you could create a Filter attribute that would run your paging validation. This allows you to use many attributes on your request and set their priority.
public class PageableValidator : Attribute, IHasRequestFilter
{
public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
{
if (requestDto is IPageable)
{
var validator = new PageableValidator(); //could use IOC for this
validator.ValidateAndThrow(requestDto as IPageable);
}
}
public IHasRequestFilter Copy()
{
return (IHasRequestFilter)this.MemberwiseClone();
}
public int Priority { get { return -1; //setting to negative value to run it before any other filters} }
}
Another option would be creating an abstract class for Paging validation. This would require a subclass for every Request and requires a bit more code and some repetition*. Though, depending on how you want to handle your error messages you could move the code around.
public abstract class PagerValidatorBase<T> : AbstractValidator<T>
{
public bool ValidatePage(IPageable instance, int page)
{
if (page >= 1)
return true;
return false;
}
public bool ValidatePageSize(IPageable instance, int pageSize)
{
if (pageSize >= 1 && instance.Page > 1)
return true;
return false;
}
}
public class SomeRequestValidator : PagerValidatorBase<SomeRequest>
{
public SomeRequestValidator()
{
//validation rules for SomeRequest
RuleFor(req => req.Page).Must(ValidatePage);
RuleFor(req => req.PageSize).Must(ValidatePageSize);
}
}
IMO, the repetition makes the code more explicit (not a bad thing) and is okay since it isn't duplicating the logic.

ViewHelper newable/injectable dilemma

I'm trying to design an application following Misko Heverys insights. It's an interesting experiment and a challenge. Currently I'm struggling with my ViewHelper implementation.
The ViewHelper decouples the model from the view. In my implementation it wraps the model and provides the API for the view to use. I'm using PHP, but I hope the implementation is readable for everyone:
class PostViewHelper {
private $postModel;
public function __construct(PostModel $postModel) {
$this->postModel = $postModel;
}
public function title() {
return $this->postModel->getTitle();
}
}
In my template (view) file this could be called like this:
<h1><?php echo $this->post->title(); ?></h1>
So far so good. The problem I have is when I want to attach a filter to the ViewHelpers. I want to have plugins that filter the output of the title() call. The method would become like this:
public function title() {
return $this->filter($this->postModel->getTitle());
}
I need to get observers in there, or an EventHandler, or whatever service (in what I see as a newable, so it needs to be passed in through the stack). How can I do this following the principles of Misko Hevery? I know how I can do this without it. I'm interested in how for I can take it and currently I don't see a solution. ViewHelper could be an injectable too, but then getting the model in there is the problem.
I didn't find the blog post you referenced very interesting or insightful.
What you are describing seems more like a Decorator than anything to do with dependency injection. Dependency injection is how you construct your object graphs, not their state once constructed.
That said, I'd suggest taking your Decorator pattern and running with it.
interface PostInterface
{
public function title();
}
class PostModel implements PostInterface
{
public function title()
{
return $this->title;
}
}
class PostViewHelper implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->post->title();
}
}
class PostFilter implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->filter($this->post->title());
}
protected function filter($str)
{
return "FILTERED:$str";
}
}
You'd simply use whatever DI framework you have to build this object graph like so:
$post = new PostFilter(new PostViewHelper($model)));
I often use this approach when building complex nested objects.
One problem you might run into is defining "too many" functions in your PostInterface. It can be a pain to have to implement these in every decorator class. I take advantage of the PHP magic functions to get around this.
interface PostInterface
{
/**
* Minimal interface. This is the accessor
* for the unique ID of this Post.
*/
public function getId();
}
class SomeDecoratedPost implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->_post = $post;
}
public function getId()
{
return $this->_post->getId();
}
/**
* The following magic functions proxy all
* calls back to the decorated Post
*/
public function __call($name, $arguments)
{
return call_user_func_array(array($this->_post, $name), $arguments);
}
public function __get($name)
{
return $this->_post->get($name);
}
public function __set($name, $value)
{
$this->_post->__set($name, $value);
}
public function __isset($name)
{
return $this->_post->__isset($name);
}
public function __unset($name)
{
$this->_post->__unset($name);
}
}
With this type of decorator in use, I can selectively override whatever method I need to provide the decorated functionality. Anything I don't override is passed back to the underlying object. Multiple decorations can occur all while maintaining the interface of the underlying object.

Resources